From 0dfa3b0cf640f4b95a3cdfdf8c32ae764d3ff5dd Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Thu, 20 Jun 2013 19:44:16 +0700 Subject: Initial commit --- .gitignore | 3 + build.xml | 71 +++ nbproject/ant-deploy.xml | 37 ++ nbproject/build-impl.xml | 1101 +++++++++++++++++++++++++++++++++++++ nbproject/genfiles.properties | 8 + nbproject/project.properties | 91 +++ nbproject/project.xml | 61 ++ src/conf/MANIFEST.MF | 2 + src/java/com/juick/api/Main.java | 145 +++++ src/java/com/juick/api/Users.java | 70 +++ src/java/com/juick/api/Utils.java | 130 +++++ web/META-INF/context.xml | 2 + web/WEB-INF/web.xml | 16 + 13 files changed, 1737 insertions(+) create mode 100644 .gitignore create mode 100644 build.xml create mode 100644 nbproject/ant-deploy.xml create mode 100644 nbproject/build-impl.xml create mode 100644 nbproject/genfiles.properties create mode 100644 nbproject/project.properties create mode 100644 nbproject/project.xml create mode 100644 src/conf/MANIFEST.MF create mode 100644 src/java/com/juick/api/Main.java create mode 100644 src/java/com/juick/api/Users.java create mode 100644 src/java/com/juick/api/Utils.java create mode 100644 web/META-INF/context.xml create mode 100644 web/WEB-INF/web.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..d3bae3d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/build/ +/dist/ +/nbproject/private/ \ No newline at end of file diff --git a/build.xml b/build.xml new file mode 100644 index 00000000..b1509601 --- /dev/null +++ b/build.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + Builds, tests, and runs the project com.juick.api. + + + diff --git a/nbproject/ant-deploy.xml b/nbproject/ant-deploy.xml new file mode 100644 index 00000000..cbfe67c3 --- /dev/null +++ b/nbproject/ant-deploy.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 00000000..00a25390 --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,1101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set build.web.dir + Must set build.generated.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.war + + + + + + + + + +The Java EE server classpath is not correctly set up - server home directory is missing. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Dj2ee.server.home=<app_server_installation_directory> + + +The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Duser.properties.file=<path_to_property_file> (where you put the property "j2ee.platform.classpath" in a .properties file) +or ant -Dj2ee.platform.classpath=<server_classpath> (where no properties file is used) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The libs.CopyLibs.classpath property is not set up. +This property must point to +org-netbeans-modules-java-j2seproject-copylibstask.jar file which is part +of NetBeans IDE installation and is usually located at +<netbeans_installation>/java<version>/ant/extra folder. +Either open the project in the IDE and make sure CopyLibs library +exists or setup the property manually. For example like this: + ant -Dlibs.CopyLibs.classpath=a/path/to/org-netbeans-modules-java-j2seproject-copylibstask.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.jsp.includes + + + + + + + + + + + + + + + + + + + + + + + + + + Must select a file in the IDE or set jsp.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Browser not found, cannot launch the deployed application. Try to set the BROWSER environment variable. + + + Launching ${browse.url} + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 00000000..fd5f8a0b --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=0970a525 +build.xml.script.CRC32=2226508e +build.xml.stylesheet.CRC32=651128d4@1.33.1.1 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=0970a525 +nbproject/build-impl.xml.script.CRC32=76130e45 +nbproject/build-impl.xml.stylesheet.CRC32=0cbf5bb7@1.33.1.1 diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 00000000..f54b89b4 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,91 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=true +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.web.dir}/WEB-INF/classes +build.classes.excludes=**/*.java,**/*.form +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +build.web.dir=${build.dir}/web +build.web.excludes=${build.classes.excludes} +client.urlPart= +compile.jsps=false +conf.dir=${source.root}/conf +debug.classpath=${build.classes.dir}:${javac.classpath} +debug.test.classpath=\ + ${run.test.classpath} +display.browser=true +dist.dir=dist +dist.ear.war=${dist.dir}/${war.ear.name} +dist.javadoc.dir=${dist.dir}/javadoc +dist.war=${dist.dir}/${war.name} +endorsed.classpath=\ + ${libs.javaee-endorsed-api-6.0.classpath} +excludes= +includes=** +j2ee.compile.on.save=true +j2ee.deploy.on.save=true +j2ee.platform=1.6-web +j2ee.platform.classpath=${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.home}/lib/tomcat-jdbc.jar:${j2ee.server.home}/lib/jasper-el.jar:${j2ee.server.home}/lib/tomcat-i18n-fr.jar:${j2ee.server.home}/lib/jsp-api.jar:${j2ee.server.home}/lib/catalina.jar:${j2ee.server.home}/lib/tomcat-i18n-ja.jar:${j2ee.server.home}/lib/el-api.jar:${j2ee.server.home}/lib/catalina-tribes.jar:${j2ee.server.home}/lib/tomcat-coyote.jar:${j2ee.server.home}/lib/ecj-3.7.1.jar:${j2ee.server.home}/lib/jasper.jar:${j2ee.server.home}/lib/tomcat-util.jar:${j2ee.server.home}/lib/tomcat-api.jar:${j2ee.server.home}/lib/tomcat-dbcp.jar:${j2ee.server.home}/lib/servlet-api.jar:${j2ee.server.home}/lib/tomcat-i18n-es.jar:${j2ee.server.home}/lib/catalina-ha.jar:${j2ee.server.home}/lib/annotations-api.jar +j2ee.server.type=Tomcat +jar.compress=false +javac.classpath=\ + ${libs.MySQLDriver.classpath}:\ + ${reference.com_juick.jar}:\ + ${reference.com_juick_server.jar}:\ + ${reference.com_juick_json.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.debug=true +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.preview=true +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +lib.dir=${web.docbase.dir}/WEB-INF/lib +no.dependencies=false +persistence.xml.dir=${conf.dir} +platform.active=default_platform +project.com_juick=../com.juick +project.com_juick_json=../com.juick.json +project.com_juick_server=../com.juick.server +reference.com_juick.jar=${project.com_juick}/dist/com.juick.jar +reference.com_juick_json.jar=${project.com_juick_json}/dist/com.juick.json.jar +reference.com_juick_server.jar=${project.com_juick_server}/dist/com.juick.server.jar +resource.dir=setup +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +# Space-separated list of JVM arguments used when running a class with a main method or a unit test +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value): +runmain.jvmargs= +source.encoding=UTF-8 +source.root=src +src.dir=${source.root}/java +test.src.dir=test +war.content.additional= +war.ear.name=com.juick.http.api.war +war.name=com.juick.http.api.war +web.docbase.dir=web +webinf.dir=web/WEB-INF diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 00000000..72915234 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,61 @@ + + + org.netbeans.modules.web.project + + + com.juick.api + 1.6.5 + + + ${libs.MySQLDriver.classpath} + WEB-INF/lib + + + ${reference.com_juick.jar} + WEB-INF/lib + + + ${reference.com_juick_server.jar} + WEB-INF/lib + + + ${reference.com_juick_json.jar} + WEB-INF/lib + + + + + + + + + + + + + com_juick + jar + + jar + clean + jar + + + com_juick_json + jar + + jar + clean + jar + + + com_juick_server + jar + + jar + clean + jar + + + + diff --git a/src/conf/MANIFEST.MF b/src/conf/MANIFEST.MF new file mode 100644 index 00000000..59499bce --- /dev/null +++ b/src/conf/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java new file mode 100644 index 00000000..d32a00aa --- /dev/null +++ b/src/java/com/juick/api/Main.java @@ -0,0 +1,145 @@ +/* + * Juick + * Copyright (C) 2008-2013, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.api; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author Ugnich Anton + */ +@WebServlet(name = "Main", urlPatterns = {"/"}) +public class Main extends HttpServlet { + + Connection sql; + Connection sqlSearch; + Users users; + + @Override + public void init() throws ServletException { + super.init(); + try { + Properties conf = new Properties(); + conf.load(new FileInputStream("/etc/juick/api.conf")); + + Class.forName("com.mysql.jdbc.Driver"); + sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); + sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password="); + + users = new Users(sql); + } catch (Exception e) { + log(null, e); + } + } + + @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 + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (request.getCharacterEncoding() == null) { + request.setCharacterEncoding("UTF-8"); + } + + int vuid = Utils.getHttpAuthUID(sql, request); + + String uri = request.getRequestURI(); + if (uri.equals("/users/read")) { + users.doGetUserRead(request, response, vuid); + } else if (uri.equals("/users/readers")) { + users.doGetUserReaders(request, response, vuid); + } else { + response.sendError(404); + } + } + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String uri = request.getRequestURI(); + if (uri.equals("/post")) { + } else { + response.sendError(405); + } + } + + 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", "*"); + + String callback = request.getParameter("callback"); + if (callback.length() > 64 || !callback.matches("a-zA-Z0-9\\-")) { + callback = null; + } + + PrintWriter out = response.getWriter(); + try { + if (callback != null) { + out.print(callback + "("); + out.print(json); + out.print(")"); + } else { + out.print(json); + } + } finally { + out.close(); + } + } +} diff --git a/src/java/com/juick/api/Users.java b/src/java/com/juick/api/Users.java new file mode 100644 index 00000000..5810ddba --- /dev/null +++ b/src/java/com/juick/api/Users.java @@ -0,0 +1,70 @@ +package com.juick.api; + +import com.juick.server.UserQueries; +import java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class Users { + + Connection sql; + + public Users(Connection sql) { + this.sql = sql; + } + + public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + int uid = vuid; + String paramUID = request.getParameter("user_id"); + if (paramUID != null) { + try { + uid = Integer.parseInt(paramUID); + } catch (NumberFormatException e) { + } + } + + if (uid > 0) { + ArrayList uids = UserQueries.getUserRead(sql, vuid); + if (uids.size() > 0) { + ArrayList users = UserQueries.getUsersByID(sql, uids); + if (users.size() > 0) { + String json = com.juick.json.Users.arrayToString(users); + Main.replyJSON(request, response, json); + return; + } + } + } + response.sendError(404); + } + + public void doGetUserReaders(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + int uid = vuid; + String paramUID = request.getParameter("user_id"); + if (paramUID != null) { + try { + uid = Integer.parseInt(paramUID); + } catch (NumberFormatException e) { + } + } + + if (uid > 0) { + ArrayList uids = UserQueries.getUserReaders(sql, vuid); + if (uids.size() > 0) { + ArrayList users = UserQueries.getUsersByID(sql, uids); + if (users.size() > 0) { + String json = com.juick.json.Users.arrayToString(users); + Main.replyJSON(request, response, json); + return; + } + } + } + response.sendError(404); + } +} diff --git a/src/java/com/juick/api/Utils.java b/src/java/com/juick/api/Utils.java new file mode 100644 index 00000000..b325b19a --- /dev/null +++ b/src/java/com/juick/api/Utils.java @@ -0,0 +1,130 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.api; + +import com.juick.server.UserQueries; +import java.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import sun.misc.BASE64Decoder; + +/** + * + * @author Ugnich Anton + */ +public class Utils { + + public static String getCookie(HttpServletRequest request, String name) { + Cookie cookies[] = request.getCookies(); + if (cookies != null) { + for (int i = 0; i < cookies.length; i++) { + if (cookies[i].getName().equals(name)) { + return cookies[i].getValue(); + } + } + } + return null; + } + + public static com.juick.User getVisitorUser(Connection sql, HttpServletRequest request) { + String hash = getCookie(request, "hash"); + if (hash != null) { + return com.juick.server.UserQueries.getUserByHash(sql, hash); + } else { + return null; + } + } + + public static int getVisitorUID(Connection sql, HttpServletRequest request) { + Cookie cookies[] = request.getCookies(); + if (cookies != null) { + for (int i = 0; i < cookies.length; i++) { + if (cookies[i].getName().equals("hash")) { + String hash = cookies[i].getValue(); + return com.juick.server.UserQueries.getUIDbyHash(sql, hash); + } + } + } + return 0; + } + + public static int getHttpAuthUID(Connection sql, HttpServletRequest request) { + String auth = request.getHeader("HTTP_AUTHORIZATION"); + if (auth != null && auth.length() > 8) { + try { + BASE64Decoder dec = new BASE64Decoder(); + String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2); + if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("a-zA-Z0-9\\-") && !loginpassw[1].isEmpty()) { + return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]); + } + } catch (IOException e) { + } + } + return 0; + } + + public static void sendPermanentRedirect(HttpServletResponse response, String location) { + response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); + response.setHeader("Location", location); + } + + public static void finishSQL(ResultSet rs, Statement stmt) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + } + } + } + + public static String convertArray2String(ArrayList mids) { + String q = ""; + for (int i = 0; i < mids.size(); i++) { + if (i > 0) { + q += ","; + } + q += mids.get(i); + } + return q; + } + + public static String encodeHTML(String str) { + String ret = str; + ret = ret.replaceAll("<", "<"); + ret = ret.replaceAll(">", ">"); + return str; + } + + public static String encodeSphinx(String str) { + String ret = str; + ret = ret.replaceAll("@", "\\\\@"); + return ret; + } +} diff --git a/web/META-INF/context.xml b/web/META-INF/context.xml new file mode 100644 index 00000000..5bee3dc3 --- /dev/null +++ b/web/META-INF/context.xml @@ -0,0 +1,2 @@ + + diff --git a/web/WEB-INF/web.xml b/web/WEB-INF/web.xml new file mode 100644 index 00000000..533a6882 --- /dev/null +++ b/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + Main + com.juick.api.Main + + + Main + / + + + + 30 + + + -- cgit v1.2.3 From df529650d03296bf03ade8c0eed4a2fcc404a041 Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Fri, 21 Jun 2013 00:16:11 +0700 Subject: Bugfix --- nbproject/build-impl.xml | 2 -- nbproject/genfiles.properties | 6 +++--- nbproject/project.properties | 5 ++--- nbproject/project.xml | 4 ---- src/java/com/juick/api/Main.java | 2 +- src/java/com/juick/api/Users.java | 36 ++++++++++++++++++++++-------------- src/java/com/juick/api/Utils.java | 2 +- 7 files changed, 29 insertions(+), 28 deletions(-) diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml index 00a25390..c6dd50e7 100644 --- a/nbproject/build-impl.xml +++ b/nbproject/build-impl.xml @@ -693,7 +693,6 @@ exists or setup the property manually. For example like this: - @@ -701,7 +700,6 @@ exists or setup the property manually. For example like this: - diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties index fd5f8a0b..0b047451 100644 --- a/nbproject/genfiles.properties +++ b/nbproject/genfiles.properties @@ -1,8 +1,8 @@ -build.xml.data.CRC32=0970a525 +build.xml.data.CRC32=649ef84a build.xml.script.CRC32=2226508e build.xml.stylesheet.CRC32=651128d4@1.33.1.1 # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=0970a525 -nbproject/build-impl.xml.script.CRC32=76130e45 +nbproject/build-impl.xml.data.CRC32=649ef84a +nbproject/build-impl.xml.script.CRC32=3499afe6 nbproject/build-impl.xml.stylesheet.CRC32=0cbf5bb7@1.33.1.1 diff --git a/nbproject/project.properties b/nbproject/project.properties index f54b89b4..5d65b1aa 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -34,7 +34,6 @@ j2ee.platform.classpath=${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.h j2ee.server.type=Tomcat jar.compress=false javac.classpath=\ - ${libs.MySQLDriver.classpath}:\ ${reference.com_juick.jar}:\ ${reference.com_juick_server.jar}:\ ${reference.com_juick_json.jar} @@ -85,7 +84,7 @@ source.root=src src.dir=${source.root}/java test.src.dir=test war.content.additional= -war.ear.name=com.juick.http.api.war -war.name=com.juick.http.api.war +war.ear.name=com.juick.api.war +war.name=com.juick.api.war web.docbase.dir=web webinf.dir=web/WEB-INF diff --git a/nbproject/project.xml b/nbproject/project.xml index 72915234..6d66c021 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -6,10 +6,6 @@ com.juick.api 1.6.5 - - ${libs.MySQLDriver.classpath} - WEB-INF/lib - ${reference.com_juick.jar} WEB-INF/lib diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index d32a00aa..ebbeb103 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -125,7 +125,7 @@ public class Main extends HttpServlet { response.setHeader("Access-Control-Allow-Origin", "*"); String callback = request.getParameter("callback"); - if (callback.length() > 64 || !callback.matches("a-zA-Z0-9\\-")) { + if (callback != null && (callback.length() > 64 || !callback.matches("[a-zA-Z0-9\\-]+"))) { callback = null; } diff --git a/src/java/com/juick/api/Users.java b/src/java/com/juick/api/Users.java index 5810ddba..2c60a95f 100644 --- a/src/java/com/juick/api/Users.java +++ b/src/java/com/juick/api/Users.java @@ -21,17 +21,21 @@ public class Users { } public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - int uid = vuid; - String paramUID = request.getParameter("user_id"); - if (paramUID != null) { - try { - uid = Integer.parseInt(paramUID); - } catch (NumberFormatException e) { + int uid = 0; + String uname = request.getParameter("uname"); + if (uname == null) { + uid = vuid; + } else { + if (UserQueries.checkUserNameValid(uname)) { + com.juick.User u = UserQueries.getUserByNick(sql, uname); + if (u != null && u.UID > 0) { + uid = u.UID; + } } } if (uid > 0) { - ArrayList uids = UserQueries.getUserRead(sql, vuid); + ArrayList uids = UserQueries.getUserRead(sql, uid); if (uids.size() > 0) { ArrayList users = UserQueries.getUsersByID(sql, uids); if (users.size() > 0) { @@ -45,17 +49,21 @@ public class Users { } public void doGetUserReaders(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - int uid = vuid; - String paramUID = request.getParameter("user_id"); - if (paramUID != null) { - try { - uid = Integer.parseInt(paramUID); - } catch (NumberFormatException e) { + int uid = 0; + String uname = request.getParameter("uname"); + if (uname == null) { + uid = vuid; + } else { + if (UserQueries.checkUserNameValid(uname)) { + com.juick.User u = UserQueries.getUserByNick(sql, uname); + if (u != null && u.UID > 0) { + uid = u.UID; + } } } if (uid > 0) { - ArrayList uids = UserQueries.getUserReaders(sql, vuid); + ArrayList uids = UserQueries.getUserReaders(sql, uid); if (uids.size() > 0) { ArrayList users = UserQueries.getUsersByID(sql, uids); if (users.size() > 0) { diff --git a/src/java/com/juick/api/Utils.java b/src/java/com/juick/api/Utils.java index b325b19a..cac5612d 100644 --- a/src/java/com/juick/api/Utils.java +++ b/src/java/com/juick/api/Utils.java @@ -75,7 +75,7 @@ public class Utils { try { BASE64Decoder dec = new BASE64Decoder(); String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2); - if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("a-zA-Z0-9\\-") && !loginpassw[1].isEmpty()) { + if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) { return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]); } } catch (IOException e) { -- cgit v1.2.3 From 4b1ef499dbd28c1639b9723ee2e9c5ff80002dde Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Mon, 22 Jul 2013 03:44:01 +0700 Subject: /users/ --- nbproject/build-impl.xml | 2 ++ nbproject/genfiles.properties | 6 ++--- nbproject/project.properties | 4 ++-- nbproject/project.xml | 8 +++++-- src/java/com/juick/api/Main.java | 4 +++- src/java/com/juick/api/Users.java | 46 +++++++++++++++++++++++++++++++++++++-- 6 files changed, 60 insertions(+), 10 deletions(-) diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml index c6dd50e7..965b7552 100644 --- a/nbproject/build-impl.xml +++ b/nbproject/build-impl.xml @@ -696,6 +696,7 @@ exists or setup the property manually. For example like this: + @@ -703,6 +704,7 @@ exists or setup the property manually. For example like this: + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties index 0b047451..13678348 100644 --- a/nbproject/genfiles.properties +++ b/nbproject/genfiles.properties @@ -1,8 +1,8 @@ -build.xml.data.CRC32=649ef84a +build.xml.data.CRC32=8cb2a940 build.xml.script.CRC32=2226508e build.xml.stylesheet.CRC32=651128d4@1.33.1.1 # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=649ef84a -nbproject/build-impl.xml.script.CRC32=3499afe6 +nbproject/build-impl.xml.data.CRC32=8cb2a940 +nbproject/build-impl.xml.script.CRC32=9918d740 nbproject/build-impl.xml.stylesheet.CRC32=0cbf5bb7@1.33.1.1 diff --git a/nbproject/project.properties b/nbproject/project.properties index 5d65b1aa..e57401a6 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -36,7 +36,8 @@ jar.compress=false javac.classpath=\ ${reference.com_juick.jar}:\ ${reference.com_juick_server.jar}:\ - ${reference.com_juick_json.jar} + ${reference.com_juick_json.jar}:\ + ${libs.JSON.classpath} # Space-separated list of extra javac options javac.compilerargs= javac.debug=true @@ -63,7 +64,6 @@ javadoc.use=true javadoc.version=false javadoc.windowtitle= lib.dir=${web.docbase.dir}/WEB-INF/lib -no.dependencies=false persistence.xml.dir=${conf.dir} platform.active=default_platform project.com_juick=../com.juick diff --git a/nbproject/project.xml b/nbproject/project.xml index 6d66c021..15c691a1 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -18,13 +18,17 @@ ${reference.com_juick_json.jar} WEB-INF/lib + + ${libs.JSON.classpath} + WEB-INF/lib + - + - + diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index ebbeb103..449c2a86 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -95,7 +95,9 @@ public class Main extends HttpServlet { int vuid = Utils.getHttpAuthUID(sql, request); String uri = request.getRequestURI(); - if (uri.equals("/users/read")) { + if (uri.equals("/users")) { + users.doGetUsers(request, response, vuid); + } else if (uri.equals("/users/read")) { users.doGetUserRead(request, response, vuid); } else if (uri.equals("/users/readers")) { users.doGetUserReaders(request, response, vuid); diff --git a/src/java/com/juick/api/Users.java b/src/java/com/juick/api/Users.java index 2c60a95f..cdd48fd6 100644 --- a/src/java/com/juick/api/Users.java +++ b/src/java/com/juick/api/Users.java @@ -1,9 +1,12 @@ package com.juick.api; +import com.juick.User; import com.juick.server.UserQueries; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -20,6 +23,45 @@ public class Users { this.sql = sql; } + public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + ArrayList users = new ArrayList(); + + String punames[] = request.getParameterValues("uname"); + if (punames != null) { + ArrayList unames = new ArrayList(Arrays.asList(punames)); + Iterator i = unames.iterator(); + while (i.hasNext()) { + if (!i.next().matches("^[a-zA-Z0-9\\-]{2,16}$")) { + i.remove(); + } + } + if (!unames.isEmpty() && unames.size() < 20) { + users.addAll(UserQueries.getUsersByName(sql, unames)); + } + } + + String pjids[] = request.getParameterValues("jid"); + if (pjids != null) { + ArrayList jids = new ArrayList(Arrays.asList(pjids)); + Iterator ii = jids.iterator(); + while (ii.hasNext()) { + if (!ii.next().matches("^[a-zA-Z0-9\\-\\_\\@\\.]{6,64}$")) { + ii.remove(); + } + } + if (!jids.isEmpty() && jids.size() < 20) { + users.addAll(UserQueries.getUsersByJID(sql, jids)); + } + } + + if (!users.isEmpty()) { + String json = com.juick.json.Users.arrayToString(users); + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } + public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { int uid = 0; String uname = request.getParameter("uname"); @@ -27,7 +69,7 @@ public class Users { uid = vuid; } else { if (UserQueries.checkUserNameValid(uname)) { - com.juick.User u = UserQueries.getUserByNick(sql, uname); + com.juick.User u = UserQueries.getUserByName(sql, uname); if (u != null && u.UID > 0) { uid = u.UID; } @@ -55,7 +97,7 @@ public class Users { uid = vuid; } else { if (UserQueries.checkUserNameValid(uname)) { - com.juick.User u = UserQueries.getUserByNick(sql, uname); + com.juick.User u = UserQueries.getUserByName(sql, uname); if (u != null && u.UID > 0) { uid = u.UID; } -- cgit v1.2.3 From 91bf74631157d8e559686ca25e4980f155d88438 Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Fri, 30 Aug 2013 13:10:14 +0700 Subject: PM --- lib/xpp3_min-1.1.4.jar | Bin 0 -> 24955 bytes nbproject/build-impl.xml | 11 ++++ nbproject/genfiles.properties | 6 +-- nbproject/project.properties | 8 ++- nbproject/project.xml | 16 ++++++ src/java/com/juick/api/Main.java | 75 ++++++++++++++++++++++++++- src/java/com/juick/api/Others.java | 45 ++++++++++++++++ src/java/com/juick/api/PM.java | 102 +++++++++++++++++++++++++++++++++++++ src/java/com/juick/api/Utils.java | 12 ++++- 9 files changed, 266 insertions(+), 9 deletions(-) create mode 100644 lib/xpp3_min-1.1.4.jar create mode 100644 src/java/com/juick/api/Others.java create mode 100644 src/java/com/juick/api/PM.java diff --git a/lib/xpp3_min-1.1.4.jar b/lib/xpp3_min-1.1.4.jar new file mode 100644 index 00000000..e02ea412 Binary files /dev/null and b/lib/xpp3_min-1.1.4.jar differ diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml index 965b7552..7fcc9e67 100644 --- a/nbproject/build-impl.xml +++ b/nbproject/build-impl.xml @@ -538,6 +538,9 @@ exists or setup the property manually. For example like this: + + + @@ -549,6 +552,9 @@ exists or setup the property manually. For example like this: + + + @@ -696,7 +702,9 @@ exists or setup the property manually. For example like this: + + @@ -704,7 +712,9 @@ exists or setup the property manually. For example like this: + + @@ -1072,6 +1082,7 @@ exists or setup the property manually. For example like this: + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties index 13678348..9fa27ff1 100644 --- a/nbproject/genfiles.properties +++ b/nbproject/genfiles.properties @@ -1,8 +1,8 @@ -build.xml.data.CRC32=8cb2a940 +build.xml.data.CRC32=0e286cb1 build.xml.script.CRC32=2226508e build.xml.stylesheet.CRC32=651128d4@1.33.1.1 # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=8cb2a940 -nbproject/build-impl.xml.script.CRC32=9918d740 +nbproject/build-impl.xml.data.CRC32=0e286cb1 +nbproject/build-impl.xml.script.CRC32=4228b93d nbproject/build-impl.xml.stylesheet.CRC32=0cbf5bb7@1.33.1.1 diff --git a/nbproject/project.properties b/nbproject/project.properties index e57401a6..92f560c4 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -1,6 +1,5 @@ annotation.processing.enabled=true annotation.processing.enabled.in.editor=true -annotation.processing.processors.list= annotation.processing.run.all.processors=true annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output build.classes.dir=${build.web.dir}/WEB-INF/classes @@ -26,6 +25,7 @@ dist.war=${dist.dir}/${war.name} endorsed.classpath=\ ${libs.javaee-endorsed-api-6.0.classpath} excludes= +file.reference.xpp3_min-1.1.4.jar=lib/xpp3_min-1.1.4.jar includes=** j2ee.compile.on.save=true j2ee.deploy.on.save=true @@ -37,7 +37,9 @@ javac.classpath=\ ${reference.com_juick.jar}:\ ${reference.com_juick_server.jar}:\ ${reference.com_juick_json.jar}:\ - ${libs.JSON.classpath} + ${reference.com_juick_xmpp.jar}:\ + ${libs.JSON.classpath}:\ + ${file.reference.xpp3_min-1.1.4.jar} # Space-separated list of extra javac options javac.compilerargs= javac.debug=true @@ -69,9 +71,11 @@ platform.active=default_platform project.com_juick=../com.juick project.com_juick_json=../com.juick.json project.com_juick_server=../com.juick.server +project.com_juick_xmpp=../com.juick.xmpp reference.com_juick.jar=${project.com_juick}/dist/com.juick.jar reference.com_juick_json.jar=${project.com_juick_json}/dist/com.juick.json.jar reference.com_juick_server.jar=${project.com_juick_server}/dist/com.juick.server.jar +reference.com_juick_xmpp.jar=${project.com_juick_xmpp}/dist/com.juick.xmpp.jar resource.dir=setup run.test.classpath=\ ${javac.test.classpath}:\ diff --git a/nbproject/project.xml b/nbproject/project.xml index 15c691a1..01e2f8c9 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -18,10 +18,18 @@ ${reference.com_juick_json.jar} WEB-INF/lib + + ${reference.com_juick_xmpp.jar} + WEB-INF/lib + ${libs.JSON.classpath} WEB-INF/lib + + ${file.reference.xpp3_min-1.1.4.jar} + WEB-INF/lib + @@ -56,6 +64,14 @@ clean jar + + com_juick_xmpp + jar + + jar + clean + jar + diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index 449c2a86..718ca249 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -17,9 +17,13 @@ */ package com.juick.api; +import com.juick.xmpp.JID; +import com.juick.xmpp.Stream; +import com.juick.xmpp.StreamComponent; 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; @@ -35,11 +39,14 @@ import javax.servlet.http.HttpServletResponse; * @author Ugnich Anton */ @WebServlet(name = "Main", urlPatterns = {"/"}) -public class Main extends HttpServlet { +public class Main extends HttpServlet implements Stream.StreamListener { Connection sql; Connection sqlSearch; + Stream xmpp; Users users; + PM pm; + Others others; @Override public void init() throws ServletException { @@ -53,11 +60,44 @@ public class Main extends HttpServlet { sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password="); users = new Users(sql); + pm = new PM(sql); + others = new Others(sql); + + setupXmppComponent(conf.getProperty("xmpp_password")); + } catch (Exception e) { log(null, e); } } + public void setupXmppComponent(final String password) { + Thread thr = new Thread(new Runnable() { + + @Override + public void run() { + try { + Socket socket = new Socket("localhost", 5347); + xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password); + xmpp.addListener(Main.this); + xmpp.startParsing(); + } catch (IOException e) { + System.err.println(e); + } + } + }); + thr.start(); + } + + @Override + public void onStreamFail(String msg) { + System.err.println("XMPP STREAM FAIL: " + msg); + } + + @Override + public void onStreamReady() { + System.err.println("XMPP STREAM READY"); + } + @Override public void destroy() { super.destroy(); @@ -93,6 +133,9 @@ public class Main extends HttpServlet { } int vuid = Utils.getHttpAuthUID(sql, request); + if (vuid == 0) { + vuid = Utils.getVisitorQueryStringUID(sql, request); + } String uri = request.getRequestURI(); if (uri.equals("/users")) { @@ -101,6 +144,18 @@ public class Main extends HttpServlet { users.doGetUserRead(request, response, vuid); } else if (uri.equals("/users/readers")) { users.doGetUserReaders(request, response, vuid); + } else if (uri.equals("/pm")) { + if (vuid > 0) { + pm.doGetPM(request, response, vuid); + } else { + response.sendError(401); + } + } else if (uri.equals("/groups_pms")) { + if (vuid > 0) { + others.doGetGroupsPMs(request, response, vuid); + } else { + response.sendError(401); + } } else { response.sendError(404); } @@ -115,8 +170,24 @@ public class Main extends HttpServlet { */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (request.getCharacterEncoding() == null) { + request.setCharacterEncoding("UTF-8"); + } + + int vuid = Utils.getHttpAuthUID(sql, request); + if (vuid == 0) { + vuid = Utils.getVisitorQueryStringUID(sql, request); + } + + String uri = request.getRequestURI(); if (uri.equals("/post")) { + } else if (uri.equals("/pm")) { + if (vuid > 0) { + pm.doPostPM(request, response, xmpp, vuid); + } else { + response.sendError(401); + } } else { response.sendError(405); } @@ -127,7 +198,7 @@ public class Main extends HttpServlet { response.setHeader("Access-Control-Allow-Origin", "*"); String callback = request.getParameter("callback"); - if (callback != null && (callback.length() > 64 || !callback.matches("[a-zA-Z0-9\\-]+"))) { + if (callback != null && (callback.length() > 64 || !callback.matches("[a-zA-Z0-9\\-\\_]+"))) { callback = null; } diff --git a/src/java/com/juick/api/Others.java b/src/java/com/juick/api/Others.java new file mode 100644 index 00000000..25df5bf4 --- /dev/null +++ b/src/java/com/juick/api/Others.java @@ -0,0 +1,45 @@ +package com.juick.api; + +import com.juick.server.PMQueries; +import java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class Others { + + Connection sql; + + public Others(Connection sql) { + this.sql = sql; + } + + public void doGetGroupsPMs(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + int cnt = 5; + try { + String cntStr = request.getParameter("cnt"); + cnt = Integer.parseInt(cntStr); + if (cnt < 3) { + cnt = 3; + } + if (cnt > 10) { + cnt = 10; + } + } catch (Exception e) { + } + + ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt); + if (lastconv != null && !lastconv.isEmpty()) { + String json = "{\"pms\":" + com.juick.json.Users.arrayToString(lastconv) + "}"; + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } +} diff --git a/src/java/com/juick/api/PM.java b/src/java/com/juick/api/PM.java new file mode 100644 index 00000000..285f9ff6 --- /dev/null +++ b/src/java/com/juick/api/PM.java @@ -0,0 +1,102 @@ +package com.juick.api; + +import com.juick.server.PMQueries; +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 java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class PM { + + Connection sql; + + public PM(Connection sql) { + this.sql = sql; + } + + 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}$")) { + uid = UserQueries.getUIDbyName(sql, uname); + } + + if (uid == 0) { + response.sendError(400); + return; + } + + ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid); + if (msgs != null && !msgs.isEmpty()) { + String json = com.juick.json.Messages.arrayToString(msgs); + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } + + 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)) { + uid = UserQueries.getUIDbyName(sql, uname); + } + + String body = request.getParameter("body"); + if (uid == 0 || body == null || body.length() < 1 || body.length() > 10240) { + response.sendError(400); + return; + } + + if (UserQueries.isInBL(sql, uid, vuid)) { + response.sendError(403); + return; + } + + if (PMQueries.createPM(sql, vuid, uid, body)) { + Main.replyJSON(request, response, ""); + + Message msg = new Message(); + 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; + msg.childs.add(jmsg); + System.out.println("MESSAGE: " + msg); + xmpp.send(msg); + + msg.to.Host = "ws.juick.com"; + xmpp.send(msg); + + String jid = UserQueries.getJIDbyUID(sql, uid); + if (jid != null) { + Message mm = new Message(); + 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.body = body; + } else { + mm.from = new JID("juick", "juick.com", "Juick"); + mm.body = "Private message from @" + jmsg.User.UName + ":\n" + body; + } + xmpp.send(mm); + } + + } else { + response.sendError(500); + } + } +} diff --git a/src/java/com/juick/api/Utils.java b/src/java/com/juick/api/Utils.java index cac5612d..b406c362 100644 --- a/src/java/com/juick/api/Utils.java +++ b/src/java/com/juick/api/Utils.java @@ -70,8 +70,8 @@ public class Utils { } public static int getHttpAuthUID(Connection sql, HttpServletRequest request) { - String auth = request.getHeader("HTTP_AUTHORIZATION"); - if (auth != null && auth.length() > 8) { + String auth = request.getHeader("Authorization"); + if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) { try { BASE64Decoder dec = new BASE64Decoder(); String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2); @@ -84,6 +84,14 @@ public class Utils { return 0; } + public static int getVisitorQueryStringUID(Connection sql, HttpServletRequest request) { + String hash = request.getParameter("hash"); + if (hash != null && hash.length() == 16) { + return com.juick.server.UserQueries.getUIDbyHash(sql, hash); + } + return 0; + } + public static void sendPermanentRedirect(HttpServletResponse response, String location) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", location); -- cgit v1.2.3 From 211edb389dcf5912b02346869264ea5dcd4cf75e Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Sat, 16 Nov 2013 03:22:57 +0700 Subject: Messages.doGetHome --- src/java/com/juick/api/Main.java | 10 ++++++++- src/java/com/juick/api/Messages.java | 39 ++++++++++++++++++++++++++++++++++++ src/java/com/juick/api/PM.java | 6 +++--- src/java/com/juick/api/Utils.java | 11 ++++++++++ 4 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 src/java/com/juick/api/Messages.java diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index 718ca249..38716282 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -44,6 +44,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { Connection sql; Connection sqlSearch; Stream xmpp; + Messages messages; Users users; PM pm; Others others; @@ -59,6 +60,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { 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); @@ -138,7 +140,13 @@ public class Main extends HttpServlet implements Stream.StreamListener { } String uri = request.getRequestURI(); - if (uri.equals("/users")) { + if (uri.equals("/home")) { + if (vuid > 0) { + messages.doGetHome(request, response, vuid); + } else { + response.sendError(401); + } + } else if (uri.equals("/users")) { users.doGetUsers(request, response, vuid); } else if (uri.equals("/users/read")) { users.doGetUserRead(request, response, vuid); diff --git a/src/java/com/juick/api/Messages.java b/src/java/com/juick/api/Messages.java new file mode 100644 index 00000000..5ecf503f --- /dev/null +++ b/src/java/com/juick/api/Messages.java @@ -0,0 +1,39 @@ +package com.juick.api; + +import com.juick.server.MessagesQueries; +import java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class Messages { + + Connection sql; + + public Messages(Connection 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); + + ArrayList mids = MessagesQueries.getMyFeed(sql, vuid, before_mid); + if (mids != null && !mids.isEmpty()) { + ArrayList msgs = MessagesQueries.getMessages(sql, mids); + if (msgs != null && !msgs.isEmpty()) { + String json = com.juick.json.Messages.arrayToString(msgs); + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } else { + response.sendError(404); + } + } +} diff --git a/src/java/com/juick/api/PM.java b/src/java/com/juick/api/PM.java index 285f9ff6..700f1665 100644 --- a/src/java/com/juick/api/PM.java +++ b/src/java/com/juick/api/PM.java @@ -59,14 +59,12 @@ public class PM { return; } - if (UserQueries.isInBL(sql, uid, vuid)) { + if (UserQueries.isInBL(sql, uid, vuid) || UserQueries.isInBL(sql, vuid, uid)) { response.sendError(403); return; } if (PMQueries.createPM(sql, vuid, uid, body)) { - Main.replyJSON(request, response, ""); - Message msg = new Message(); msg.from = new JID("juick", "juick.com", null); msg.to = new JID(Integer.toString(uid), "push.juick.com", null); @@ -80,6 +78,8 @@ public class PM { msg.to.Host = "ws.juick.com"; xmpp.send(msg); + Main.replyJSON(request, response, com.juick.json.Message.toJSON(jmsg).toString()); + String jid = UserQueries.getJIDbyUID(sql, uid); if (jid != null) { Message mm = new Message(); diff --git a/src/java/com/juick/api/Utils.java b/src/java/com/juick/api/Utils.java index b406c362..10e0cccb 100644 --- a/src/java/com/juick/api/Utils.java +++ b/src/java/com/juick/api/Utils.java @@ -135,4 +135,15 @@ public class Utils { ret = ret.replaceAll("@", "\\\\@"); return ret; } + + public static int parseInt(String str, int def) { + int ret = def; + if (str != null) { + try { + ret = Integer.parseInt(str); + } catch (Exception e) { + } + } + return ret; + } } -- cgit v1.2.3 From 64641073d2a9aa3a9e64a67c91558d5708462260 Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Tue, 19 Nov 2013 08:51:49 +0700 Subject: -debug println --- src/java/com/juick/api/PM.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/java/com/juick/api/PM.java b/src/java/com/juick/api/PM.java index 700f1665..d279d9e3 100644 --- a/src/java/com/juick/api/PM.java +++ b/src/java/com/juick/api/PM.java @@ -72,7 +72,6 @@ public class PM { jmsg.User = UserQueries.getUserByUID(sql, vuid); jmsg.Text = body; msg.childs.add(jmsg); - System.out.println("MESSAGE: " + msg); xmpp.send(msg); msg.to.Host = "ws.juick.com"; -- cgit v1.2.3 From 74f0e662697a05d30b5ac1cec6d1ffeaae14bf5f Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Fri, 24 Jan 2014 19:19:31 +0700 Subject: Tomcat upgrade, small fixes --- nbproject/project.properties | 2 +- src/java/com/juick/api/Main.java | 13 +++++++------ src/java/com/juick/api/PM.java | 2 +- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/nbproject/project.properties b/nbproject/project.properties index 92f560c4..9991f39f 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -30,7 +30,7 @@ includes=** j2ee.compile.on.save=true j2ee.deploy.on.save=true j2ee.platform=1.6-web -j2ee.platform.classpath=${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.home}/lib/tomcat-jdbc.jar:${j2ee.server.home}/lib/jasper-el.jar:${j2ee.server.home}/lib/tomcat-i18n-fr.jar:${j2ee.server.home}/lib/jsp-api.jar:${j2ee.server.home}/lib/catalina.jar:${j2ee.server.home}/lib/tomcat-i18n-ja.jar:${j2ee.server.home}/lib/el-api.jar:${j2ee.server.home}/lib/catalina-tribes.jar:${j2ee.server.home}/lib/tomcat-coyote.jar:${j2ee.server.home}/lib/ecj-3.7.1.jar:${j2ee.server.home}/lib/jasper.jar:${j2ee.server.home}/lib/tomcat-util.jar:${j2ee.server.home}/lib/tomcat-api.jar:${j2ee.server.home}/lib/tomcat-dbcp.jar:${j2ee.server.home}/lib/servlet-api.jar:${j2ee.server.home}/lib/tomcat-i18n-es.jar:${j2ee.server.home}/lib/catalina-ha.jar:${j2ee.server.home}/lib/annotations-api.jar +j2ee.platform.classpath=${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.home}/lib/tomcat-jdbc.jar:${j2ee.server.home}/lib/jasper-el.jar:${j2ee.server.home}/lib/tomcat-i18n-fr.jar:${j2ee.server.home}/lib/tomcat7-websocket.jar:${j2ee.server.home}/lib/jsp-api.jar:${j2ee.server.home}/lib/catalina.jar:${j2ee.server.home}/lib/ecj-4.2.2.jar:${j2ee.server.home}/lib/tomcat-i18n-ja.jar:${j2ee.server.home}/lib/websocket-api.jar:${j2ee.server.home}/lib/el-api.jar:${j2ee.server.home}/lib/catalina-tribes.jar:${j2ee.server.home}/lib/tomcat-coyote.jar:${j2ee.server.home}/lib/jasper.jar:${j2ee.server.home}/lib/tomcat-util.jar:${j2ee.server.home}/lib/tomcat-api.jar:${j2ee.server.home}/lib/tomcat-dbcp.jar:${j2ee.server.home}/lib/servlet-api.jar:${j2ee.server.home}/lib/tomcat-i18n-es.jar:${j2ee.server.home}/lib/catalina-ha.jar:${j2ee.server.home}/lib/annotations-api.jar j2ee.server.type=Tomcat jar.compress=false javac.classpath=\ diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index 38716282..9e0b8523 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -29,6 +29,7 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import javax.servlet.ServletException; +import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -39,6 +40,7 @@ import javax.servlet.http.HttpServletResponse; * @author Ugnich Anton */ @WebServlet(name = "Main", urlPatterns = {"/"}) +@MultipartConfig public class Main extends HttpServlet implements Stream.StreamListener { Connection sql; @@ -186,16 +188,15 @@ public class Main extends HttpServlet implements Stream.StreamListener { if (vuid == 0) { vuid = Utils.getVisitorQueryStringUID(sql, request); } - + if (vuid == 0) { + response.sendError(401); + return; + } String uri = request.getRequestURI(); if (uri.equals("/post")) { } else if (uri.equals("/pm")) { - if (vuid > 0) { - pm.doPostPM(request, response, xmpp, vuid); - } else { - response.sendError(401); - } + pm.doPostPM(request, response, xmpp, vuid); } else { response.sendError(405); } diff --git a/src/java/com/juick/api/PM.java b/src/java/com/juick/api/PM.java index d279d9e3..2722526d 100644 --- a/src/java/com/juick/api/PM.java +++ b/src/java/com/juick/api/PM.java @@ -59,7 +59,7 @@ public class PM { return; } - if (UserQueries.isInBL(sql, uid, vuid) || UserQueries.isInBL(sql, vuid, uid)) { + if (UserQueries.isInBLAny(sql, uid, vuid)) { response.sendError(403); return; } -- cgit v1.2.3 From ebbd16e1553d25dcd1135c4b3a3a9279f4509844 Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Sun, 9 Mar 2014 01:12:56 +0700 Subject: Messages.doSetPopular --- nbproject/project.properties | 1 + src/java/com/juick/api/Main.java | 2 ++ src/java/com/juick/api/Messages.java | 10 ++++++++++ 3 files changed, 13 insertions(+) diff --git a/nbproject/project.properties b/nbproject/project.properties index 9991f39f..b3480c49 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -1,5 +1,6 @@ annotation.processing.enabled=true annotation.processing.enabled.in.editor=true +annotation.processing.processors.list= annotation.processing.run.all.processors=true annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output build.classes.dir=${build.web.dir}/WEB-INF/classes diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index 9e0b8523..c4fe911e 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -166,6 +166,8 @@ public class Main extends HttpServlet implements Stream.StreamListener { } else { response.sendError(401); } + } else if (uri.equals("/messages/set_popular") && vuid == 1) { + messages.doSetPopular(request, response); } else { response.sendError(404); } diff --git a/src/java/com/juick/api/Messages.java b/src/java/com/juick/api/Messages.java index 5ecf503f..3aeede68 100644 --- a/src/java/com/juick/api/Messages.java +++ b/src/java/com/juick/api/Messages.java @@ -36,4 +36,14 @@ public class Messages { response.sendError(404); } } + + public void doSetPopular(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + int mid = Utils.parseInt(request.getParameter("mid"), 0); + int popular = Utils.parseInt(request.getParameter("popular"), 0); + + if (mid > 0) { + MessagesQueries.setMessagePopular(sql, mid, popular); + Main.replyJSON(request, response, "{\"status\":\"ok\"}"); + } + } } -- cgit v1.2.3 From b9de1e4cf886ee5b0fbd7025e2cf0fee6166d2ce Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Thu, 20 Mar 2014 02:36:35 +0700 Subject: Messages.doSetPopular crosspost --- src/java/com/juick/api/Main.java | 2 +- src/java/com/juick/api/Messages.java | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index c4fe911e..71b70839 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -167,7 +167,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { response.sendError(401); } } else if (uri.equals("/messages/set_popular") && vuid == 1) { - messages.doSetPopular(request, response); + messages.doSetPopular(request, response, xmpp); } else { response.sendError(404); } diff --git a/src/java/com/juick/api/Messages.java b/src/java/com/juick/api/Messages.java index 3aeede68..b7d0891e 100644 --- a/src/java/com/juick/api/Messages.java +++ b/src/java/com/juick/api/Messages.java @@ -1,6 +1,10 @@ package com.juick.api; import com.juick.server.MessagesQueries; +import com.juick.xmpp.JID; +import com.juick.xmpp.Message; +import com.juick.xmpp.Stream; +import com.juick.xmpp.extensions.JuickMessage; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; @@ -37,12 +41,38 @@ public class Messages { } } - public void doSetPopular(HttpServletRequest request, HttpServletResponse response) 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); if (mid > 0) { - MessagesQueries.setMessagePopular(sql, mid, popular); + boolean ret = MessagesQueries.setMessagePopular(sql, mid, popular); + + if (ret && popular == 2) { + try { + com.juick.Message m = MessagesQueries.getMessage(sql, mid); + if (m != null) { + Message msg = new Message(); + 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; + msg.childs.add(jmsg); + + msg.to.Username = "twitter"; + xmpp.send(msg); + msg.to.Username = "fb"; + xmpp.send(msg); + msg.to.Username = "vk"; + xmpp.send(msg); + } else { + throw new Exception("Message not found"); + } + } catch (Exception e) { + System.err.println("SETPOPULAR ERROR: " + e.toString()); + } + } + Main.replyJSON(request, response, "{\"status\":\"ok\"}"); } } -- cgit v1.2.3 From 0742847f430b02d2d9031f1a11799ac7076e9e26 Mon Sep 17 00:00:00 2001 From: Ugnich Anton Date: Tue, 5 Aug 2014 04:49:24 +0700 Subject: Messages.setPrivacy --- src/java/com/juick/api/Main.java | 2 ++ src/java/com/juick/api/Messages.java | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java index 71b70839..5ee4027b 100644 --- a/src/java/com/juick/api/Main.java +++ b/src/java/com/juick/api/Main.java @@ -168,6 +168,8 @@ public class Main extends HttpServlet implements Stream.StreamListener { } } else if (uri.equals("/messages/set_popular") && vuid == 1) { messages.doSetPopular(request, response, xmpp); + } else if (uri.equals("/messages/set_privacy") && vuid > 0) { + messages.doSetPrivacy(request, response, xmpp, vuid); } else { response.sendError(404); } diff --git a/src/java/com/juick/api/Messages.java b/src/java/com/juick/api/Messages.java index b7d0891e..b5462258 100644 --- a/src/java/com/juick/api/Messages.java +++ b/src/java/com/juick/api/Messages.java @@ -41,6 +41,16 @@ public class Messages { } } + 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)) { + 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 popular = Utils.parseInt(request.getParameter("popular"), 0); -- cgit v1.2.3 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 --- .gitignore | 9 +- .gitmodules | 12 + build.gradle | 67 ++ build.xml | 71 -- deps/com.juick | 1 + deps/com.juick.json | 1 + deps/com.juick.server | 1 + deps/com.juick.xmpp | 1 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 53637 bytes gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 160 +++++ gradlew.bat | 90 +++ lib/xpp3_min-1.1.4.jar | Bin 24955 -> 0 bytes nbproject/ant-deploy.xml | 37 - nbproject/build-impl.xml | 1112 ----------------------------- nbproject/genfiles.properties | 8 - nbproject/project.properties | 95 --- nbproject/project.xml | 77 -- settings.gradle | 1 + src/conf/MANIFEST.MF | 2 - src/java/com/juick/api/Main.java | 231 ------ src/java/com/juick/api/Messages.java | 89 --- src/java/com/juick/api/Others.java | 45 -- src/java/com/juick/api/PM.java | 101 --- src/java/com/juick/api/Users.java | 120 ---- src/java/com/juick/api/Utils.java | 149 ---- src/main/java/com/juick/api/Main.java | 231 ++++++ src/main/java/com/juick/api/Messages.java | 89 +++ src/main/java/com/juick/api/Others.java | 45 ++ src/main/java/com/juick/api/PM.java | 101 +++ src/main/java/com/juick/api/Users.java | 120 ++++ src/main/java/com/juick/api/Utils.java | 149 ++++ src/main/webapp/WEB-INF/web.xml | 16 + web/META-INF/context.xml | 2 - web/WEB-INF/web.xml | 16 - 35 files changed, 1097 insertions(+), 2158 deletions(-) create mode 100644 .gitmodules create mode 100644 build.gradle delete mode 100644 build.xml 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 create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat delete mode 100644 lib/xpp3_min-1.1.4.jar delete mode 100644 nbproject/ant-deploy.xml delete mode 100644 nbproject/build-impl.xml delete mode 100644 nbproject/genfiles.properties delete mode 100644 nbproject/project.properties delete mode 100644 nbproject/project.xml create mode 100644 settings.gradle delete mode 100644 src/conf/MANIFEST.MF delete mode 100644 src/java/com/juick/api/Main.java delete mode 100644 src/java/com/juick/api/Messages.java delete mode 100644 src/java/com/juick/api/Others.java delete mode 100644 src/java/com/juick/api/PM.java delete mode 100644 src/java/com/juick/api/Users.java delete mode 100644 src/java/com/juick/api/Utils.java create mode 100644 src/main/java/com/juick/api/Main.java create mode 100644 src/main/java/com/juick/api/Messages.java create mode 100644 src/main/java/com/juick/api/Others.java create mode 100644 src/main/java/com/juick/api/PM.java create mode 100644 src/main/java/com/juick/api/Users.java create mode 100644 src/main/java/com/juick/api/Utils.java create mode 100644 src/main/webapp/WEB-INF/web.xml delete mode 100644 web/META-INF/context.xml delete mode 100644 web/WEB-INF/web.xml diff --git a/.gitignore b/.gitignore index d3bae3d4..ec7d29ba 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ -/build/ -/dist/ -/nbproject/private/ \ No newline at end of file +build/* +.gradle/* +deps/* +.idea/* +*.iml +**/juick.conf diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..35d5ef99 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,12 @@ +[submodule "deps/com.juick"] + path = deps/com.juick + url = ssh://den.jabber.ru:2205/var/lib/git/com.juick.git +[submodule "deps/com.juick.xmpp"] + path = deps/com.juick.xmpp + url = ssh://den.jabber.ru:2205/var/lib/git/com.juick.xmpp.git +[submodule "deps/com.juick.server"] + path = deps/com.juick.server + url = ssh://den.jabber.ru:2205/var/lib/git/com.juick.server.git +[submodule "deps/com.juick.json"] + path = deps/com.juick.json + url = ssh://den.jabber.ru:2205/var/lib/git/com.juick.json.git diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..ab3d39b2 --- /dev/null +++ b/build.gradle @@ -0,0 +1,67 @@ +subprojects { + apply plugin: 'java' + repositories { + mavenCentral() + } +} + +buildscript { + repositories { + mavenCentral() + jcenter() + } + dependencies { + classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.+' + } +} + +apply plugin: 'java' +apply plugin: 'war' +apply plugin: 'com.bmuschko.tomcat' + +repositories { + mavenCentral() +} + +def core = project(':deps:com.juick') +def server = project(':deps:com.juick.server') +def xmpp = project(':deps:com.juick.xmpp') +def json = project(':deps:com.juick.json') + +project(':deps:com.juick.server') { + dependencies { + compile core + } +} + +project(':deps:com.juick.xmpp') { + dependencies { + compile core + } +} + +project(':deps:com.juick.json') { + dependencies { + compile core + } +} + +dependencies { + compile 'org.json:json:20140107' + compile core + compile server + compile xmpp + compile json + providedCompile 'javax.servlet:javax.servlet-api:3.1.0' + def tomcatVersion = '7.0.+' + tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}", + "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}", + "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}" +} + +compileJava.options.encoding = 'UTF-8' + +tomcat { + httpPort = 8080 + contextPath = '/' +} diff --git a/build.xml b/build.xml deleted file mode 100644 index b1509601..00000000 --- a/build.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - - - - Builds, tests, and runs the project com.juick.api. - - - 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 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..05ef575b Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..65a9525c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Oct 29 12:36:21 MSK 2015 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..9d82f789 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..aec99730 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/xpp3_min-1.1.4.jar b/lib/xpp3_min-1.1.4.jar deleted file mode 100644 index e02ea412..00000000 Binary files a/lib/xpp3_min-1.1.4.jar and /dev/null differ diff --git a/nbproject/ant-deploy.xml b/nbproject/ant-deploy.xml deleted file mode 100644 index cbfe67c3..00000000 --- a/nbproject/ant-deploy.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml deleted file mode 100644 index 7fcc9e67..00000000 --- a/nbproject/build-impl.xml +++ /dev/null @@ -1,1112 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set src.dir - Must set test.src.dir - Must set build.dir - Must set build.web.dir - Must set build.generated.dir - Must set dist.dir - Must set build.classes.dir - Must set dist.javadoc.dir - Must set build.test.classes.dir - Must set build.test.results.dir - Must set build.classes.excludes - Must set dist.war - - - - - - - - - -The Java EE server classpath is not correctly set up - server home directory is missing. -Either open the project in the IDE and assign the server or setup the server classpath manually. -For example like this: - ant -Dj2ee.server.home=<app_server_installation_directory> - - -The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}. -Either open the project in the IDE and assign the server or setup the server classpath manually. -For example like this: - ant -Duser.properties.file=<path_to_property_file> (where you put the property "j2ee.platform.classpath" in a .properties file) -or ant -Dj2ee.platform.classpath=<server_classpath> (where no properties file is used) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -The libs.CopyLibs.classpath property is not set up. -This property must point to -org-netbeans-modules-java-j2seproject-copylibstask.jar file which is part -of NetBeans IDE installation and is usually located at -<netbeans_installation>/java<version>/ant/extra folder. -Either open the project in the IDE and make sure CopyLibs library -exists or setup the property manually. For example like this: - ant -Dlibs.CopyLibs.classpath=a/path/to/org-netbeans-modules-java-j2seproject-copylibstask.jar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set JVM to use for profiling in profiler.info.jvm - Must set profiler agent JVM arguments in profiler.info.jvmargs.agent - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.jsp.includes - - - - - - - - - - - - - - - - - - - - - - - - - - Must select a file in the IDE or set jsp.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Browser not found, cannot launch the deployed application. Try to set the BROWSER environment variable. - - - Launching ${browse.url} - - - - - - Must select one file in the IDE or set run.class - - - - Must select one file in the IDE or set run.class - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set debug.class - - - - - - - - - - - - Must select one file in the IDE or set debug.class - - - - - Must set fix.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - - Some tests failed; see details above. - - - - - - - - - Must select some files in the IDE or set test.includes - - - - Some tests failed; see details above. - - - - - Must select one file in the IDE or set test.class - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties deleted file mode 100644 index 9fa27ff1..00000000 --- a/nbproject/genfiles.properties +++ /dev/null @@ -1,8 +0,0 @@ -build.xml.data.CRC32=0e286cb1 -build.xml.script.CRC32=2226508e -build.xml.stylesheet.CRC32=651128d4@1.33.1.1 -# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. -# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=0e286cb1 -nbproject/build-impl.xml.script.CRC32=4228b93d -nbproject/build-impl.xml.stylesheet.CRC32=0cbf5bb7@1.33.1.1 diff --git a/nbproject/project.properties b/nbproject/project.properties deleted file mode 100644 index b3480c49..00000000 --- a/nbproject/project.properties +++ /dev/null @@ -1,95 +0,0 @@ -annotation.processing.enabled=true -annotation.processing.enabled.in.editor=true -annotation.processing.processors.list= -annotation.processing.run.all.processors=true -annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output -build.classes.dir=${build.web.dir}/WEB-INF/classes -build.classes.excludes=**/*.java,**/*.form -build.dir=build -build.generated.dir=${build.dir}/generated -build.generated.sources.dir=${build.dir}/generated-sources -build.test.classes.dir=${build.dir}/test/classes -build.test.results.dir=${build.dir}/test/results -build.web.dir=${build.dir}/web -build.web.excludes=${build.classes.excludes} -client.urlPart= -compile.jsps=false -conf.dir=${source.root}/conf -debug.classpath=${build.classes.dir}:${javac.classpath} -debug.test.classpath=\ - ${run.test.classpath} -display.browser=true -dist.dir=dist -dist.ear.war=${dist.dir}/${war.ear.name} -dist.javadoc.dir=${dist.dir}/javadoc -dist.war=${dist.dir}/${war.name} -endorsed.classpath=\ - ${libs.javaee-endorsed-api-6.0.classpath} -excludes= -file.reference.xpp3_min-1.1.4.jar=lib/xpp3_min-1.1.4.jar -includes=** -j2ee.compile.on.save=true -j2ee.deploy.on.save=true -j2ee.platform=1.6-web -j2ee.platform.classpath=${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.home}/lib/tomcat-jdbc.jar:${j2ee.server.home}/lib/jasper-el.jar:${j2ee.server.home}/lib/tomcat-i18n-fr.jar:${j2ee.server.home}/lib/tomcat7-websocket.jar:${j2ee.server.home}/lib/jsp-api.jar:${j2ee.server.home}/lib/catalina.jar:${j2ee.server.home}/lib/ecj-4.2.2.jar:${j2ee.server.home}/lib/tomcat-i18n-ja.jar:${j2ee.server.home}/lib/websocket-api.jar:${j2ee.server.home}/lib/el-api.jar:${j2ee.server.home}/lib/catalina-tribes.jar:${j2ee.server.home}/lib/tomcat-coyote.jar:${j2ee.server.home}/lib/jasper.jar:${j2ee.server.home}/lib/tomcat-util.jar:${j2ee.server.home}/lib/tomcat-api.jar:${j2ee.server.home}/lib/tomcat-dbcp.jar:${j2ee.server.home}/lib/servlet-api.jar:${j2ee.server.home}/lib/tomcat-i18n-es.jar:${j2ee.server.home}/lib/catalina-ha.jar:${j2ee.server.home}/lib/annotations-api.jar -j2ee.server.type=Tomcat -jar.compress=false -javac.classpath=\ - ${reference.com_juick.jar}:\ - ${reference.com_juick_server.jar}:\ - ${reference.com_juick_json.jar}:\ - ${reference.com_juick_xmpp.jar}:\ - ${libs.JSON.classpath}:\ - ${file.reference.xpp3_min-1.1.4.jar} -# Space-separated list of extra javac options -javac.compilerargs= -javac.debug=true -javac.deprecation=false -javac.processorpath=\ - ${javac.classpath} -javac.source=1.6 -javac.target=1.6 -javac.test.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -javac.test.processorpath=\ - ${javac.test.classpath} -javadoc.additionalparam= -javadoc.author=false -javadoc.encoding=${source.encoding} -javadoc.noindex=false -javadoc.nonavbar=false -javadoc.notree=false -javadoc.preview=true -javadoc.private=false -javadoc.splitindex=true -javadoc.use=true -javadoc.version=false -javadoc.windowtitle= -lib.dir=${web.docbase.dir}/WEB-INF/lib -persistence.xml.dir=${conf.dir} -platform.active=default_platform -project.com_juick=../com.juick -project.com_juick_json=../com.juick.json -project.com_juick_server=../com.juick.server -project.com_juick_xmpp=../com.juick.xmpp -reference.com_juick.jar=${project.com_juick}/dist/com.juick.jar -reference.com_juick_json.jar=${project.com_juick_json}/dist/com.juick.json.jar -reference.com_juick_server.jar=${project.com_juick_server}/dist/com.juick.server.jar -reference.com_juick_xmpp.jar=${project.com_juick_xmpp}/dist/com.juick.xmpp.jar -resource.dir=setup -run.test.classpath=\ - ${javac.test.classpath}:\ - ${build.test.classes.dir} -# Space-separated list of JVM arguments used when running a class with a main method or a unit test -# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value): -runmain.jvmargs= -source.encoding=UTF-8 -source.root=src -src.dir=${source.root}/java -test.src.dir=test -war.content.additional= -war.ear.name=com.juick.api.war -war.name=com.juick.api.war -web.docbase.dir=web -webinf.dir=web/WEB-INF diff --git a/nbproject/project.xml b/nbproject/project.xml deleted file mode 100644 index 01e2f8c9..00000000 --- a/nbproject/project.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - org.netbeans.modules.web.project - - - com.juick.api - 1.6.5 - - - ${reference.com_juick.jar} - WEB-INF/lib - - - ${reference.com_juick_server.jar} - WEB-INF/lib - - - ${reference.com_juick_json.jar} - WEB-INF/lib - - - ${reference.com_juick_xmpp.jar} - WEB-INF/lib - - - ${libs.JSON.classpath} - WEB-INF/lib - - - ${file.reference.xpp3_min-1.1.4.jar} - WEB-INF/lib - - - - - - - - - - - - - com_juick - jar - - jar - clean - jar - - - com_juick_json - jar - - jar - clean - jar - - - com_juick_server - jar - - jar - clean - jar - - - com_juick_xmpp - jar - - jar - clean - jar - - - - diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..d775a49a --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +include ':deps:com.juick', ':deps:com.juick.server', ':deps:com.juick.xmpp', ':deps:com.juick.json' diff --git a/src/conf/MANIFEST.MF b/src/conf/MANIFEST.MF deleted file mode 100644 index 59499bce..00000000 --- a/src/conf/MANIFEST.MF +++ /dev/null @@ -1,2 +0,0 @@ -Manifest-Version: 1.0 - diff --git a/src/java/com/juick/api/Main.java b/src/java/com/juick/api/Main.java deleted file mode 100644 index 5ee4027b..00000000 --- a/src/java/com/juick/api/Main.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Juick - * Copyright (C) 2008-2013, Ugnich Anton - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package com.juick.api; - -import com.juick.xmpp.JID; -import com.juick.xmpp.Stream; -import com.juick.xmpp.StreamComponent; -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; -import javax.servlet.ServletException; -import javax.servlet.annotation.MultipartConfig; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * - * @author Ugnich Anton - */ -@WebServlet(name = "Main", urlPatterns = {"/"}) -@MultipartConfig -public class Main extends HttpServlet implements Stream.StreamListener { - - Connection sql; - Connection sqlSearch; - Stream xmpp; - Messages messages; - Users users; - PM pm; - Others others; - - @Override - public void init() throws ServletException { - super.init(); - try { - Properties conf = new Properties(); - conf.load(new FileInputStream("/etc/juick/api.conf")); - - Class.forName("com.mysql.jdbc.Driver"); - sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); - 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); - - setupXmppComponent(conf.getProperty("xmpp_password")); - - } catch (Exception e) { - log(null, e); - } - } - - public void setupXmppComponent(final String password) { - Thread thr = new Thread(new Runnable() { - - @Override - public void run() { - try { - Socket socket = new Socket("localhost", 5347); - xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password); - xmpp.addListener(Main.this); - xmpp.startParsing(); - } catch (IOException e) { - System.err.println(e); - } - } - }); - thr.start(); - } - - @Override - public void onStreamFail(String msg) { - System.err.println("XMPP STREAM FAIL: " + msg); - } - - @Override - public void onStreamReady() { - 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 - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getCharacterEncoding() == null) { - request.setCharacterEncoding("UTF-8"); - } - - int vuid = Utils.getHttpAuthUID(sql, request); - if (vuid == 0) { - vuid = Utils.getVisitorQueryStringUID(sql, request); - } - - String uri = request.getRequestURI(); - if (uri.equals("/home")) { - if (vuid > 0) { - messages.doGetHome(request, response, vuid); - } else { - response.sendError(401); - } - } else if (uri.equals("/users")) { - users.doGetUsers(request, response, vuid); - } else if (uri.equals("/users/read")) { - users.doGetUserRead(request, response, vuid); - } else if (uri.equals("/users/readers")) { - users.doGetUserReaders(request, response, vuid); - } else if (uri.equals("/pm")) { - if (vuid > 0) { - pm.doGetPM(request, response, vuid); - } else { - response.sendError(401); - } - } else if (uri.equals("/groups_pms")) { - if (vuid > 0) { - others.doGetGroupsPMs(request, response, vuid); - } else { - response.sendError(401); - } - } else if (uri.equals("/messages/set_popular") && vuid == 1) { - messages.doSetPopular(request, response, xmpp); - } else if (uri.equals("/messages/set_privacy") && vuid > 0) { - messages.doSetPrivacy(request, response, xmpp, vuid); - } else { - response.sendError(404); - } - } - - /** - * Handles the HTTP POST method. - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getCharacterEncoding() == null) { - request.setCharacterEncoding("UTF-8"); - } - - int vuid = Utils.getHttpAuthUID(sql, request); - if (vuid == 0) { - vuid = Utils.getVisitorQueryStringUID(sql, request); - } - if (vuid == 0) { - response.sendError(401); - return; - } - - String uri = request.getRequestURI(); - if (uri.equals("/post")) { - } else if (uri.equals("/pm")) { - pm.doPostPM(request, response, xmpp, vuid); - } else { - response.sendError(405); - } - } - - 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", "*"); - - String callback = request.getParameter("callback"); - if (callback != null && (callback.length() > 64 || !callback.matches("[a-zA-Z0-9\\-\\_]+"))) { - callback = null; - } - - PrintWriter out = response.getWriter(); - try { - if (callback != null) { - out.print(callback + "("); - out.print(json); - out.print(")"); - } else { - out.print(json); - } - } finally { - out.close(); - } - } -} diff --git a/src/java/com/juick/api/Messages.java b/src/java/com/juick/api/Messages.java deleted file mode 100644 index b5462258..00000000 --- a/src/java/com/juick/api/Messages.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.juick.api; - -import com.juick.server.MessagesQueries; -import com.juick.xmpp.JID; -import com.juick.xmpp.Message; -import com.juick.xmpp.Stream; -import com.juick.xmpp.extensions.JuickMessage; -import java.io.IOException; -import java.sql.Connection; -import java.util.ArrayList; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * - * @author ugnich - */ -public class Messages { - - Connection sql; - - public Messages(Connection 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); - - ArrayList mids = MessagesQueries.getMyFeed(sql, vuid, before_mid); - if (mids != null && !mids.isEmpty()) { - ArrayList msgs = MessagesQueries.getMessages(sql, mids); - if (msgs != null && !msgs.isEmpty()) { - String json = com.juick.json.Messages.arrayToString(msgs); - Main.replyJSON(request, response, json); - } else { - response.sendError(404); - } - } 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); - 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 popular = Utils.parseInt(request.getParameter("popular"), 0); - - if (mid > 0) { - boolean ret = MessagesQueries.setMessagePopular(sql, mid, popular); - - if (ret && popular == 2) { - try { - com.juick.Message m = MessagesQueries.getMessage(sql, mid); - if (m != null) { - Message msg = new Message(); - 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; - msg.childs.add(jmsg); - - msg.to.Username = "twitter"; - xmpp.send(msg); - msg.to.Username = "fb"; - xmpp.send(msg); - msg.to.Username = "vk"; - xmpp.send(msg); - } else { - throw new Exception("Message not found"); - } - } catch (Exception e) { - System.err.println("SETPOPULAR ERROR: " + e.toString()); - } - } - - Main.replyJSON(request, response, "{\"status\":\"ok\"}"); - } - } -} diff --git a/src/java/com/juick/api/Others.java b/src/java/com/juick/api/Others.java deleted file mode 100644 index 25df5bf4..00000000 --- a/src/java/com/juick/api/Others.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.juick.api; - -import com.juick.server.PMQueries; -import java.io.IOException; -import java.sql.Connection; -import java.util.ArrayList; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * - * @author ugnich - */ -public class Others { - - Connection sql; - - public Others(Connection sql) { - this.sql = sql; - } - - public void doGetGroupsPMs(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - int cnt = 5; - try { - String cntStr = request.getParameter("cnt"); - cnt = Integer.parseInt(cntStr); - if (cnt < 3) { - cnt = 3; - } - if (cnt > 10) { - cnt = 10; - } - } catch (Exception e) { - } - - ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt); - if (lastconv != null && !lastconv.isEmpty()) { - String json = "{\"pms\":" + com.juick.json.Users.arrayToString(lastconv) + "}"; - Main.replyJSON(request, response, json); - } else { - response.sendError(404); - } - } -} diff --git a/src/java/com/juick/api/PM.java b/src/java/com/juick/api/PM.java deleted file mode 100644 index 2722526d..00000000 --- a/src/java/com/juick/api/PM.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.juick.api; - -import com.juick.server.PMQueries; -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 java.io.IOException; -import java.sql.Connection; -import java.util.ArrayList; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * - * @author ugnich - */ -public class PM { - - Connection sql; - - public PM(Connection sql) { - this.sql = sql; - } - - 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}$")) { - uid = UserQueries.getUIDbyName(sql, uname); - } - - if (uid == 0) { - response.sendError(400); - return; - } - - ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid); - if (msgs != null && !msgs.isEmpty()) { - String json = com.juick.json.Messages.arrayToString(msgs); - Main.replyJSON(request, response, json); - } else { - response.sendError(404); - } - } - - 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)) { - uid = UserQueries.getUIDbyName(sql, uname); - } - - String body = request.getParameter("body"); - if (uid == 0 || body == null || body.length() < 1 || body.length() > 10240) { - response.sendError(400); - return; - } - - if (UserQueries.isInBLAny(sql, uid, vuid)) { - response.sendError(403); - return; - } - - if (PMQueries.createPM(sql, vuid, uid, body)) { - Message msg = new Message(); - 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; - msg.childs.add(jmsg); - xmpp.send(msg); - - msg.to.Host = "ws.juick.com"; - xmpp.send(msg); - - Main.replyJSON(request, response, com.juick.json.Message.toJSON(jmsg).toString()); - - String jid = UserQueries.getJIDbyUID(sql, uid); - if (jid != null) { - Message mm = new Message(); - 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.body = body; - } else { - mm.from = new JID("juick", "juick.com", "Juick"); - mm.body = "Private message from @" + jmsg.User.UName + ":\n" + body; - } - xmpp.send(mm); - } - - } else { - response.sendError(500); - } - } -} diff --git a/src/java/com/juick/api/Users.java b/src/java/com/juick/api/Users.java deleted file mode 100644 index cdd48fd6..00000000 --- a/src/java/com/juick/api/Users.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.juick.api; - -import com.juick.User; -import com.juick.server.UserQueries; -import java.io.IOException; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * - * @author ugnich - */ -public class Users { - - Connection sql; - - public Users(Connection sql) { - this.sql = sql; - } - - public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - ArrayList users = new ArrayList(); - - String punames[] = request.getParameterValues("uname"); - if (punames != null) { - ArrayList unames = new ArrayList(Arrays.asList(punames)); - Iterator i = unames.iterator(); - while (i.hasNext()) { - if (!i.next().matches("^[a-zA-Z0-9\\-]{2,16}$")) { - i.remove(); - } - } - if (!unames.isEmpty() && unames.size() < 20) { - users.addAll(UserQueries.getUsersByName(sql, unames)); - } - } - - String pjids[] = request.getParameterValues("jid"); - if (pjids != null) { - ArrayList jids = new ArrayList(Arrays.asList(pjids)); - Iterator ii = jids.iterator(); - while (ii.hasNext()) { - if (!ii.next().matches("^[a-zA-Z0-9\\-\\_\\@\\.]{6,64}$")) { - ii.remove(); - } - } - if (!jids.isEmpty() && jids.size() < 20) { - users.addAll(UserQueries.getUsersByJID(sql, jids)); - } - } - - if (!users.isEmpty()) { - String json = com.juick.json.Users.arrayToString(users); - Main.replyJSON(request, response, json); - } else { - response.sendError(404); - } - } - - public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - int uid = 0; - String uname = request.getParameter("uname"); - if (uname == null) { - uid = vuid; - } else { - if (UserQueries.checkUserNameValid(uname)) { - com.juick.User u = UserQueries.getUserByName(sql, uname); - if (u != null && u.UID > 0) { - uid = u.UID; - } - } - } - - if (uid > 0) { - ArrayList uids = UserQueries.getUserRead(sql, uid); - if (uids.size() > 0) { - ArrayList users = UserQueries.getUsersByID(sql, uids); - if (users.size() > 0) { - String json = com.juick.json.Users.arrayToString(users); - Main.replyJSON(request, response, json); - return; - } - } - } - response.sendError(404); - } - - public void doGetUserReaders(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - int uid = 0; - String uname = request.getParameter("uname"); - if (uname == null) { - uid = vuid; - } else { - if (UserQueries.checkUserNameValid(uname)) { - com.juick.User u = UserQueries.getUserByName(sql, uname); - if (u != null && u.UID > 0) { - uid = u.UID; - } - } - } - - if (uid > 0) { - ArrayList uids = UserQueries.getUserReaders(sql, uid); - if (uids.size() > 0) { - ArrayList users = UserQueries.getUsersByID(sql, uids); - if (users.size() > 0) { - String json = com.juick.json.Users.arrayToString(users); - Main.replyJSON(request, response, json); - return; - } - } - } - response.sendError(404); - } -} diff --git a/src/java/com/juick/api/Utils.java b/src/java/com/juick/api/Utils.java deleted file mode 100644 index 10e0cccb..00000000 --- a/src/java/com/juick/api/Utils.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Juick - * Copyright (C) 2008-2011, Ugnich Anton - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package com.juick.api; - -import com.juick.server.UserQueries; -import java.io.IOException; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import sun.misc.BASE64Decoder; - -/** - * - * @author Ugnich Anton - */ -public class Utils { - - public static String getCookie(HttpServletRequest request, String name) { - Cookie cookies[] = request.getCookies(); - if (cookies != null) { - for (int i = 0; i < cookies.length; i++) { - if (cookies[i].getName().equals(name)) { - return cookies[i].getValue(); - } - } - } - return null; - } - - public static com.juick.User getVisitorUser(Connection sql, HttpServletRequest request) { - String hash = getCookie(request, "hash"); - if (hash != null) { - return com.juick.server.UserQueries.getUserByHash(sql, hash); - } else { - return null; - } - } - - public static int getVisitorUID(Connection sql, HttpServletRequest request) { - Cookie cookies[] = request.getCookies(); - if (cookies != null) { - for (int i = 0; i < cookies.length; i++) { - if (cookies[i].getName().equals("hash")) { - String hash = cookies[i].getValue(); - return com.juick.server.UserQueries.getUIDbyHash(sql, hash); - } - } - } - return 0; - } - - public static int getHttpAuthUID(Connection sql, HttpServletRequest request) { - String auth = request.getHeader("Authorization"); - if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) { - try { - BASE64Decoder dec = new BASE64Decoder(); - String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2); - if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) { - return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]); - } - } catch (IOException e) { - } - } - return 0; - } - - public static int getVisitorQueryStringUID(Connection sql, HttpServletRequest request) { - String hash = request.getParameter("hash"); - if (hash != null && hash.length() == 16) { - return com.juick.server.UserQueries.getUIDbyHash(sql, hash); - } - return 0; - } - - public static void sendPermanentRedirect(HttpServletResponse response, String location) { - response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); - response.setHeader("Location", location); - } - - public static void finishSQL(ResultSet rs, Statement stmt) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - } - } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - } - } - } - - public static String convertArray2String(ArrayList mids) { - String q = ""; - for (int i = 0; i < mids.size(); i++) { - if (i > 0) { - q += ","; - } - q += mids.get(i); - } - return q; - } - - public static String encodeHTML(String str) { - String ret = str; - ret = ret.replaceAll("<", "<"); - ret = ret.replaceAll(">", ">"); - return str; - } - - public static String encodeSphinx(String str) { - String ret = str; - ret = ret.replaceAll("@", "\\\\@"); - return ret; - } - - public static int parseInt(String str, int def) { - int ret = def; - if (str != null) { - try { - ret = Integer.parseInt(str); - } catch (Exception e) { - } - } - return ret; - } -} diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java new file mode 100644 index 00000000..5ee4027b --- /dev/null +++ b/src/main/java/com/juick/api/Main.java @@ -0,0 +1,231 @@ +/* + * Juick + * Copyright (C) 2008-2013, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.api; + +import com.juick.xmpp.JID; +import com.juick.xmpp.Stream; +import com.juick.xmpp.StreamComponent; +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; +import javax.servlet.ServletException; +import javax.servlet.annotation.MultipartConfig; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author Ugnich Anton + */ +@WebServlet(name = "Main", urlPatterns = {"/"}) +@MultipartConfig +public class Main extends HttpServlet implements Stream.StreamListener { + + Connection sql; + Connection sqlSearch; + Stream xmpp; + Messages messages; + Users users; + PM pm; + Others others; + + @Override + public void init() throws ServletException { + super.init(); + try { + Properties conf = new Properties(); + conf.load(new FileInputStream("/etc/juick/api.conf")); + + Class.forName("com.mysql.jdbc.Driver"); + sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); + 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); + + setupXmppComponent(conf.getProperty("xmpp_password")); + + } catch (Exception e) { + log(null, e); + } + } + + public void setupXmppComponent(final String password) { + Thread thr = new Thread(new Runnable() { + + @Override + public void run() { + try { + Socket socket = new Socket("localhost", 5347); + xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password); + xmpp.addListener(Main.this); + xmpp.startParsing(); + } catch (IOException e) { + System.err.println(e); + } + } + }); + thr.start(); + } + + @Override + public void onStreamFail(String msg) { + System.err.println("XMPP STREAM FAIL: " + msg); + } + + @Override + public void onStreamReady() { + 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 + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (request.getCharacterEncoding() == null) { + request.setCharacterEncoding("UTF-8"); + } + + int vuid = Utils.getHttpAuthUID(sql, request); + if (vuid == 0) { + vuid = Utils.getVisitorQueryStringUID(sql, request); + } + + String uri = request.getRequestURI(); + if (uri.equals("/home")) { + if (vuid > 0) { + messages.doGetHome(request, response, vuid); + } else { + response.sendError(401); + } + } else if (uri.equals("/users")) { + users.doGetUsers(request, response, vuid); + } else if (uri.equals("/users/read")) { + users.doGetUserRead(request, response, vuid); + } else if (uri.equals("/users/readers")) { + users.doGetUserReaders(request, response, vuid); + } else if (uri.equals("/pm")) { + if (vuid > 0) { + pm.doGetPM(request, response, vuid); + } else { + response.sendError(401); + } + } else if (uri.equals("/groups_pms")) { + if (vuid > 0) { + others.doGetGroupsPMs(request, response, vuid); + } else { + response.sendError(401); + } + } else if (uri.equals("/messages/set_popular") && vuid == 1) { + messages.doSetPopular(request, response, xmpp); + } else if (uri.equals("/messages/set_privacy") && vuid > 0) { + messages.doSetPrivacy(request, response, xmpp, vuid); + } else { + response.sendError(404); + } + } + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (request.getCharacterEncoding() == null) { + request.setCharacterEncoding("UTF-8"); + } + + int vuid = Utils.getHttpAuthUID(sql, request); + if (vuid == 0) { + vuid = Utils.getVisitorQueryStringUID(sql, request); + } + if (vuid == 0) { + response.sendError(401); + return; + } + + String uri = request.getRequestURI(); + if (uri.equals("/post")) { + } else if (uri.equals("/pm")) { + pm.doPostPM(request, response, xmpp, vuid); + } else { + response.sendError(405); + } + } + + 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", "*"); + + String callback = request.getParameter("callback"); + if (callback != null && (callback.length() > 64 || !callback.matches("[a-zA-Z0-9\\-\\_]+"))) { + callback = null; + } + + PrintWriter out = response.getWriter(); + try { + if (callback != null) { + out.print(callback + "("); + out.print(json); + out.print(")"); + } 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 new file mode 100644 index 00000000..b5462258 --- /dev/null +++ b/src/main/java/com/juick/api/Messages.java @@ -0,0 +1,89 @@ +package com.juick.api; + +import com.juick.server.MessagesQueries; +import com.juick.xmpp.JID; +import com.juick.xmpp.Message; +import com.juick.xmpp.Stream; +import com.juick.xmpp.extensions.JuickMessage; +import java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class Messages { + + Connection sql; + + public Messages(Connection 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); + + ArrayList mids = MessagesQueries.getMyFeed(sql, vuid, before_mid); + if (mids != null && !mids.isEmpty()) { + ArrayList msgs = MessagesQueries.getMessages(sql, mids); + if (msgs != null && !msgs.isEmpty()) { + String json = com.juick.json.Messages.arrayToString(msgs); + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } 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); + 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 popular = Utils.parseInt(request.getParameter("popular"), 0); + + if (mid > 0) { + boolean ret = MessagesQueries.setMessagePopular(sql, mid, popular); + + if (ret && popular == 2) { + try { + com.juick.Message m = MessagesQueries.getMessage(sql, mid); + if (m != null) { + Message msg = new Message(); + 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; + msg.childs.add(jmsg); + + msg.to.Username = "twitter"; + xmpp.send(msg); + msg.to.Username = "fb"; + xmpp.send(msg); + msg.to.Username = "vk"; + xmpp.send(msg); + } else { + throw new Exception("Message not found"); + } + } catch (Exception e) { + System.err.println("SETPOPULAR ERROR: " + e.toString()); + } + } + + 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 new file mode 100644 index 00000000..25df5bf4 --- /dev/null +++ b/src/main/java/com/juick/api/Others.java @@ -0,0 +1,45 @@ +package com.juick.api; + +import com.juick.server.PMQueries; +import java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class Others { + + Connection sql; + + public Others(Connection sql) { + this.sql = sql; + } + + public void doGetGroupsPMs(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + int cnt = 5; + try { + String cntStr = request.getParameter("cnt"); + cnt = Integer.parseInt(cntStr); + if (cnt < 3) { + cnt = 3; + } + if (cnt > 10) { + cnt = 10; + } + } catch (Exception e) { + } + + ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt); + if (lastconv != null && !lastconv.isEmpty()) { + String json = "{\"pms\":" + com.juick.json.Users.arrayToString(lastconv) + "}"; + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } +} diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java new file mode 100644 index 00000000..2722526d --- /dev/null +++ b/src/main/java/com/juick/api/PM.java @@ -0,0 +1,101 @@ +package com.juick.api; + +import com.juick.server.PMQueries; +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 java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class PM { + + Connection sql; + + public PM(Connection sql) { + this.sql = sql; + } + + 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}$")) { + uid = UserQueries.getUIDbyName(sql, uname); + } + + if (uid == 0) { + response.sendError(400); + return; + } + + ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid); + if (msgs != null && !msgs.isEmpty()) { + String json = com.juick.json.Messages.arrayToString(msgs); + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } + + 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)) { + uid = UserQueries.getUIDbyName(sql, uname); + } + + String body = request.getParameter("body"); + if (uid == 0 || body == null || body.length() < 1 || body.length() > 10240) { + response.sendError(400); + return; + } + + if (UserQueries.isInBLAny(sql, uid, vuid)) { + response.sendError(403); + return; + } + + if (PMQueries.createPM(sql, vuid, uid, body)) { + Message msg = new Message(); + 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; + msg.childs.add(jmsg); + xmpp.send(msg); + + msg.to.Host = "ws.juick.com"; + xmpp.send(msg); + + Main.replyJSON(request, response, com.juick.json.Message.toJSON(jmsg).toString()); + + String jid = UserQueries.getJIDbyUID(sql, uid); + if (jid != null) { + Message mm = new Message(); + 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.body = body; + } else { + mm.from = new JID("juick", "juick.com", "Juick"); + mm.body = "Private message from @" + jmsg.User.UName + ":\n" + body; + } + xmpp.send(mm); + } + + } else { + response.sendError(500); + } + } +} diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java new file mode 100644 index 00000000..cdd48fd6 --- /dev/null +++ b/src/main/java/com/juick/api/Users.java @@ -0,0 +1,120 @@ +package com.juick.api; + +import com.juick.User; +import com.juick.server.UserQueries; +import java.io.IOException; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author ugnich + */ +public class Users { + + Connection sql; + + public Users(Connection sql) { + this.sql = sql; + } + + public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + ArrayList users = new ArrayList(); + + String punames[] = request.getParameterValues("uname"); + if (punames != null) { + ArrayList unames = new ArrayList(Arrays.asList(punames)); + Iterator i = unames.iterator(); + while (i.hasNext()) { + if (!i.next().matches("^[a-zA-Z0-9\\-]{2,16}$")) { + i.remove(); + } + } + if (!unames.isEmpty() && unames.size() < 20) { + users.addAll(UserQueries.getUsersByName(sql, unames)); + } + } + + String pjids[] = request.getParameterValues("jid"); + if (pjids != null) { + ArrayList jids = new ArrayList(Arrays.asList(pjids)); + Iterator ii = jids.iterator(); + while (ii.hasNext()) { + if (!ii.next().matches("^[a-zA-Z0-9\\-\\_\\@\\.]{6,64}$")) { + ii.remove(); + } + } + if (!jids.isEmpty() && jids.size() < 20) { + users.addAll(UserQueries.getUsersByJID(sql, jids)); + } + } + + if (!users.isEmpty()) { + String json = com.juick.json.Users.arrayToString(users); + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } + + public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + int uid = 0; + String uname = request.getParameter("uname"); + if (uname == null) { + uid = vuid; + } else { + if (UserQueries.checkUserNameValid(uname)) { + com.juick.User u = UserQueries.getUserByName(sql, uname); + if (u != null && u.UID > 0) { + uid = u.UID; + } + } + } + + if (uid > 0) { + ArrayList uids = UserQueries.getUserRead(sql, uid); + if (uids.size() > 0) { + ArrayList users = UserQueries.getUsersByID(sql, uids); + if (users.size() > 0) { + String json = com.juick.json.Users.arrayToString(users); + Main.replyJSON(request, response, json); + return; + } + } + } + response.sendError(404); + } + + public void doGetUserReaders(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + int uid = 0; + String uname = request.getParameter("uname"); + if (uname == null) { + uid = vuid; + } else { + if (UserQueries.checkUserNameValid(uname)) { + com.juick.User u = UserQueries.getUserByName(sql, uname); + if (u != null && u.UID > 0) { + uid = u.UID; + } + } + } + + if (uid > 0) { + ArrayList uids = UserQueries.getUserReaders(sql, uid); + if (uids.size() > 0) { + ArrayList users = UserQueries.getUsersByID(sql, uids); + if (users.size() > 0) { + String json = com.juick.json.Users.arrayToString(users); + Main.replyJSON(request, response, json); + return; + } + } + } + response.sendError(404); + } +} diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java new file mode 100644 index 00000000..10e0cccb --- /dev/null +++ b/src/main/java/com/juick/api/Utils.java @@ -0,0 +1,149 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.api; + +import com.juick.server.UserQueries; +import java.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import sun.misc.BASE64Decoder; + +/** + * + * @author Ugnich Anton + */ +public class Utils { + + public static String getCookie(HttpServletRequest request, String name) { + Cookie cookies[] = request.getCookies(); + if (cookies != null) { + for (int i = 0; i < cookies.length; i++) { + if (cookies[i].getName().equals(name)) { + return cookies[i].getValue(); + } + } + } + return null; + } + + public static com.juick.User getVisitorUser(Connection sql, HttpServletRequest request) { + String hash = getCookie(request, "hash"); + if (hash != null) { + return com.juick.server.UserQueries.getUserByHash(sql, hash); + } else { + return null; + } + } + + public static int getVisitorUID(Connection sql, HttpServletRequest request) { + Cookie cookies[] = request.getCookies(); + if (cookies != null) { + for (int i = 0; i < cookies.length; i++) { + if (cookies[i].getName().equals("hash")) { + String hash = cookies[i].getValue(); + return com.juick.server.UserQueries.getUIDbyHash(sql, hash); + } + } + } + return 0; + } + + public static int getHttpAuthUID(Connection sql, HttpServletRequest request) { + String auth = request.getHeader("Authorization"); + if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) { + try { + BASE64Decoder dec = new BASE64Decoder(); + String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2); + if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) { + return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]); + } + } catch (IOException e) { + } + } + return 0; + } + + public static int getVisitorQueryStringUID(Connection sql, HttpServletRequest request) { + String hash = request.getParameter("hash"); + if (hash != null && hash.length() == 16) { + return com.juick.server.UserQueries.getUIDbyHash(sql, hash); + } + return 0; + } + + public static void sendPermanentRedirect(HttpServletResponse response, String location) { + response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); + response.setHeader("Location", location); + } + + public static void finishSQL(ResultSet rs, Statement stmt) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + } + } + } + + public static String convertArray2String(ArrayList mids) { + String q = ""; + for (int i = 0; i < mids.size(); i++) { + if (i > 0) { + q += ","; + } + q += mids.get(i); + } + return q; + } + + public static String encodeHTML(String str) { + String ret = str; + ret = ret.replaceAll("<", "<"); + ret = ret.replaceAll(">", ">"); + return str; + } + + public static String encodeSphinx(String str) { + String ret = str; + ret = ret.replaceAll("@", "\\\\@"); + return ret; + } + + public static int parseInt(String str, int def) { + int ret = def; + if (str != null) { + try { + ret = Integer.parseInt(str); + } catch (Exception e) { + } + } + return ret; + } +} diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000..533a6882 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + Main + com.juick.api.Main + + + Main + / + + + + 30 + + + diff --git a/web/META-INF/context.xml b/web/META-INF/context.xml deleted file mode 100644 index 5bee3dc3..00000000 --- a/web/META-INF/context.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/web/WEB-INF/web.xml b/web/WEB-INF/web.xml deleted file mode 100644 index 533a6882..00000000 --- a/web/WEB-INF/web.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - Main - com.juick.api.Main - - - Main - / - - - - 30 - - - -- cgit v1.2.3 From 0acc3ca041434ca5486e7def8cb75729995106d5 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 3 Nov 2015 16:38:52 +0300 Subject: /messages/recommended --- src/main/java/com/juick/api/Main.java | 6 ++++++ src/main/java/com/juick/api/Messages.java | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 5ee4027b..e10b9078 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -166,6 +166,12 @@ public class Main extends HttpServlet implements Stream.StreamListener { } else { response.sendError(401); } + } else if (uri.equals("/messages/recommended")) { + if (vuid > 0) { + messages.doGetRecommended(request, response, vuid); + } else { + response.sendError(401); + } } else if (uri.equals("/messages/set_popular") && vuid == 1) { messages.doSetPopular(request, response, xmpp); } else if (uri.equals("/messages/set_privacy") && vuid > 0) { diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index b5462258..76615e44 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -41,6 +41,23 @@ 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); + + ArrayList mids = MessagesQueries.getRecommended(sql, vuid, before_mid); + if (mids != null && !mids.isEmpty()) { + ArrayList msgs = MessagesQueries.getMessages(sql, mids); + if (msgs != null && !msgs.isEmpty()) { + String json = com.juick.json.Messages.arrayToString(msgs); + Main.replyJSON(request, response, json); + } else { + response.sendError(404); + } + } 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); com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid); -- cgit v1.2.3 From 9d7b2473308fe841d84ce8af9efef164c61518e8 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 3 Nov 2015 16:52:58 +0300 Subject: recommended -> UserRecommendations --- src/main/java/com/juick/api/Messages.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index 76615e44..b7a55361 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -44,7 +44,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); - ArrayList mids = MessagesQueries.getRecommended(sql, vuid, before_mid); + ArrayList mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid); if (mids != null && !mids.isEmpty()) { ArrayList msgs = MessagesQueries.getMessages(sql, mids); if (msgs != null && !msgs.isEmpty()) { -- cgit v1.2.3 From e1a1f6d450c5ffd79eb8132d13583606663d640d Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 4 Nov 2015 14:17:18 +0300 Subject: add unit tests stub --- build.gradle | 1 + src/test/java/com/juick/tests/JsonTests.java | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/test/java/com/juick/tests/JsonTests.java diff --git a/build.gradle b/build.gradle index ab3d39b2..3ebf0fd0 100644 --- a/build.gradle +++ b/build.gradle @@ -57,6 +57,7 @@ dependencies { tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}", "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}", "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}" + testCompile 'junit:junit:4.12' } compileJava.options.encoding = 'UTF-8' diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java new file mode 100644 index 00000000..9a42dea5 --- /dev/null +++ b/src/test/java/com/juick/tests/JsonTests.java @@ -0,0 +1,23 @@ +package com.juick.tests; + +import com.google.gson.Gson; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.juick.Message; + +public class JsonTests { + @Test + public void CompareSerializers() { + Message msg = new Message(); + msg.ReplyTo = 1; + msg.MID = 234566; + Gson gson = new Gson(); + String gsonResult = gson.toJson(msg); + String ugnichResult = com.juick.json.Message.toJSON(msg).toString(); + System.out.println(gsonResult); + System.out.println(ugnichResult); + assertEquals("our result must equal to ugnich", ugnichResult, gsonResult); + } +} \ No newline at end of file -- 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(-) 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 9325971f2f6e2bf83e3d4d69bae3f8e63226bc63 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 4 Nov 2015 14:23:31 +0300 Subject: ignore netbeans and eclipse projects --- .gitignore | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index ec7d29ba..451c9d35 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,12 @@ -build/* -.gradle/* -deps/* -.idea/* -*.iml -**/juick.conf +build/* +.gradle/* +deps/* +.idea/* +*.iml +**/juick.conf +/build/ +/bin/ +/.nb-gradle/ +.settings/* +.classpath +.project \ No newline at end of file -- cgit v1.2.3 From 63b14e7818a20d598e4634a0ee686376d7f687b2 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 4 Nov 2015 15:18:41 +0300 Subject: drop gson, refactoring --- src/main/java/com/juick/api/Messages.java | 7 +++++-- src/main/java/com/juick/api/Others.java | 5 ++++- src/main/java/com/juick/api/PM.java | 7 +++++-- src/main/java/com/juick/api/Users.java | 9 ++++++--- src/test/java/com/juick/tests/JsonTests.java | 12 ------------ 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index b7a55361..548e816f 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -1,5 +1,6 @@ package com.juick.api; +import com.juick.json.MessageSerializer; import com.juick.server.MessagesQueries; import com.juick.xmpp.JID; import com.juick.xmpp.Message; @@ -19,6 +20,8 @@ import javax.servlet.http.HttpServletResponse; public class Messages { Connection sql; + + MessageSerializer messageSerializer = new MessageSerializer(); public Messages(Connection sql) { this.sql = sql; @@ -31,7 +34,7 @@ public class Messages { if (mids != null && !mids.isEmpty()) { ArrayList msgs = MessagesQueries.getMessages(sql, mids); if (msgs != null && !msgs.isEmpty()) { - String json = com.juick.json.Messages.arrayToString(msgs); + String json = messageSerializer.serializeList(msgs); Main.replyJSON(request, response, json); } else { response.sendError(404); @@ -48,7 +51,7 @@ public class Messages { if (mids != null && !mids.isEmpty()) { ArrayList msgs = MessagesQueries.getMessages(sql, mids); if (msgs != null && !msgs.isEmpty()) { - String json = com.juick.json.Messages.arrayToString(msgs); + String json = messageSerializer.serializeList(msgs); Main.replyJSON(request, response, json); } else { response.sendError(404); diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java index 25df5bf4..5e5c7475 100644 --- a/src/main/java/com/juick/api/Others.java +++ b/src/main/java/com/juick/api/Others.java @@ -1,5 +1,6 @@ package com.juick.api; +import com.juick.json.UserSerializer; import com.juick.server.PMQueries; import java.io.IOException; import java.sql.Connection; @@ -15,6 +16,8 @@ import javax.servlet.http.HttpServletResponse; public class Others { Connection sql; + + UserSerializer userSerializer = new UserSerializer(); public Others(Connection sql) { this.sql = sql; @@ -36,7 +39,7 @@ public class Others { ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt); if (lastconv != null && !lastconv.isEmpty()) { - String json = "{\"pms\":" + com.juick.json.Users.arrayToString(lastconv) + "}"; + String json = "{\"pms\":" + userSerializer.serializeList(lastconv) + "}"; Main.replyJSON(request, response, json); } else { response.sendError(404); diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java index 2722526d..ffcd155a 100644 --- a/src/main/java/com/juick/api/PM.java +++ b/src/main/java/com/juick/api/PM.java @@ -1,5 +1,6 @@ package com.juick.api; +import com.juick.json.MessageSerializer; import com.juick.server.PMQueries; import com.juick.server.UserQueries; import com.juick.xmpp.JID; @@ -20,6 +21,8 @@ import javax.servlet.http.HttpServletResponse; public class PM { Connection sql; + + MessageSerializer messageSerializer = new MessageSerializer(); public PM(Connection sql) { this.sql = sql; @@ -39,7 +42,7 @@ public class PM { ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid); if (msgs != null && !msgs.isEmpty()) { - String json = com.juick.json.Messages.arrayToString(msgs); + String json = messageSerializer.serializeList(msgs); Main.replyJSON(request, response, json); } else { response.sendError(404); @@ -77,7 +80,7 @@ public class PM { msg.to.Host = "ws.juick.com"; xmpp.send(msg); - Main.replyJSON(request, response, com.juick.json.Message.toJSON(jmsg).toString()); + Main.replyJSON(request, response, messageSerializer.serialize(jmsg).toString()); String jid = UserQueries.getJIDbyUID(sql, uid); if (jid != null) { diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java index cdd48fd6..37c9ca49 100644 --- a/src/main/java/com/juick/api/Users.java +++ b/src/main/java/com/juick/api/Users.java @@ -1,6 +1,7 @@ package com.juick.api; import com.juick.User; +import com.juick.json.UserSerializer; import com.juick.server.UserQueries; import java.io.IOException; import java.sql.Connection; @@ -18,6 +19,8 @@ import javax.servlet.http.HttpServletResponse; public class Users { Connection sql; + + UserSerializer userSerializer = new UserSerializer(); public Users(Connection sql) { this.sql = sql; @@ -55,7 +58,7 @@ public class Users { } if (!users.isEmpty()) { - String json = com.juick.json.Users.arrayToString(users); + String json = userSerializer.serializeList(users); Main.replyJSON(request, response, json); } else { response.sendError(404); @@ -81,7 +84,7 @@ public class Users { if (uids.size() > 0) { ArrayList users = UserQueries.getUsersByID(sql, uids); if (users.size() > 0) { - String json = com.juick.json.Users.arrayToString(users); + String json = userSerializer.serializeList(users); Main.replyJSON(request, response, json); return; } @@ -109,7 +112,7 @@ public class Users { if (uids.size() > 0) { ArrayList users = UserQueries.getUsersByID(sql, uids); if (users.size() > 0) { - String json = com.juick.json.Users.arrayToString(users); + String json = userSerializer.serializeList(users); Main.replyJSON(request, response, json); return; } diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java index 9a42dea5..f44fac20 100644 --- a/src/test/java/com/juick/tests/JsonTests.java +++ b/src/test/java/com/juick/tests/JsonTests.java @@ -1,23 +1,11 @@ package com.juick.tests; -import com.google.gson.Gson; import static org.junit.Assert.assertEquals; import org.junit.Test; -import com.juick.Message; - public class JsonTests { @Test public void CompareSerializers() { - Message msg = new Message(); - msg.ReplyTo = 1; - msg.MID = 234566; - Gson gson = new Gson(); - String gsonResult = gson.toJson(msg); - String ugnichResult = com.juick.json.Message.toJSON(msg).toString(); - System.out.println(gsonResult); - System.out.println(ugnichResult); - assertEquals("our result must equal to ugnich", ugnichResult, gsonResult); } } \ No newline at end of file -- 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(-) 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 36a01d90e0948435046abf0c40db48a60c525420 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 5 Nov 2015 16:02:04 +0300 Subject: set myself as top moderator --- src/main/java/com/juick/api/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index e10b9078..07504179 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -172,7 +172,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { } else { response.sendError(401); } - } else if (uri.equals("/messages/set_popular") && vuid == 1) { + } else if (uri.equals("/messages/set_popular") && vuid == 3694) { messages.doSetPopular(request, response, xmpp); } else if (uri.equals("/messages/set_privacy") && vuid > 0) { messages.doSetPrivacy(request, response, xmpp, vuid); -- cgit v1.2.3 From c61e8ac0eab84e55986319f0e8c44c43d266d9ef Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 27 Nov 2015 14:18:03 +0300 Subject: add test --- src/test/java/com/juick/tests/JsonTests.java | 52 ++++++++++++++++++++++++++-- src/test/java/com/juick/tests/original.json | 1 + 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/juick/tests/original.json diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java index f44fac20..c99432a6 100644 --- a/src/test/java/com/juick/tests/JsonTests.java +++ b/src/test/java/com/juick/tests/JsonTests.java @@ -1,11 +1,59 @@ package com.juick.tests; -import static org.junit.Assert.assertEquals; - +import com.juick.json.MessageSerializer; +import com.juick.server.MessagesQueries; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Properties; + public class JsonTests { + + Connection sql; + + @Before + public void setupConnection() { + Properties conf = new Properties(); + try { + conf.load(new FileInputStream("/etc/juick/api.conf")); + Class.forName("com.mysql.jdbc.Driver"); + sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + + conf.getProperty("mysql_username", "") + + "&password=" + conf.getProperty("mysql_password", "")); + } catch (IOException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + @Test public void CompareSerializers() { + ArrayList mids = MessagesQueries.getMyFeed(sql, 3694, 2799786); + MessageSerializer messageSerializer = new MessageSerializer(); + if (mids != null && !mids.isEmpty()) { + ArrayList msgs = MessagesQueries.getMessages(sql, 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(); + } + + } + } } } \ No newline at end of file diff --git a/src/test/java/com/juick/tests/original.json b/src/test/java/com/juick/tests/original.json new file mode 100644 index 00000000..2f4e42a3 --- /dev/null +++ b/src/test/java/com/juick/tests/original.json @@ -0,0 +1 @@ +[{"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 fe8b6a40491129461cd3fb5ccc793a3f6f2d8f34 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 27 Nov 2015 15:20:23 +0300 Subject: add groovy shell --- build.gradle | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build.gradle b/build.gradle index 3ebf0fd0..4a98c4d2 100644 --- a/build.gradle +++ b/build.gradle @@ -12,12 +12,14 @@ buildscript { } dependencies { classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.+' + classpath 'com.tkruse.gradle:gradle-groovysh-plugin:1.0.7' } } apply plugin: 'java' apply plugin: 'war' apply plugin: 'com.bmuschko.tomcat' +apply plugin: 'com.github.tkruse.groovysh' repositories { mavenCentral() -- 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(-) 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 38013dd67292fa186e3a07d098bc9a484ea2bd0f Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 14 Dec 2015 14:40:13 +0300 Subject: sync deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deps/com.juick.server b/deps/com.juick.server index 5f981ff9..79e48598 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 5f981ff945d7bad508d0fb56d037bfe3dccd0cf3 +Subproject commit 79e48598873f6a2b4ec1aa850e310a689d862afa -- 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(-) 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 98802a172b5e0bea73976e48db53b4bb25bcea17 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 10 Jan 2016 18:26:07 +0300 Subject: update gitigonre --- .gitignore | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 451c9d35..b25773e5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,11 +2,11 @@ build/* .gradle/* deps/* .idea/* -*.iml +**/*.iml **/juick.conf /build/ /bin/ /.nb-gradle/ .settings/* .classpath -.project \ No newline at end of file +.project -- 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(-) 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 ee86970fcae9878af0adcad00cf5333647b8babf Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 10 Jan 2016 18:54:05 +0300 Subject: refactoring --- src/main/java/com/juick/api/Main.java | 23 ++++++++++------------- src/main/java/com/juick/api/Messages.java | 15 ++++++++------- src/main/java/com/juick/api/Others.java | 10 ++++++---- src/main/java/com/juick/api/PM.java | 3 ++- src/main/java/com/juick/api/Users.java | 23 ++++++++++++----------- src/test/java/com/juick/tests/JsonTests.java | 5 +++-- 6 files changed, 41 insertions(+), 38 deletions(-) diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 07504179..09dd4cbd 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -28,6 +28,7 @@ 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; @@ -75,18 +76,14 @@ public class Main extends HttpServlet implements Stream.StreamListener { } public void setupXmppComponent(final String password) { - Thread thr = new Thread(new Runnable() { - - @Override - public void run() { - try { - Socket socket = new Socket("localhost", 5347); - xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password); - xmpp.addListener(Main.this); - xmpp.startParsing(); - } catch (IOException e) { - System.err.println(e); - } + Thread thr = new Thread(() -> { + try { + Socket socket = new Socket("localhost", 5347); + xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password); + xmpp.addListener(Main.this); + xmpp.startParsing(); + } catch (IOException e) { + log("XMPP exception", e); } }); thr.start(); @@ -94,7 +91,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { @Override public void onStreamFail(String msg) { - System.err.println("XMPP STREAM FAIL: " + msg); + log("XMPP failed: " + msg); } @Override diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index 548e816f..cde3987f 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -6,12 +6,13 @@ import com.juick.xmpp.JID; import com.juick.xmpp.Message; import com.juick.xmpp.Stream; import com.juick.xmpp.extensions.JuickMessage; -import java.io.IOException; -import java.sql.Connection; -import java.util.ArrayList; + 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; /** * @@ -30,9 +31,9 @@ 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); - ArrayList mids = MessagesQueries.getMyFeed(sql, vuid, before_mid); + List mids = MessagesQueries.getMyFeed(sql, vuid, before_mid); if (mids != null && !mids.isEmpty()) { - ArrayList msgs = MessagesQueries.getMessages(sql, mids); + List msgs = MessagesQueries.getMessages(sql, mids); if (msgs != null && !msgs.isEmpty()) { String json = messageSerializer.serializeList(msgs); Main.replyJSON(request, response, json); @@ -47,9 +48,9 @@ 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); - ArrayList mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid); + List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid); if (mids != null && !mids.isEmpty()) { - ArrayList msgs = MessagesQueries.getMessages(sql, mids); + List msgs = MessagesQueries.getMessages(sql, mids); if (msgs != null && !msgs.isEmpty()) { String json = messageSerializer.serializeList(msgs); Main.replyJSON(request, response, json); diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java index 5e5c7475..323ed41a 100644 --- a/src/main/java/com/juick/api/Others.java +++ b/src/main/java/com/juick/api/Others.java @@ -1,13 +1,15 @@ package com.juick.api; +import com.juick.User; import com.juick.json.UserSerializer; import com.juick.server.PMQueries; -import java.io.IOException; -import java.sql.Connection; -import java.util.ArrayList; + 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; /** * @@ -37,7 +39,7 @@ public class Others { } catch (Exception e) { } - ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt); + List lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt); if (lastconv != null && !lastconv.isEmpty()) { String json = "{\"pms\":" + userSerializer.serializeList(lastconv) + "}"; Main.replyJSON(request, response, json); diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java index ffcd155a..f22a4add 100644 --- a/src/main/java/com/juick/api/PM.java +++ b/src/main/java/com/juick/api/PM.java @@ -10,6 +10,7 @@ import com.juick.xmpp.extensions.JuickMessage; 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; import javax.servlet.http.HttpServletResponse; @@ -40,7 +41,7 @@ public class PM { return; } - ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid); + List msgs = PMQueries.getPMMessages(sql, vuid, uid); if (msgs != null && !msgs.isEmpty()) { String json = messageSerializer.serializeList(msgs); Main.replyJSON(request, response, json); diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java index 37c9ca49..5bae4028 100644 --- a/src/main/java/com/juick/api/Users.java +++ b/src/main/java/com/juick/api/Users.java @@ -1,16 +1,17 @@ package com.juick.api; -import com.juick.User; import com.juick.json.UserSerializer; import com.juick.server.UserQueries; + +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; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import java.util.List; /** * @@ -27,11 +28,11 @@ public class Users { } public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - ArrayList users = new ArrayList(); + List users = new ArrayList<>(); String punames[] = request.getParameterValues("uname"); if (punames != null) { - ArrayList unames = new ArrayList(Arrays.asList(punames)); + ArrayList unames = new ArrayList<>(Arrays.asList(punames)); Iterator i = unames.iterator(); while (i.hasNext()) { if (!i.next().matches("^[a-zA-Z0-9\\-]{2,16}$")) { @@ -45,7 +46,7 @@ public class Users { String pjids[] = request.getParameterValues("jid"); if (pjids != null) { - ArrayList jids = new ArrayList(Arrays.asList(pjids)); + List jids = new ArrayList<>(Arrays.asList(pjids)); Iterator ii = jids.iterator(); while (ii.hasNext()) { if (!ii.next().matches("^[a-zA-Z0-9\\-\\_\\@\\.]{6,64}$")) { @@ -80,9 +81,9 @@ public class Users { } if (uid > 0) { - ArrayList uids = UserQueries.getUserRead(sql, uid); + List uids = UserQueries.getUserRead(sql, uid); if (uids.size() > 0) { - ArrayList users = UserQueries.getUsersByID(sql, uids); + List users = UserQueries.getUsersByID(sql, uids); if (users.size() > 0) { String json = userSerializer.serializeList(users); Main.replyJSON(request, response, json); @@ -108,9 +109,9 @@ public class Users { } if (uid > 0) { - ArrayList uids = UserQueries.getUserReaders(sql, uid); + List uids = UserQueries.getUserReaders(sql, uid); if (uids.size() > 0) { - ArrayList users = UserQueries.getUsersByID(sql, uids); + List users = UserQueries.getUsersByID(sql, uids); if (users.size() > 0) { String json = userSerializer.serializeList(users); Main.replyJSON(request, response, json); diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java index c99432a6..35854171 100644 --- a/src/test/java/com/juick/tests/JsonTests.java +++ b/src/test/java/com/juick/tests/JsonTests.java @@ -14,6 +14,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; +import java.util.List; import java.util.Properties; public class JsonTests { @@ -40,10 +41,10 @@ public class JsonTests { @Test public void CompareSerializers() { - ArrayList mids = MessagesQueries.getMyFeed(sql, 3694, 2799786); + List mids = MessagesQueries.getMyFeed(sql, 3694, 2799786); MessageSerializer messageSerializer = new MessageSerializer(); if (mids != null && !mids.isEmpty()) { - ArrayList msgs = MessagesQueries.getMessages(sql, mids); + List msgs = MessagesQueries.getMessages(sql, mids); if (msgs != null && !msgs.isEmpty()) { String json = messageSerializer.serializeList(msgs); try { -- 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 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 d44d5be975b5196d7aa961e8fd3012f389626380 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 12:56:11 +0300 Subject: spring-jdbc WIP --- src/test/java/com/juick/tests/JsonTests.java | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java index 35854171..99d9ca46 100644 --- a/src/test/java/com/juick/tests/JsonTests.java +++ b/src/test/java/com/juick/tests/JsonTests.java @@ -10,41 +10,35 @@ import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; import java.util.Properties; +import org.apache.commons.dbcp2.BasicDataSource; +import org.springframework.jdbc.core.JdbcTemplate; public class JsonTests { - Connection sql; - + JdbcTemplate jdbc; @Before public void setupConnection() { Properties conf = new Properties(); try { conf.load(new FileInputStream("/etc/juick/api.conf")); - Class.forName("com.mysql.jdbc.Driver"); - sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + 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(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); } } @Test public void CompareSerializers() { - List mids = MessagesQueries.getMyFeed(sql, 3694, 2799786); + List mids = MessagesQueries.getMyFeed(jdbc, 3694, 2799786); MessageSerializer messageSerializer = new MessageSerializer(); if (mids != null && !mids.isEmpty()) { - List msgs = MessagesQueries.getMessages(sql, mids); + List msgs = MessagesQueries.getMessages(jdbc, mids); if (msgs != null && !msgs.isEmpty()) { String json = messageSerializer.serializeList(msgs); try { -- cgit v1.2.3 From c59c665fcbd5a7a8926bfba6b368efe7f568e167 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 13:03:04 +0300 Subject: fix tests --- src/test/java/com/juick/tests/ApiTests.java | 1 + src/test/java/com/juick/tests/JsonTests.java | 109 ++++++++++++++------------- 2 files changed, 56 insertions(+), 54 deletions(-) diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 01cdd4c5..f111ffc7 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -27,6 +27,7 @@ public class ApiTests { 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(); } diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java index 99d9ca46..496dea24 100644 --- a/src/test/java/com/juick/tests/JsonTests.java +++ b/src/test/java/com/juick/tests/JsonTests.java @@ -1,54 +1,55 @@ -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 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; -import org.apache.commons.dbcp2.BasicDataSource; -import org.springframework.jdbc.core.JdbcTemplate; - -public class JsonTests { - - 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 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(); - } - - } - } - } -} \ No newline at end of file +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 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; +import org.apache.commons.dbcp2.BasicDataSource; +import org.springframework.jdbc.core.JdbcTemplate; + +public class JsonTests { + + 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", "")); + 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(); + } + + } + } + } +} -- 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(-) 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(-) 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(-) 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 598b90ceedb51f11bd412f6a544bcc2d358dd028 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 15:02:31 +0300 Subject: fix test --- src/test/java/com/juick/tests/ApiTests.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index e67c23f2..b679f528 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -41,7 +41,8 @@ public class ApiTests { Assert.assertEquals("it should be me", "vt", user.UName); } - @Test void messageTests() { + @Test + public void messageTests() { Message msg = MessagesQueries.getMessage(jdbc, 2817722); User ugnich = msg.User; Assert.assertEquals("ugnich", ugnich.UName); -- 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(-) 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(-) 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(-) 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 093a022955d547e6f94a4204a193c0e7296c11b2 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 14:13:11 +0300 Subject: drop unneeded dependency --- build.gradle | 1 - src/main/java/com/juick/api/Main.java | 16 ++++++++-------- src/test/java/com/juick/tests/JsonTests.java | 6 +++--- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/build.gradle b/build.gradle index c2ca747e..380f5b39 100644 --- a/build.gradle +++ b/build.gradle @@ -54,7 +54,6 @@ dependencies { 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/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 71f7f2d7..4233c45d 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -20,9 +20,15 @@ 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 org.springframework.jdbc.datasource.DriverManagerDataSource; +import javax.servlet.ServletException; +import javax.servlet.annotation.MultipartConfig; +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; @@ -31,12 +37,6 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; -import javax.servlet.ServletException; -import javax.servlet.annotation.MultipartConfig; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; /** * @@ -65,7 +65,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { 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="); - BasicDataSource dataSource = new BasicDataSource(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl(sql.getMetaData().getURL()); dataSource.setDriverClassName(driverClassName); jdbc = new JdbcTemplate(dataSource); diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java index 496dea24..795b3429 100644 --- a/src/test/java/com/juick/tests/JsonTests.java +++ b/src/test/java/com/juick/tests/JsonTests.java @@ -5,6 +5,8 @@ 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; @@ -12,8 +14,6 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Properties; -import org.apache.commons.dbcp2.BasicDataSource; -import org.springframework.jdbc.core.JdbcTemplate; public class JsonTests { @@ -23,7 +23,7 @@ public class JsonTests { Properties conf = new Properties(); try { conf.load(new FileInputStream("/etc/juick/api.conf")); - BasicDataSource dataSource = new BasicDataSource(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") -- cgit v1.2.3 From b5b9d41d91f038780c8cf29ddacde82087e43a5a Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 14:14:15 +0300 Subject: drop unneeded dependency, part 2 --- src/test/java/com/juick/tests/ApiTests.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 046077ef..44cd7c1b 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -5,10 +5,10 @@ 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; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; import java.io.FileInputStream; import java.io.IOException; @@ -24,7 +24,7 @@ public class ApiTests { Properties conf = new Properties(); try { conf.load(new FileInputStream("/etc/juick/api.conf")); - BasicDataSource dataSource = new BasicDataSource(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") -- cgit v1.2.3 From 439d74c975c6485b501bf1cbbbc04ab47fde9cec Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 14:17:21 +0300 Subject: more tests --- src/test/java/com/juick/tests/ApiTests.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 44cd7c1b..ccd53dde 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -9,6 +9,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import sun.jvm.hotspot.utilities.MessageQueue; import java.io.FileInputStream; import java.io.IOException; @@ -46,6 +47,10 @@ public class ApiTests { Message msg = MessagesQueries.getMessage(jdbc, 2817722); User ugnich = msg.getUser(); Assert.assertEquals("ugnich", ugnich.getUName()); + org.junit.Assert.assertEquals("ugnich", MessagesQueries.getMessageAuthor(jdbc, 281772).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()); } } -- cgit v1.2.3 From 43f9f59b05915ba85709b28ab0a18ef083829fb3 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 14:18:03 +0300 Subject: fix imports --- src/test/java/com/juick/tests/ApiTests.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index ccd53dde..6a264c9a 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -2,14 +2,13 @@ package com.juick.tests; import com.juick.Message; import com.juick.User; -import com.juick.server.UserQueries; import com.juick.server.MessagesQueries; +import com.juick.server.UserQueries; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; -import sun.jvm.hotspot.utilities.MessageQueue; import java.io.FileInputStream; import java.io.IOException; -- cgit v1.2.3 From ed24ebac9a717fbec3357a168438e2617955d609 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 14:18:55 +0300 Subject: fix test --- src/test/java/com/juick/tests/ApiTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 6a264c9a..f7d6d6ac 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -46,7 +46,7 @@ public class ApiTests { Message msg = MessagesQueries.getMessage(jdbc, 2817722); User ugnich = msg.getUser(); Assert.assertEquals("ugnich", ugnich.getUName()); - org.junit.Assert.assertEquals("ugnich", MessagesQueries.getMessageAuthor(jdbc, 281772).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(); -- 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 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(-) 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(-) 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(-) 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 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(-) 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 222678a48ac72117deb2ad42e6e1da7fb025ce0c Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 17 Jan 2016 01:09:54 +0300 Subject: fix typo --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index e82e7e96..b76df16a 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' - testTuntime 'com.h2database:h2:1.4.190' + testRuntime 'com.h2database:h2:1.4.190' } compileJava.options.encoding = 'UTF-8' -- 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(-) 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(-) 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(-) 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(-) 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(-) 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 846d0b67d11ba9444a8a32ee173bb431683fa572 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 10:01:43 +0300 Subject: fix base64 usage --- src/main/java/com/juick/api/Utils.java | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java index 7a498a10..ca0518e1 100644 --- a/src/main/java/com/juick/api/Utils.java +++ b/src/main/java/com/juick/api/Utils.java @@ -18,27 +18,22 @@ package com.juick.api; import com.juick.server.UserQueries; +import org.springframework.jdbc.core.JdbcTemplate; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.Part; 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.Base64; 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; /** * @@ -46,8 +41,6 @@ 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) { @@ -85,14 +78,10 @@ public class Utils { public static int getHttpAuthUID(JdbcTemplate sql, HttpServletRequest request) { String auth = request.getHeader("Authorization"); if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) { - try { - BASE64Decoder dec = new BASE64Decoder(); - String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2); - if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) { - return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]); - } - } catch (IOException e) { - LOGGER.log(Level.WARNING, "Auth", e); + Base64.Decoder dec = Base64.getDecoder(); + String loginpassw[] = new String(dec.decode(auth.substring(6))).split(":", 2); + if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) { + return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]); } } return 0; -- cgit v1.2.3 From 70a6b6c49ee6e220942a43ae4328ce9dcd24232b Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 19:25:26 +0300 Subject: initial telegram bot --- build.gradle | 2 +- src/main/java/com/juick/api/Main.java | 13 +++++++---- src/main/java/com/juick/api/TelegramBotHook.java | 29 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/juick/api/TelegramBotHook.java diff --git a/build.gradle b/build.gradle index b76df16a..f6b37262 100644 --- a/build.gradle +++ b/build.gradle @@ -54,7 +54,7 @@ dependencies { compile xmpp compile json compile "org.apache.commons:commons-lang3:3.4" - compile "org.springframework:spring-jdbc:4.2.4.RELEASE" + compile 'com.github.pengrad:java-telegram-bot-api:2.0.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/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index c43804d7..003b9aa3 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -19,7 +19,10 @@ package com.juick.api; import com.juick.Tag; import com.juick.json.MessageSerializer; -import com.juick.server.*; +import com.juick.server.MessagesQueries; +import com.juick.server.SubscriptionsQueries; +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; @@ -40,8 +43,6 @@ 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; @@ -63,6 +64,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { Users users; PM pm; Others others; + TelegramBotHook tgb; @Override public void init() throws ServletException { @@ -79,7 +81,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { users = new Users(jdbc); pm = new PM(jdbc); others = new Others(jdbc); - + tgb = new TelegramBotHook(conf.getProperty("telegram_token", "")); setupXmppComponent(conf.getProperty("xmpp_host", "localhost"), Integer.parseInt(conf.getProperty("xmpp_port", "5347")), conf.getProperty("xmpp_jid", "api.localhost"), conf.getProperty("xmpp_password")); @@ -209,6 +211,9 @@ public class Main extends HttpServlet implements Stream.StreamListener { case "/pm": pm.doPostPM(request, response, xmpp, vuid); break; + case "/tlgmbtwbhk": + tgb.doPost(request, response); + break; default: response.sendError(405); break; diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java new file mode 100644 index 00000000..6d73fbfb --- /dev/null +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -0,0 +1,29 @@ +package com.juick.api; + +import com.pengrad.telegrambot.TelegramBot; +import com.pengrad.telegrambot.TelegramBotAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.logging.Logger; + +/** + * Created by vt on 12/05/16. + */ +public class TelegramBotHook { + private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName()); + + private String token; + TelegramBot bot; + + + public TelegramBotHook(String token) { + this.token = token; + bot = TelegramBotAdapter.build(token); + bot.setWebhook("https://api.juick.com/tlgmbtwbhk"); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) { + logger.info("got telegram msg: " + request); + } +} -- cgit v1.2.3 From c58e021d8631fd8e1dd1d40546a4aabce27e2cdf Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 22:27:41 +0300 Subject: parse update --- src/main/java/com/juick/api/Main.java | 6 +++++- src/main/java/com/juick/api/TelegramBotHook.java | 12 ++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 003b9aa3..7d5c8f1b 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -127,12 +127,16 @@ public class Main extends HttpServlet implements Stream.StreamListener { request.setCharacterEncoding("UTF-8"); } + String uri = request.getRequestURI(); + if (uri.equals("/tlgmbtwbhk")) { + tgb.doPost(request, response); + return; + } int vuid = Utils.getHttpAuthUID(jdbc, request); if (vuid == 0) { vuid = Utils.getVisitorQueryStringUID(jdbc, request); } - String uri = request.getRequestURI(); if (uri.equals("/home")) { if (vuid > 0) { messages.doGetHome(request, response, vuid); diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 6d73fbfb..a502e846 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -1,10 +1,14 @@ package com.juick.api; +import com.pengrad.telegrambot.BotUtils; import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.TelegramBotAdapter; +import com.pengrad.telegrambot.model.Update; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.IOException; import java.util.logging.Logger; /** @@ -23,7 +27,11 @@ public class TelegramBotHook { bot.setWebhook("https://api.juick.com/tlgmbtwbhk"); } - public void doPost(HttpServletRequest request, HttpServletResponse response) { - logger.info("got telegram msg: " + request); + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { + StringBuilder sb = new StringBuilder(); + try (BufferedReader reader = request.getReader()) { + Update update = BotUtils.parseUpdate(reader); + logger.info("got telegram msg: " + update.message().toString()); + } } } -- cgit v1.2.3 From 01cf5ebb4e9db6458bdda762454b699593f796f5 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 22:30:23 +0300 Subject: use post not get --- src/main/java/com/juick/api/Main.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 7d5c8f1b..7a571fe0 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -128,10 +128,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { } String uri = request.getRequestURI(); - if (uri.equals("/tlgmbtwbhk")) { - tgb.doPost(request, response); - return; - } + int vuid = Utils.getHttpAuthUID(jdbc, request); if (vuid == 0) { vuid = Utils.getVisitorQueryStringUID(jdbc, request); @@ -192,6 +189,11 @@ public class Main extends HttpServlet implements Stream.StreamListener { if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("UTF-8"); } + String uri = request.getRequestURI(); + if (uri.equals("/tlgmbtwbhk")) { + tgb.doPost(request, response); + return; + } int vuid = Utils.getHttpAuthUID(jdbc, request); if (vuid == 0) { @@ -201,8 +203,6 @@ public class Main extends HttpServlet implements Stream.StreamListener { response.sendError(401); return; } - - String uri = request.getRequestURI(); switch (uri) { case "/post": int mid = Utils.parseInt(request.getParameter("mid"), 0); @@ -215,9 +215,6 @@ public class Main extends HttpServlet implements Stream.StreamListener { case "/pm": pm.doPostPM(request, response, xmpp, vuid); break; - case "/tlgmbtwbhk": - tgb.doPost(request, response); - break; default: response.sendError(405); break; -- cgit v1.2.3 From a24822ad17cc4be9ccaa01badfd17f193867e457 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 22:53:12 +0300 Subject: forward all juick messages --- build.gradle | 1 + src/main/java/com/juick/api/Main.java | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 57 ++++++++++++++++++++---- 3 files changed, 51 insertions(+), 9 deletions(-) diff --git a/build.gradle b/build.gradle index f6b37262..d9317928 100644 --- a/build.gradle +++ b/build.gradle @@ -55,6 +55,7 @@ dependencies { compile json compile "org.apache.commons:commons-lang3:3.4" compile 'com.github.pengrad:java-telegram-bot-api:2.0.1' + compile 'com.neovisionaries:nv-websocket-client:1.27' 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/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 7a571fe0..6adef22a 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -191,7 +191,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { } String uri = request.getRequestURI(); if (uri.equals("/tlgmbtwbhk")) { - tgb.doPost(request, response); + tgb.doPost(request); return; } diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index a502e846..b6cd16ab 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -1,14 +1,25 @@ package com.juick.api; +import com.juick.json.MessageSerializer; +import com.neovisionaries.ws.client.WebSocket; +import com.neovisionaries.ws.client.WebSocketAdapter; +import com.neovisionaries.ws.client.WebSocketFactory; +import com.neovisionaries.ws.client.WebSocketListener; import com.pengrad.telegrambot.BotUtils; +import com.pengrad.telegrambot.Callback; import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.TelegramBotAdapter; -import com.pengrad.telegrambot.model.Update; +import com.pengrad.telegrambot.model.Message; +import com.pengrad.telegrambot.request.SendMessage; +import com.pengrad.telegrambot.response.SendResponse; +import org.json.JSONObject; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; import java.util.logging.Logger; /** @@ -17,21 +28,51 @@ import java.util.logging.Logger; public class TelegramBotHook { private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName()); - private String token; TelegramBot bot; + List chats = new ArrayList<>(); + WebSocket ws; + MessageSerializer ms = new MessageSerializer(); public TelegramBotHook(String token) { - this.token = token; bot = TelegramBotAdapter.build(token); bot.setWebhook("https://api.juick.com/tlgmbtwbhk"); + try { + ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all"); + ws.addListener(new WebSocketAdapter() { + @Override + public void onTextMessage(WebSocket websocket, String text) throws Exception { + super.onTextMessage(websocket, text); + com.juick.Message jmsg = ms.deserialize(new JSONObject(text)); + logger.info("got jmsg: " + jmsg.toString()); + chats.stream().forEach(c -> { + bot.execute(new SendMessage(c, jmsg.getText()), 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); + } + }); + }); + } + }); + } catch (IOException e) { + logger.log(Level.SEVERE, "couldn't create ws connection", e); + } } - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { - StringBuilder sb = new StringBuilder(); + public void doPost(HttpServletRequest request) throws IOException { try (BufferedReader reader = request.getReader()) { - Update update = BotUtils.parseUpdate(reader); - logger.info("got telegram msg: " + update.message().toString()); + Message message = BotUtils.parseUpdate(reader).message(); + logger.info("got telegram msg: " + message.toString()); + if (!chats.contains(message.chat().id())) { + chats.add(message.chat().id()); + logger.info("added chat with " + message.from().firstName()); + } } } } -- cgit v1.2.3 From 2c7fb63528ee2544d2c9f6f32047c9178618331b Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 22:58:07 +0300 Subject: forgot to connect --- src/main/java/com/juick/api/TelegramBotHook.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index b6cd16ab..83eea314 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -1,10 +1,7 @@ package com.juick.api; import com.juick.json.MessageSerializer; -import com.neovisionaries.ws.client.WebSocket; -import com.neovisionaries.ws.client.WebSocketAdapter; -import com.neovisionaries.ws.client.WebSocketFactory; -import com.neovisionaries.ws.client.WebSocketListener; +import com.neovisionaries.ws.client.*; import com.pengrad.telegrambot.BotUtils; import com.pengrad.telegrambot.Callback; import com.pengrad.telegrambot.TelegramBot; @@ -19,6 +16,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; @@ -40,6 +38,10 @@ public class TelegramBotHook { try { ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all"); ws.addListener(new WebSocketAdapter() { + @Override + public void onConnected(WebSocket websocket, Map> headers) { + logger.info("ws connected"); + } @Override public void onTextMessage(WebSocket websocket, String text) throws Exception { super.onTextMessage(websocket, text); @@ -60,7 +62,8 @@ public class TelegramBotHook { }); } }); - } catch (IOException e) { + ws.connect(); + } catch (IOException | WebSocketException e) { logger.log(Level.SEVERE, "couldn't create ws connection", e); } } -- cgit v1.2.3 From d77b21dcf62c3e8d63615d5ef5acaaaf2614736d Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 23:32:50 +0300 Subject: add ping --- src/main/java/com/juick/api/TelegramBotHook.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 83eea314..2d64b83e 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -37,7 +37,15 @@ public class TelegramBotHook { bot.setWebhook("https://api.juick.com/tlgmbtwbhk"); try { ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all"); + ws.addHeader("Origin", "ws.juick.com"); + ws.addHeader("Host", "ws.juick.com"); //TODO: remove from server + ws.setPingInterval(60 * 1000); ws.addListener(new WebSocketAdapter() { + @Override + public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception { + logger.info("ws disconnected"); + } + @Override public void onConnected(WebSocket websocket, Map> headers) { logger.info("ws connected"); -- cgit v1.2.3 From 0879730b19ac8d5ea2250c320a17de0ed7361bb3 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 23:37:48 +0300 Subject: notify subscribed users --- src/main/java/com/juick/api/TelegramBotHook.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 2d64b83e..7ee759eb 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -83,6 +83,17 @@ public class TelegramBotHook { if (!chats.contains(message.chat().id())) { chats.add(message.chat().id()); logger.info("added chat with " + message.from().firstName()); + bot.execute(new SendMessage(message.chat().id(), "Subscribed!"), 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); + } + }); } } } -- cgit v1.2.3 From daab143efa277ca42e60dcd29daeddbfa5179ace Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 09:32:46 +0300 Subject: gretty --- build.gradle | 26 ++++++++++---------------- src/main/java/com/juick/api/Main.java | 13 +++++++------ 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/build.gradle b/build.gradle index b76df16a..84617e95 100644 --- a/build.gradle +++ b/build.gradle @@ -4,21 +4,20 @@ subprojects { mavenCentral() } } - buildscript { repositories { mavenCentral() jcenter() } dependencies { - classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.+' + classpath 'org.akhikhl.gretty:gretty:+' classpath 'com.tkruse.gradle:gradle-groovysh-plugin:1.0.7' } } apply plugin: 'java' apply plugin: 'war' -apply plugin: 'com.bmuschko.tomcat' +apply plugin: 'org.akhikhl.gretty' apply plugin: 'com.github.tkruse.groovysh' repositories { @@ -35,39 +34,34 @@ project(':deps:com.juick.server') { compile core } } - project(':deps:com.juick.xmpp') { dependencies { compile core } } - project(':deps:com.juick.json') { dependencies { compile core } } - +configurations.all { + exclude group: "commons-logging", module: "commons-logging" +} dependencies { compile core compile server compile xmpp compile json compile "org.apache.commons:commons-lang3:3.4" - compile "org.springframework:spring-jdbc:4.2.4.RELEASE" + compile "org.springframework:spring-jdbc:4.2.6.RELEASE" providedCompile 'javax.servlet:javax.servlet-api:3.1.0' - def tomcatVersion = '7.0.+' - tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}", - "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' + compile 'javax.inject:javax.inject:1' + runtime 'mysql:mysql-connector-java:5.1.39' testRuntime 'com.h2database:h2:1.4.190' } - compileJava.options.encoding = 'UTF-8' - -tomcat { +gretty { httpPort = 8080 contextPath = '/' + servletContainer = 'tomcat8' } diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index c43804d7..09fb51ec 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -19,7 +19,10 @@ package com.juick.api; import com.juick.Tag; import com.juick.json.MessageSerializer; -import com.juick.server.*; +import com.juick.server.MessagesQueries; +import com.juick.server.SubscriptionsQueries; +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; @@ -40,8 +43,6 @@ 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; @@ -68,11 +69,11 @@ 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")); + LogManager.getLogManager().readConfiguration(getServletContext().getResourceAsStream("/WEB-INF/logging.properties")); Properties conf = new Properties(); - conf.load(getServletContext().getResourceAsStream("WEB-INF/juick.conf")); + conf.load(getServletContext().getResourceAsStream("/WEB-INF/juick.conf")); DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(conf.getProperty("datasource_driver")); + dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); dataSource.setUrl(conf.getProperty("datasource_url")); jdbc = new JdbcTemplate(dataSource); messages = new Messages(jdbc); -- cgit v1.2.3 From 0713cb62f8abf99252ce9e07c06e40c96f04f3b0 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 11:26:18 +0300 Subject: fix merge --- build.gradle | 3 +++ src/test/java/com/juick/tests/ApiTests.java | 5 ++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 84617e95..1cffaf68 100644 --- a/build.gradle +++ b/build.gradle @@ -56,7 +56,10 @@ dependencies { compile "org.springframework:spring-jdbc:4.2.6.RELEASE" providedCompile 'javax.servlet:javax.servlet-api:3.1.0' compile 'javax.inject:javax.inject:1' + compile 'com.github.pengrad:java-telegram-bot-api:2.0.1' + compile 'com.neovisionaries:nv-websocket-client:1.27' runtime 'mysql:mysql-connector-java:5.1.39' + testCompile 'junit:junit:4.12' testRuntime 'com.h2database:h2:1.4.190' } compileJava.options.encoding = 'UTF-8' diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 7b0264c0..5bd90509 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -7,8 +7,7 @@ import com.juick.server.MessagesQueries; import com.juick.server.SubscriptionsQueries; import com.juick.server.TagQueries; import com.juick.server.UserQueries; -import junit.framework.Assert; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; @@ -92,7 +91,7 @@ public class ApiTests { } - @Test + @Test public void messageTests() { int user_id = UserQueries.createUser(jdbc, "me", "secret"); User user = UserQueries.getUserByUID(jdbc, user_id); -- cgit v1.2.3 From c0115554aac7106974e12fd5b66ceaf69cee6e84 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 11:26:34 +0300 Subject: full message format --- src/main/java/com/juick/api/TelegramBotHook.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 7ee759eb..6a6404de 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -54,9 +54,15 @@ public class TelegramBotHook { public void onTextMessage(WebSocket websocket, String text) throws Exception { super.onTextMessage(websocket, text); com.juick.Message jmsg = ms.deserialize(new JSONObject(text)); - logger.info("got jmsg: " + jmsg.toString()); + logger.info("got jmsg: " + ms.serialize(jmsg).toString()); + StringBuilder sb = new StringBuilder(); + sb.append(jmsg.getUser()).append("\n").append(jmsg.getText()).append("\n"); + if (jmsg.getAttachmentURL() != null) { + sb.append(jmsg.getAttachmentURL()); + } + sb.append("https://juick.com/" + jmsg.getMID()); chats.stream().forEach(c -> { - bot.execute(new SendMessage(c, jmsg.getText()), new Callback() { + bot.execute(new SendMessage(c, sb.toString()), new Callback() { @Override public void onResponse(SendMessage request, SendResponse response) { logger.info("got response: " + response.message().toString()); -- cgit v1.2.3 From e9202d13bca4894efb7e365d42eb9b703a0dc7eb Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 11:33:17 +0300 Subject: full message format, take 2 --- build.gradle | 3 --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 1cffaf68..d11187c4 100644 --- a/build.gradle +++ b/build.gradle @@ -44,9 +44,6 @@ project(':deps:com.juick.json') { compile core } } -configurations.all { - exclude group: "commons-logging", module: "commons-logging" -} dependencies { compile core compile server diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 6a6404de..90c644af 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -56,7 +56,7 @@ public class TelegramBotHook { com.juick.Message jmsg = ms.deserialize(new JSONObject(text)); logger.info("got jmsg: " + ms.serialize(jmsg).toString()); StringBuilder sb = new StringBuilder(); - sb.append(jmsg.getUser()).append("\n").append(jmsg.getText()).append("\n"); + sb.append("@").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n"); if (jmsg.getAttachmentURL() != null) { sb.append(jmsg.getAttachmentURL()); } -- cgit v1.2.3 From 324391a3b775f6508b316f72268d776e50aff2cc Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 11:48:19 +0300 Subject: full message format, take 3 --- src/main/java/com/juick/api/TelegramBotHook.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 90c644af..ed3e8942 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -60,9 +60,10 @@ public class TelegramBotHook { if (jmsg.getAttachmentURL() != null) { sb.append(jmsg.getAttachmentURL()); } - sb.append("https://juick.com/" + jmsg.getMID()); + sb.append("https://juick.com/").append(jmsg.getMID()); + String msg = sb.toString(); chats.stream().forEach(c -> { - bot.execute(new SendMessage(c, sb.toString()), new Callback() { + bot.execute(new SendMessage(c, msg), new Callback() { @Override public void onResponse(SendMessage request, SendResponse response) { logger.info("got response: " + response.message().toString()); -- cgit v1.2.3 From 950177ab7959590cfd9c8678b6dbe563fcc964e0 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 12:11:52 +0300 Subject: store chats in db --- src/main/java/com/juick/api/Main.java | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 9b327e83..c632d8fc 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -81,7 +81,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { users = new Users(jdbc); pm = new PM(jdbc); others = new Others(jdbc); - tgb = new TelegramBotHook(conf.getProperty("telegram_token", "")); + tgb = new TelegramBotHook(jdbc, conf.getProperty("telegram_token", "")); setupXmppComponent(conf.getProperty("xmpp_host", "localhost"), Integer.parseInt(conf.getProperty("xmpp_port", "5347")), conf.getProperty("xmpp_jid", "api.localhost"), conf.getProperty("xmpp_password")); diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index ed3e8942..d06473a3 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -10,6 +10,7 @@ import com.pengrad.telegrambot.model.Message; import com.pengrad.telegrambot.request.SendMessage; import com.pengrad.telegrambot.response.SendResponse; import org.json.JSONObject; +import org.springframework.jdbc.core.JdbcTemplate; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; @@ -27,12 +28,13 @@ public class TelegramBotHook { private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName()); TelegramBot bot; - List chats = new ArrayList<>(); WebSocket ws; MessageSerializer ms = new MessageSerializer(); + JdbcTemplate jdbc; - public TelegramBotHook(String token) { + public TelegramBotHook(JdbcTemplate jdbc, String token) { + this.jdbc = jdbc; bot = TelegramBotAdapter.build(token); bot.setWebhook("https://api.juick.com/tlgmbtwbhk"); try { @@ -62,6 +64,7 @@ public class TelegramBotHook { } sb.append("https://juick.com/").append(jmsg.getMID()); String msg = sb.toString(); + List chats = getChats(); chats.stream().forEach(c -> { bot.execute(new SendMessage(c, msg), new Callback() { @Override @@ -83,12 +86,20 @@ public class TelegramBotHook { } } + List getChats() { + return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class); + } + void addChat(Long id) { + jdbc.update("INSERT IGNORE TO telegram_chats(chat_id) VALUES(?)", id); + } + public void doPost(HttpServletRequest request) throws IOException { try (BufferedReader reader = request.getReader()) { Message message = BotUtils.parseUpdate(reader).message(); logger.info("got telegram msg: " + message.toString()); + List chats = getChats(); if (!chats.contains(message.chat().id())) { - chats.add(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() { @Override -- cgit v1.2.3 From 2a595eb7e7f0c220f38b1501b75d97f7b8a234a3 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 12:33:52 +0300 Subject: store chats in db, fix --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index d06473a3..880be5e2 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -90,7 +90,7 @@ public class TelegramBotHook { return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class); } void addChat(Long id) { - jdbc.update("INSERT IGNORE TO telegram_chats(chat_id) VALUES(?)", id); + jdbc.update("INSERT IGNORE INTO telegram_chats(chat_id) VALUES(?)", id); } public void doPost(HttpServletRequest request) throws IOException { -- cgit v1.2.3 From d7b8c7307b09a0dad102c37863bd03d551b5c8a9 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 14:47:14 +0300 Subject: url as button --- src/main/java/com/juick/api/TelegramBotHook.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 880be5e2..cf0979cd 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -7,6 +7,8 @@ import com.pengrad.telegrambot.Callback; import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.TelegramBotAdapter; import com.pengrad.telegrambot.model.Message; +import com.pengrad.telegrambot.model.request.InlineKeyboardButton; +import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup; import com.pengrad.telegrambot.request.SendMessage; import com.pengrad.telegrambot.response.SendResponse; import org.json.JSONObject; @@ -15,7 +17,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; @@ -62,11 +63,15 @@ public class TelegramBotHook { if (jmsg.getAttachmentURL() != null) { sb.append(jmsg.getAttachmentURL()); } - sb.append("https://juick.com/").append(jmsg.getMID()); String msg = sb.toString(); List chats = getChats(); chats.stream().forEach(c -> { - bot.execute(new SendMessage(c, msg), new Callback() { + 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()); -- 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(-) 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 9cd79ef58a443289aa6756e8fbfabf5fe9ac8630 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 16:15:13 +0300 Subject: fix login type --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 9b75a4ae..05b99b02 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -115,7 +115,7 @@ public class TelegramBotHook { "what do you want to receive").replyMarkup( new InlineKeyboardMarkup( new InlineKeyboardButton[]{ - new InlineKeyboardButton("LOGIN").url("http://juick.com/signup?type=d&hash=" + + new InlineKeyboardButton("LOGIN").url("http://juick.com/signup?type=durov&hash=" + UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue())) })), new Callback() { @Override -- cgit v1.2.3 From 0400e141715d44e6cb8f25a3709e86a2d1ac7a1a Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 16:32:24 +0300 Subject: fix typo --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 05b99b02..c68d829a 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -132,7 +132,7 @@ public class TelegramBotHook { } } private boolean createTelegramUser(long tgID, String tgName) { - return jdbc.update("INSERT INTO telegram(tg_ig, tg_name, loginhash) VALUES(?,?,?)", + return jdbc.update("INSERT INTO telegram(tg_id, 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(-) 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 15f02eb428584970a95ce5787299f32b432b9a80 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 19:57:24 +0300 Subject: telegram: fix user query --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 907898f2..0cc3aa84 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -146,7 +146,7 @@ public class TelegramBotHook { } private Optional getUser(long tgId) { try { - return Optional.of(jdbc.queryForObject("SELECT id, name, banned FROM users INNER JOIN telegram" + + 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)); } catch (EmptyResultDataAccessException e) { return Optional.empty(); -- cgit v1.2.3 From 2b49c5d7215aa5bd75b14101ca48c872b232bc79 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 20:14:21 +0300 Subject: comment notifications --- src/main/java/com/juick/api/TelegramBotHook.java | 46 +++++++++++++++++++++--- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 907898f2..40ff5411 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -34,7 +34,7 @@ public class TelegramBotHook { private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName()); TelegramBot bot; - WebSocket ws; + WebSocket ws, wsReply; MessageSerializer ms = new MessageSerializer(); JdbcTemplate jdbc; @@ -72,22 +72,54 @@ public class TelegramBotHook { List users = getSubscribers(jmsg.getUser().getUID()); List chats = getChats(); // registered subscribed users - users.stream().forEach(c -> telegramNotify(c, msg, jmsg.getMID())); + 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, jmsg.getMID())); + chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, msgUrl)); } }); ws.connect(); + wsReply = new WebSocketFactory().createSocket("wss://ws.juick.com/_replies"); + wsReply.addHeader("Origin", "ws.juick.com"); + wsReply.addHeader("Host", "ws.juick.com"); + wsReply.setPingInterval(60 * 1000); + wsReply.addListener(new WebSocketAdapter() { + @Override + public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception { + logger.info("ws replies disconnected"); + } + + @Override + public void onConnected(WebSocket websocket, Map> headers) throws Exception { + logger.info("ws replies connected"); + } + + @Override + public void onTextMessage(WebSocket websocket, String text) throws Exception { + com.juick.Message jmsg = ms.deserialize(new JSONObject(text)); + logger.info(String.format("got jmsg: %s", ms.serialize(jmsg).toString())); + StringBuilder sb = new StringBuilder(); + sb.append("Reply from @").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n"); + if (jmsg.getAttachmentURL() != null) { + sb.append(jmsg.getAttachmentURL()); + } + String msg = sb.toString(); + String msgUrl = String.format("https://juick.com/%d#%d", jmsg.getMID(), jmsg.getRID()); + getSubscribersToComments(jmsg.getMID(), jmsg.getUser().getUID()).stream() + .forEach(c -> telegramNotify(c, msg, msgUrl)); + } + }); + wsReply.connect(); } catch (IOException | WebSocketException e) { logger.log(Level.SEVERE, "couldn't create ws connection", e); } } - private void telegramNotify(Long c, String msg, int mid) { + private void telegramNotify(Long c, String msg, String msgUrl) { bot.execute(new SendMessage(c, msg).replyMarkup( new InlineKeyboardMarkup( new InlineKeyboardButton[] { - new InlineKeyboardButton("See on Juick").url("https://juick.com/" + mid) + new InlineKeyboardButton("See on Juick").url(msgUrl) } )), new Callback() { @Override @@ -156,4 +188,8 @@ public class TelegramBotHook { 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); } + private List getSubscribersToComments(int mid, int ignore_uid) { + return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " + + "ON (telegram.user_id=subscr_messages.suser_id) WHERE message_id=? AND suser_id!=?", Long.class, mid, ignore_uid); + } } -- cgit v1.2.3 From 9be74d0e4b5c62e54685483b132c0311bc8aed2a Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 20:42:48 +0300 Subject: fix subscribers query --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 97418418..9a743bc1 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -186,7 +186,7 @@ public class TelegramBotHook { } 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); + "ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid, uid); } private List getSubscribersToComments(int mid, int ignore_uid) { return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " + -- cgit v1.2.3 From b4e6e2092606afb2a321fd07f5bdb687ef03356e Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 20:50:09 +0300 Subject: telegram reply quote --- src/main/java/com/juick/api/TelegramBotHook.java | 26 ++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 9a743bc1..a9a35683 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -2,6 +2,7 @@ package com.juick.api; import com.juick.User; import com.juick.json.MessageSerializer; +import com.juick.server.MessagesQueries; import com.juick.server.UserQueries; import com.neovisionaries.ws.client.*; import com.pengrad.telegrambot.BotUtils; @@ -99,9 +100,10 @@ public class TelegramBotHook { com.juick.Message jmsg = ms.deserialize(new JSONObject(text)); logger.info(String.format("got jmsg: %s", ms.serialize(jmsg).toString())); StringBuilder sb = new StringBuilder(); - sb.append("Reply from @").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n"); + sb.append("Reply by @").append(jmsg.getUser().getUName()).append(":\n") + .append(getReplyQuote(jmsg.getMID(), jmsg.ReplyTo)).append("\n").append(jmsg.getText()); if (jmsg.getAttachmentURL() != null) { - sb.append(jmsg.getAttachmentURL()); + sb.append("\n").append(jmsg.getAttachmentURL()); } String msg = sb.toString(); String msgUrl = String.format("https://juick.com/%d#%d", jmsg.getMID(), jmsg.getRID()); @@ -192,4 +194,24 @@ public class TelegramBotHook { return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " + "ON (telegram.user_id=subscr_messages.suser_id) WHERE message_id=? AND suser_id!=?", Long.class, mid, ignore_uid); } + private String getReplyQuote(int MID, int ReplyTo) { + String quote = ""; + if (ReplyTo > 0) { + com.juick.Message q = MessagesQueries.getReply(jdbc, MID, ReplyTo); + if (q != null) { + quote = q.getText(); + } + } else { + com.juick.Message q = MessagesQueries.getMessage(jdbc, MID); + if (q != null) { + quote = q.getText(); + } + } + if (quote.length() > 50) { + quote = ">" + quote.substring(0, 47).replace('\n', ' ') + "...\n"; + } else if (quote.length() > 0) { + quote = ">" + quote.replace('\n', ' ') + "\n"; + } + return quote; + } } -- cgit v1.2.3 From 7c7d4de2f68a22b63920dd4662ab530cc1b6ecfe Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 21:06:28 +0300 Subject: improve login flow --- src/main/java/com/juick/api/TelegramBotHook.java | 54 +++++++++++++++--------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index a9a35683..80ae0649 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -146,34 +146,48 @@ public class TelegramBotHook { public void doPost(HttpServletRequest request) throws IOException { try (BufferedReader reader = request.getReader()) { Message message = BotUtils.parseUpdate(reader).message(); - logger.info("got telegram msg: " + message.toString()); + User user_from = 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())) { addChat(message.chat().id()); logger.info("added chat with " + message.from().firstName()); 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=durov&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()); - } - - @Override - public void onFailure(SendMessage request, IOException e) { - logger.log(Level.WARNING, "telegram failure", e); - } - }); + telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue())); + } else { + if (user_from.getUID() == 0) { + telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue())); + } 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()); + telegramNotify(message.from().id().longValue(), msg, msgUrl); + } } } } + + private void telegramSignupNotify(Long telegramId, String hash) { + bot.execute(new SendMessage(telegramId, + "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("SIGNUP").url("http://juick.com/signup?type=durov&hash=" + + hash) + })), 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); + } + }); + } + private boolean createTelegramUser(long tgID, String tgName) { return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)", tgID, tgName, UUID.randomUUID().toString()) > 0; -- cgit v1.2.3 From 2dd33510e9b82174605bc0f19514cf04d194fe52 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 21:09:38 +0300 Subject: fix user query --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 80ae0649..6b1f946c 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -194,7 +194,7 @@ public class TelegramBotHook { } private Optional getUser(long tgId) { try { - return Optional.of(jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram" + + 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)); } catch (EmptyResultDataAccessException e) { return Optional.empty(); -- 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(-) 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(-) 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 c622ff7f5a99277c0c27da1eba527c1257471ae0 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 20 May 2016 00:03:04 +0300 Subject: fix sql --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 8bbf0e33..48e6bccb 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -202,7 +202,7 @@ public class TelegramBotHook { } private List getSubscribers(int uid) { return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " + - "ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid, uid); + "ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid); } private List getSubscribersToComments(int mid, int ignore_uid) { return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " + -- cgit v1.2.3 From 3c47c5763ad624ac525cd8d2c19b08b61a55fcda Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 20 May 2016 00:13:11 +0300 Subject: fix query --- src/main/java/com/juick/api/TelegramBotHook.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 48e6bccb..fa05c2f0 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -194,7 +194,7 @@ public class TelegramBotHook { } private int getUser(long tgId) { try { - return jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram " + + return jdbc.queryForObject("SELECT id FROM users INNER JOIN telegram " + "ON telegram.user_id = users.id WHERE telegram.tg_id=?", Integer.class, tgId); } catch (EmptyResultDataAccessException e) { return 0; -- 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(-) 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 f2d66113d764f81d58905256a0f74e4f2ebd19f0 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 7 Jun 2016 18:56:02 +0300 Subject: telegram: use first name when username is not set --- src/main/java/com/juick/api/TelegramBotHook.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 8c23973e..ccfa2c11 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -149,14 +149,18 @@ public class TelegramBotHook { 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(); + String username = message.from().username(); + if (username == null) { + username = message.from().firstName(); + } if (!chats.contains(message.chat().id())) { 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(), message.from().username())); + logger.info("added chat with " + username); + createTelegramUser(message.from().id(), username); + telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), username)); } else { if (user_from.getUID() == 0) { - telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), message.from().username())); + telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), 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 904a06d013f999e98724b222e6a4b48f68ddf32f Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 7 Jun 2016 19:01:40 +0300 Subject: fix indentation and update telegram library --- build.gradle | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/build.gradle b/build.gradle index d11187c4..0d69481d 100644 --- a/build.gradle +++ b/build.gradle @@ -53,7 +53,7 @@ dependencies { compile "org.springframework:spring-jdbc:4.2.6.RELEASE" providedCompile 'javax.servlet:javax.servlet-api:3.1.0' compile 'javax.inject:javax.inject:1' - compile 'com.github.pengrad:java-telegram-bot-api:2.0.1' + compile 'com.github.pengrad:java-telegram-bot-api:2.1.1' compile 'com.neovisionaries:nv-websocket-client:1.27' runtime 'mysql:mysql-connector-java:5.1.39' testCompile 'junit:junit:4.12' diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index ccfa2c11..2e1ac20c 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -42,7 +42,7 @@ public class TelegramBotHook { public TelegramBotHook(JdbcTemplate jdbc, String token) { this.jdbc = jdbc; - bot = TelegramBotAdapter.build(token); + bot = TelegramBotAdapter.build(token); bot.setWebhook("https://api.juick.com/tlgmbtwbhk"); try { ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all"); @@ -59,6 +59,7 @@ public class TelegramBotHook { public void onConnected(WebSocket websocket, Map> headers) { logger.info("ws connected"); } + @Override public void onTextMessage(WebSocket websocket, String text) throws Exception { super.onTextMessage(websocket, text); @@ -120,7 +121,7 @@ public class TelegramBotHook { private void telegramNotify(Long c, String msg, String msgUrl) { bot.execute(new SendMessage(c, msg).replyMarkup( new InlineKeyboardMarkup( - new InlineKeyboardButton[] { + new InlineKeyboardButton[]{ new InlineKeyboardButton("See on Juick").url(msgUrl) } )), new Callback() { @@ -139,6 +140,7 @@ public class TelegramBotHook { List getChats() { return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class); } + void addChat(Long id) { jdbc.update("INSERT IGNORE INTO telegram_chats(chat_id) VALUES(?)", id); } @@ -149,10 +151,10 @@ public class TelegramBotHook { 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(); - String username = message.from().username(); - if (username == null) { - username = message.from().firstName(); - } + String username = message.from().username(); + if (username == null) { + username = message.from().firstName(); + } if (!chats.contains(message.chat().id())) { addChat(message.chat().id()); logger.info("added chat with " + username); @@ -196,6 +198,7 @@ public class TelegramBotHook { return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)", tgID, tgName, UUID.randomUUID().toString()) > 0; } + private int getUser(long tgId) { try { return jdbc.queryForObject("SELECT id FROM users INNER JOIN telegram " + @@ -204,14 +207,17 @@ public class TelegramBotHook { return 0; } } + private List getSubscribers(int uid) { return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " + "ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid); } + private List getSubscribersToComments(int mid, int ignore_uid) { return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " + "ON (telegram.user_id=subscr_messages.suser_id) WHERE message_id=? AND suser_id!=?", Long.class, mid, ignore_uid); } + private String getReplyQuote(int MID, int ReplyTo) { String quote = ""; if (ReplyTo > 0) { -- cgit v1.2.3 From 0a2d8c6b44acc8f9e4ca3a70bcd891ff903f1708 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 7 Jun 2016 19:35:57 +0300 Subject: telegram: show tags --- src/main/java/com/juick/api/TelegramBotHook.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 2e1ac20c..e3afdd51 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -23,7 +23,6 @@ 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,7 +65,8 @@ public class TelegramBotHook { com.juick.Message jmsg = ms.deserialize(new JSONObject(text)); logger.info("got jmsg: " + ms.serialize(jmsg).toString()); StringBuilder sb = new StringBuilder(); - sb.append("@").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n"); + sb.append("@").append(jmsg.getUser().getUName()).append(":\n") + .append(jmsg.getTagsString()).append("\n").append(jmsg.getText()).append("\n"); if (jmsg.getAttachmentURL() != null) { sb.append(jmsg.getAttachmentURL()); } -- cgit v1.2.3 From 76f8fcd4269ac99bf2522a8ef2fa565bddd2a6fc Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 27 Jun 2016 16:02:23 +0300 Subject: update deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deps/com.juick.server b/deps/com.juick.server index 1ce6bc55..9d182aa4 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 1ce6bc55817129159b1cda5076d039e9c3bc8508 +Subproject commit 9d182aa45b5e2428ba684973837a8d035c0d50a2 -- cgit v1.2.3 From 5df4a0d2631e31e4c035aaedec1d6d50e3bdb098 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 27 Jun 2016 16:02:40 +0300 Subject: telegram: try to add photo --- src/main/java/com/juick/api/TelegramBotHook.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index e3afdd51..429b55f3 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -67,8 +67,8 @@ public class TelegramBotHook { StringBuilder sb = new StringBuilder(); sb.append("@").append(jmsg.getUser().getUName()).append(":\n") .append(jmsg.getTagsString()).append("\n").append(jmsg.getText()).append("\n"); - if (jmsg.getAttachmentURL() != null) { - sb.append(jmsg.getAttachmentURL()); + if (jmsg.Photo != null) { + sb.append(jmsg.Photo); } String msg = sb.toString(); List users = getSubscribers(jmsg.getUser().getUID()); -- cgit v1.2.3 From 1f631483bbed66a5afee88eb8341880a40075a7c Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 27 Jun 2016 16:38:56 +0300 Subject: fix compilation --- src/main/java/com/juick/api/PM.java | 4 ++-- src/main/java/com/juick/api/Users.java | 14 +++++--------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java index c7123d0a..631ae978 100644 --- a/src/main/java/com/juick/api/PM.java +++ b/src/main/java/com/juick/api/PM.java @@ -87,8 +87,8 @@ public class PM { Main.replyJSON(request, response, messageSerializer.serialize(jmsg).toString()); - String jid = UserQueries.getJIDbyUID(sql, uid); - if (jid != null) { + List jids = UserQueries.getJIDsbyUID(sql, uid); + for (String jid: jids) { Message mm = new Message(); mm.to = new JID(jid); mm.type = Message.Type.chat; diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java index 57f8c4b9..e85c517a 100644 --- a/src/main/java/com/juick/api/Users.java +++ b/src/main/java/com/juick/api/Users.java @@ -1,5 +1,6 @@ package com.juick.api; +import com.juick.User; import com.juick.json.UserSerializer; import com.juick.server.UserQueries; import org.springframework.jdbc.core.JdbcTemplate; @@ -115,15 +116,10 @@ public class Users { } if (uid > 0) { - List uids = UserQueries.getUserReaders(sql, uid); - if (uids.size() > 0) { - List users = UserQueries.getUsersByID(sql, uids); - if (users.size() > 0) { - String json = userSerializer.serializeList(users); - Main.replyJSON(request, response, json); - return; - } - } + List users = UserQueries.getUserReaders(sql, uid); + String json = userSerializer.serializeList(users); + Main.replyJSON(request, response, json); + return; } response.sendError(404); } -- cgit v1.2.3 From 462013333ed9ab6244e8b46106e3cb566efdd0e0 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 27 Jun 2016 16:39:15 +0300 Subject: embedded mariadb for tests --- build.gradle | 4 +- src/main/resources/schema.sql | 838 ++++++++++++++++++++++++++++ src/test/java/com/juick/tests/ApiTests.java | 72 +-- 3 files changed, 850 insertions(+), 64 deletions(-) create mode 100644 src/main/resources/schema.sql diff --git a/build.gradle b/build.gradle index 0d69481d..9ab3bce3 100644 --- a/build.gradle +++ b/build.gradle @@ -22,6 +22,7 @@ apply plugin: 'com.github.tkruse.groovysh' repositories { mavenCentral() + jcenter() } def core = project(':deps:com.juick') @@ -56,8 +57,9 @@ dependencies { compile 'com.github.pengrad:java-telegram-bot-api:2.1.1' compile 'com.neovisionaries:nv-websocket-client:1.27' runtime 'mysql:mysql-connector-java:5.1.39' + testCompile 'ch.vorburger.mariaDB4j:mariaDB4j:2.1.3' + testCompile 'org.slf4j:slf4j-jdk14:1.7.13' testCompile 'junit:junit:4.12' - testRuntime 'com.h2database:h2:1.4.190' } compileJava.options.encoding = 'UTF-8' gretty { diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql new file mode 100644 index 00000000..cdc97b86 --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,838 @@ +-- MySQL dump 10.13 Distrib 5.5.44, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: juick +-- ------------------------------------------------------ +-- Server version 5.5.44-0+deb8u1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +use juick; +-- +-- Table structure for table `ads_messages` +-- + +DROP TABLE IF EXISTS `ads_messages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ads_messages` ( + `message_id` int(10) unsigned NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ads_messages_log` +-- + +DROP TABLE IF EXISTS `ads_messages_log`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ads_messages_log` ( + `user_id` int(10) unsigned NOT NULL, + `message_id` int(10) unsigned NOT NULL, + `ts` int(10) unsigned NOT NULL DEFAULT '0' +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `android` +-- + +DROP TABLE IF EXISTS `android`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `android` ( + `user_id` int(10) unsigned NOT NULL, + `regid` char(255) NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `regid` (`regid`), + KEY `user_id` (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `auth` +-- + +DROP TABLE IF EXISTS `auth`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `auth` ( + `user_id` int(10) unsigned NOT NULL, + `protocol` enum('xmpp','email','sms') NOT NULL, + `account` char(64) NOT NULL, + `authcode` char(8) NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bl_tags` +-- + +DROP TABLE IF EXISTS `bl_tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `bl_tags` ( + `user_id` int(10) unsigned NOT NULL, + `tag_id` int(10) unsigned NOT NULL, + KEY `tag_id` (`tag_id`), + KEY `user_id` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bl_users` +-- + +DROP TABLE IF EXISTS `bl_users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `bl_users` ( + `user_id` int(10) unsigned NOT NULL, + `bl_user_id` int(10) unsigned NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`user_id`,`bl_user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `captcha` +-- + +DROP TABLE IF EXISTS `captcha`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `captcha` ( + `jid` char(64) NOT NULL, + `hash` char(16) NOT NULL, + `confirmed` tinyint(4) NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `captchaimg` +-- + +DROP TABLE IF EXISTS `captchaimg`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `captchaimg` ( + `id` char(16) NOT NULL, + `txt` char(6) NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `ip` char(16) NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `emails` +-- + +DROP TABLE IF EXISTS `emails`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `emails` ( + `user_id` int(10) unsigned NOT NULL, + `email` char(64) NOT NULL, + `subscr_hour` tinyint(4) DEFAULT NULL, + KEY `email` (`email`) USING HASH +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `facebook` +-- + +DROP TABLE IF EXISTS `facebook`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `facebook` ( + `user_id` int(10) unsigned DEFAULT NULL, + `fb_id` bigint(20) unsigned NOT NULL, + `loginhash` char(36) DEFAULT NULL, + `access_token` char(255) DEFAULT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `fb_name` char(64) NOT NULL, + `fb_link` char(64) NOT NULL, + `crosspost` tinyint(1) unsigned NOT NULL DEFAULT '1', + KEY `user_id` (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `favorites` +-- + +DROP TABLE IF EXISTS `favorites`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `favorites` ( + `user_id` int(10) unsigned NOT NULL, + `message_id` int(10) unsigned NOT NULL, + `ts` datetime NOT NULL, + UNIQUE KEY `user_id_2` (`user_id`,`message_id`), + KEY `user_id` (`user_id`), + KEY `message_id` (`message_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `friends_facebook` +-- + +DROP TABLE IF EXISTS `friends_facebook`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `friends_facebook` ( + `user_id` int(10) unsigned NOT NULL, + `friend_id` bigint(20) unsigned NOT NULL, + UNIQUE KEY `user_id` (`user_id`,`friend_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ios` +-- + +DROP TABLE IF EXISTS `ios`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ios` ( + `user_id` int(10) unsigned NOT NULL, + `token` char(64) COLLATE utf8mb4_unicode_ci NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `token` (`token`), + KEY `user_id` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `jids` +-- + +DROP TABLE IF EXISTS `jids`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `jids` ( + `user_id` int(10) unsigned DEFAULT NULL, + `jid` char(64) NOT NULL, + `active` tinyint(1) NOT NULL DEFAULT '1', + `loginhash` char(36) DEFAULT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `jid` (`jid`), + KEY `user_id` (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `logins` +-- + +DROP TABLE IF EXISTS `logins`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `logins` ( + `user_id` int(10) unsigned NOT NULL, + `hash` char(16) NOT NULL, + UNIQUE KEY `user_id` (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mail` +-- + +DROP TABLE IF EXISTS `mail`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `mail` ( + `user_id` int(10) unsigned NOT NULL, + `hash` char(16) NOT NULL, + PRIMARY KEY (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `meon` +-- + +DROP TABLE IF EXISTS `meon`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `meon` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `user_id` int(10) unsigned NOT NULL, + `link` char(255) NOT NULL, + `name` char(32) NOT NULL, + `ico` smallint(5) unsigned DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=MyISAM AUTO_INCREMENT=10850 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `messages` +-- + +DROP TABLE IF EXISTS `messages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `messages` ( + `message_id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `user_id` int(10) unsigned NOT NULL, + `lang` enum('en','ru','fr','fa','__') NOT NULL DEFAULT '__', + `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', + `readonly` tinyint(1) NOT NULL DEFAULT '0', + `attach` enum('jpg','mp4','png') DEFAULT NULL, + `place_id` int(10) unsigned DEFAULT NULL, + `lat` decimal(10,7) DEFAULT NULL, + `lon` decimal(10,7) DEFAULT NULL, + `popular` tinyint(4) NOT NULL DEFAULT '0', + `hidden` tinyint(3) unsigned NOT NULL DEFAULT '0', + `likes` smallint(6) NOT NULL DEFAULT '0', + PRIMARY KEY (`message_id`), + KEY `user_id` (`user_id`), + KEY `ts` (`ts`), + KEY `attach` (`attach`), + KEY `place_id` (`place_id`), + KEY `popular` (`popular`), + KEY `hidden` (`hidden`) +) ENGINE=InnoDB AUTO_INCREMENT=2814769 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `messages_access` +-- + +DROP TABLE IF EXISTS `messages_access`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `messages_access` ( + `message_id` int(10) unsigned NOT NULL, + `user_id` int(10) unsigned NOT NULL, + KEY `message_id` (`message_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `messages_tags` +-- + +DROP TABLE IF EXISTS `messages_tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `messages_tags` ( + `message_id` int(10) unsigned NOT NULL, + `tag_id` int(10) unsigned NOT NULL, + UNIQUE KEY `message_id_2` (`message_id`,`tag_id`), + KEY `message_id` (`message_id`), + KEY `tag_id` (`tag_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `messages_txt` +-- + +DROP TABLE IF EXISTS `messages_txt`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `messages_txt` ( + `message_id` int(10) unsigned NOT NULL, + `tags` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `repliesby` varchar(96) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `txt` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL, + PRIMARY KEY (`message_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `messages_votes` +-- + +DROP TABLE IF EXISTS `messages_votes`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `messages_votes` ( + `message_id` int(10) unsigned NOT NULL, + `user_id` int(10) unsigned NOT NULL, + `vote` tinyint(4) NOT NULL DEFAULT '1', + UNIQUE KEY `message_id` (`message_id`,`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `places` +-- + +DROP TABLE IF EXISTS `places`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `places` ( + `place_id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `lat` decimal(10,7) NOT NULL, + `lon` decimal(10,7) NOT NULL, + `name` char(64) NOT NULL, + `descr` char(255) DEFAULT NULL, + `url` char(128) DEFAULT NULL, + `user_id` int(10) unsigned NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`place_id`) +) ENGINE=MyISAM AUTO_INCREMENT=2697 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `places_tags` +-- + +DROP TABLE IF EXISTS `places_tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `places_tags` ( + `place_id` int(10) unsigned NOT NULL, + `tag_id` int(10) unsigned NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `pm` +-- + +DROP TABLE IF EXISTS `pm`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `pm` ( + `user_id` int(10) unsigned NOT NULL, + `user_id_to` int(10) unsigned NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `txt` text NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `pm_inroster` +-- + +DROP TABLE IF EXISTS `pm_inroster`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `pm_inroster` ( + `user_id` int(10) unsigned NOT NULL, + `jid` char(64) NOT NULL, + UNIQUE KEY `user_id_2` (`user_id`,`jid`), + KEY `user_id` (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `pm_streams` +-- + +DROP TABLE IF EXISTS `pm_streams`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `pm_streams` ( + `user_id` int(10) unsigned NOT NULL, + `user_id_to` int(10) unsigned NOT NULL, + `lastmessage` datetime NOT NULL, + `lastview` datetime DEFAULT NULL, + `unread` smallint(5) unsigned NOT NULL DEFAULT '0', + UNIQUE KEY `user_id` (`user_id`,`user_id_to`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `presence` +-- + +DROP TABLE IF EXISTS `presence`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `presence` ( + `user_id` int(10) unsigned NOT NULL, + `jid` char(64) DEFAULT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY `jid` (`jid`) +) ENGINE=MEMORY DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `reader_links` +-- + +DROP TABLE IF EXISTS `reader_links`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `reader_links` ( + `link_id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `rss_id` int(10) unsigned NOT NULL, + `url` char(255) NOT NULL, + `title` char(255) NOT NULL, + `ts` datetime NOT NULL, + PRIMARY KEY (`link_id`) +) ENGINE=MyISAM AUTO_INCREMENT=29932 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `reader_rss` +-- + +DROP TABLE IF EXISTS `reader_rss`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `reader_rss` ( + `rss_id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `url` char(255) NOT NULL, + `lastcheck` datetime NOT NULL, + PRIMARY KEY (`rss_id`) +) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `replies` +-- + +DROP TABLE IF EXISTS `replies`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +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` enum('jpg','mp4','png') COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `txt` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL, + KEY `message_id` (`message_id`), + KEY `user_id` (`user_id`), + KEY `ts` (`ts`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sphinx` +-- + +DROP TABLE IF EXISTS `sphinx`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sphinx` ( + `counter_id` tinyint(3) unsigned NOT NULL, + `max_id` int(10) unsigned NOT NULL, + PRIMARY KEY (`counter_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `subscr_messages` +-- + +DROP TABLE IF EXISTS `subscr_messages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `subscr_messages` ( + `message_id` int(10) unsigned NOT NULL, + `suser_id` int(10) unsigned NOT NULL, + UNIQUE KEY `message_id` (`message_id`,`suser_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `subscr_tags` +-- + +DROP TABLE IF EXISTS `subscr_tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `subscr_tags` ( + `tag_id` int(10) unsigned NOT NULL, + `suser_id` int(10) unsigned NOT NULL, + `jid` char(64) NOT NULL, + `active` bit(1) NOT NULL DEFAULT b'1', + UNIQUE KEY `tag_id` (`tag_id`,`suser_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `subscr_users` +-- + +DROP TABLE IF EXISTS `subscr_users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `subscr_users` ( + `user_id` int(10) unsigned NOT NULL, + `suser_id` int(10) unsigned NOT NULL, + `jid` char(64) DEFAULT NULL, + `active` bit(1) NOT NULL DEFAULT b'1', + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `user_id` (`user_id`,`suser_id`), + KEY `suser_id` (`suser_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tags` +-- + +DROP TABLE IF EXISTS `tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +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', + `noindex` 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', + PRIMARY KEY (`tag_id`), + KEY `synonym_id` (`synonym_id`) +) ENGINE=MyISAM AUTO_INCREMENT=115285 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tags_ignore` +-- + +DROP TABLE IF EXISTS `tags_ignore`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `tags_ignore` ( + `tag_id` int(10) unsigned NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tags_synonyms` +-- + +DROP TABLE IF EXISTS `tags_synonyms`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `tags_synonyms` ( + `name` char(64) NOT NULL, + `changeto` char(64) NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `top_ignore_messages` +-- + +DROP TABLE IF EXISTS `top_ignore_messages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `top_ignore_messages` ( + `message_id` int(10) unsigned NOT NULL +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `top_ignore_tags` +-- + +DROP TABLE IF EXISTS `top_ignore_tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `top_ignore_tags` ( + `tag_id` int(10) unsigned NOT NULL, + PRIMARY KEY (`tag_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `top_ignore_users` +-- + +DROP TABLE IF EXISTS `top_ignore_users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `top_ignore_users` ( + `user_id` int(10) unsigned NOT NULL, + PRIMARY KEY (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `twitter` +-- + +DROP TABLE IF EXISTS `twitter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `twitter` ( + `user_id` int(10) unsigned NOT NULL, + `access_token` char(64) NOT NULL, + `access_token_secret` char(64) NOT NULL, + `uname` char(64) NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `crosspost` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `useroptions` +-- + +DROP TABLE IF EXISTS `useroptions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +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', + `off_ts` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `xmppxhtml` tinyint(1) NOT NULL DEFAULT '0', + `subscr_notify` tinyint(1) NOT NULL DEFAULT '1', + `recommendations` tinyint(1) NOT NULL DEFAULT '1', + `privacy_view` tinyint(1) NOT NULL DEFAULT '1', + `privacy_reply` tinyint(1) NOT NULL DEFAULT '1', + `privacy_pm` tinyint(1) NOT NULL DEFAULT '1', + `repliesview` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`user_id`), + KEY `recommendations` (`recommendations`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `users` +-- + +DROP TABLE IF EXISTS `users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `users` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `nick` char(64) NOT NULL, + `passw` char(32) NOT NULL, + `lang` enum('en','ru','fr','fa','__') NOT NULL DEFAULT '__', + `banned` tinyint(3) unsigned NOT NULL DEFAULT '0', + `lastmessage` int(11) NOT NULL DEFAULT '0', + `lastpm` int(11) NOT NULL DEFAULT '0', + `lastphoto` int(11) NOT NULL DEFAULT '0', + `karma` smallint(6) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `nick` (`nick`) +) ENGINE=InnoDB AUTO_INCREMENT=29642 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `users_refs` +-- + +DROP TABLE IF EXISTS `users_refs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `users_refs` ( + `user_id` int(10) unsigned NOT NULL, + `ref` int(10) unsigned NOT NULL, + KEY `ref` (`ref`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `users_subscr` +-- + +DROP TABLE IF EXISTS `users_subscr`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `users_subscr` ( + `user_id` int(10) unsigned NOT NULL, + `cnt` smallint(5) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `usersinfo` +-- + +DROP TABLE IF EXISTS `usersinfo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `usersinfo` ( + `user_id` int(10) unsigned NOT NULL, + `jid` char(32) DEFAULT NULL, + `fullname` char(32) DEFAULT NULL, + `country` char(32) DEFAULT NULL, + `url` char(64) DEFAULT NULL, + `gender` char(32) DEFAULT NULL, + `bday` char(10) DEFAULT NULL, + `descr` varchar(255) DEFAULT NULL, + PRIMARY KEY (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vk` +-- + +DROP TABLE IF EXISTS `vk`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vk` ( + `user_id` int(10) unsigned DEFAULT NULL, + `vk_id` bigint(20) NOT NULL, + `loginhash` char(36) DEFAULT NULL, + `access_token` char(128) NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `vk_name` char(64) NOT NULL, + `vk_link` char(64) NOT NULL, + `crosspost` tinyint(3) unsigned NOT NULL DEFAULT '1', + KEY `user_id` (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `winphone` +-- + +DROP TABLE IF EXISTS `winphone`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `winphone` ( + `user_id` int(10) unsigned NOT NULL, + `url` char(255) NOT NULL, + `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `url` (`url`), + KEY `user_id` (`user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `wl_users` +-- + +DROP TABLE IF EXISTS `wl_users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `wl_users` ( + `user_id` int(10) unsigned NOT NULL, + `wl_user_id` int(10) unsigned NOT NULL, + PRIMARY KEY (`user_id`,`wl_user_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2015-12-17 10:49:43 diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 2bae183d..7ab04708 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -1,5 +1,7 @@ package com.juick.tests; +import ch.vorburger.exec.ManagedProcessException; +import ch.vorburger.mariadb4j.DB; import com.juick.Message; import com.juick.Tag; import com.juick.User; @@ -23,71 +25,15 @@ import java.util.List; public class ApiTests { JdbcTemplate jdbc; @Before - public void setupConnection() { + public void setupConnection() throws ManagedProcessException { + DB db = DB.newEmbeddedDB(3306); + db.start(); + db.createDB("juick"); + db.source("schema.sql"); DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.h2.Driver"); - dataSource.setUrl("jdbc:h2:~/test"); + dataSource.setDriverClassName("com.mysql.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=root"); 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 (" + - "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 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)," + - "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)"); } -- cgit v1.2.3 From 5fc121e7dc0c5c61dda58f4e4a73d7e43848e1e4 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 27 Jun 2016 16:56:13 +0300 Subject: telegram: reconnect websockets --- src/main/java/com/juick/api/TelegramBotHook.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 429b55f3..e1094ff6 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -52,6 +52,7 @@ public class TelegramBotHook { @Override public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception { logger.info("ws disconnected"); + ws.connect(); } @Override @@ -89,6 +90,7 @@ public class TelegramBotHook { @Override public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception { logger.info("ws replies disconnected"); + ws.connect(); } @Override -- cgit v1.2.3 From 7babecb107b183713a5fde33cae95e6bec726142 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 30 Jun 2016 15:24:49 +0300 Subject: exclude mysql-connector from war --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 0d69481d..171cb3db 100644 --- a/build.gradle +++ b/build.gradle @@ -55,7 +55,7 @@ dependencies { compile 'javax.inject:javax.inject:1' compile 'com.github.pengrad:java-telegram-bot-api:2.1.1' compile 'com.neovisionaries:nv-websocket-client:1.27' - runtime 'mysql:mysql-connector-java:5.1.39' + providedRuntime 'mysql:mysql-connector-java:5.1.39' testCompile 'junit:junit:4.12' testRuntime 'com.h2database:h2:1.4.190' } -- 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(-) 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(-) 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