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 --- src/test/java/com/juick/tests/JsonTests.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/test/java/com/juick/tests/JsonTests.java (limited to 'src/test') 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 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(-) (limited to 'src/test') 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 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 (limited to 'src/test') 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 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(-) (limited to 'src/test') 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 (limited to 'src/test') 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(-) (limited to 'src/test') 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(-) (limited to 'src/test') 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 f9d5099bf4be816aa267e02b5713a672fd4da562 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 14:49:51 +0300 Subject: spring-jdbc WIP --- deps/com.juick.server | 2 +- src/main/java/com/juick/api/Messages.java | 12 ++++++------ src/test/java/com/juick/tests/ApiTests.java | 9 +++++++++ 3 files changed, 16 insertions(+), 7 deletions(-) (limited to 'src/test') 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 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(-) (limited to 'src/test') 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 30068e18a3d8ae37b509f5cd766515735a818692 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 15:54:04 +0300 Subject: update core --- deps/com.juick | 2 +- deps/com.juick.server | 2 +- src/main/java/com/juick/api/Messages.java | 23 ++++++++++++++++------- src/main/java/com/juick/api/Others.java | 4 +++- src/main/java/com/juick/api/PM.java | 16 ++++++++++------ src/main/java/com/juick/api/Users.java | 20 +++++++++++++------- src/test/java/com/juick/tests/ApiTests.java | 6 +++--- 7 files changed, 47 insertions(+), 26 deletions(-) (limited to 'src/test') 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 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(-) (limited to 'src/test') 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(-) (limited to 'src/test') 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(+) (limited to 'src/test') 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(-) (limited to 'src/test') 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(-) (limited to 'src/test') 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 (limited to 'src/test') 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 d8f9f16d16f4e2f7133de464ba8d3f6cc704bd00 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 17 Jan 2016 00:18:33 +0300 Subject: almost working messages api --- .gitignore | 26 ++++---- build.gradle | 1 + deps/com.juick.server | 2 +- src/main/java/com/juick/api/Main.java | 31 +++++---- src/main/java/com/juick/api/Messages.java | 97 +++++++++++++++++++---------- src/main/java/com/juick/api/Utils.java | 5 ++ src/main/webapp/WEB-INF/juick.conf.example | 6 ++ src/test/java/com/juick/tests/ApiTests.java | 11 ++-- 8 files changed, 118 insertions(+), 61 deletions(-) create mode 100644 src/main/webapp/WEB-INF/juick.conf.example (limited to 'src/test') 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 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(-) (limited to 'src/test') 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 7fb8cdfb02c24c265a081499c858f3aca1efbb2b Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 23:24:22 +0300 Subject: update server api and try to fix anonymous chats --- deps/com.juick.server | 2 +- src/main/java/com/juick/api/Messages.java | 2 +- src/main/java/com/juick/api/PM.java | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 12 ++++++------ src/test/java/com/juick/tests/ApiTests.java | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) (limited to 'src/test') 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 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 (limited to 'src/test') 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