aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2016-12-19 13:41:23 +0300
committerGravatar Vitaly Takmazov2016-12-19 13:41:23 +0300
commit274de5ede59ed4023826a9db09ec60788bc950e1 (patch)
tree107dbca37f559666eb065989aa92fd81e79fef24
parentacddd380e1868e28491eaf85f05e87d7a47a123f (diff)
all projects except juick-www are spring-managed now
-rw-r--r--build.gradle1
-rw-r--r--juick-demo/src/main/java/com/juick/demo/Demo.java79
-rw-r--r--juick-demo/src/main/java/com/juick/demo/DemoApp.java82
-rw-r--r--juick-demo/src/main/java/com/juick/demo/configuration/DemoAppConfiguration.java90
-rw-r--r--juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java136
-rw-r--r--juick-xmpp-bot/src/main/java/com/juick/components/XMPPBot.java11
-rw-r--r--src/test/java/com/juick/tests/ApiTests.java257
7 files changed, 432 insertions, 224 deletions
diff --git a/build.gradle b/build.gradle
index 226b0b72..02b010ad 100644
--- a/build.gradle
+++ b/build.gradle
@@ -39,6 +39,7 @@ dependencies {
testCompile "com.fasterxml.jackson.core:jackson-core:${jacksonVersion}"
testCompile "com.fasterxml.jackson.core:jackson-databind:${jacksonVersion}"
testCompile "org.springframework:spring-jdbc:${springFrameworkVersion}"
+ testCompile "org.springframework:spring-test:${springFrameworkVersion}"
testCompile "ch.vorburger.mariaDB4j:mariaDB4j:2.2.2"
testCompile "org.slf4j:slf4j-api:${slf4jVersion}"
testCompile "junit:junit:${junitVersion}"
diff --git a/juick-demo/src/main/java/com/juick/demo/Demo.java b/juick-demo/src/main/java/com/juick/demo/Demo.java
index b94c9830..db03e2e5 100644
--- a/juick-demo/src/main/java/com/juick/demo/Demo.java
+++ b/juick-demo/src/main/java/com/juick/demo/Demo.java
@@ -1,77 +1,28 @@
package com.juick.demo;
import ch.vorburger.exec.ManagedProcessException;
-import ch.vorburger.mariadb4j.DB;
-import com.juick.Tag;
-import com.juick.User;
-import com.juick.server.MessagesQueries;
-import com.juick.server.PMQueries;
-import com.juick.server.TagQueries;
-import com.juick.server.UserQueries;
-import com.juick.server.protocol.JuickProtocol;
-import com.juick.server.protocol.ProtocolReply;
-import jline.UnsupportedTerminal;
-import jline.console.ConsoleReader;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.jdbc.datasource.DriverManagerDataSource;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
+import com.juick.demo.configuration.DemoAppConfiguration;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.core.env.SimpleCommandLinePropertySource;
/**
* Created by vitalyster on 30.08.2016.
*/
public class Demo {
- private static final Logger logger = LoggerFactory.getLogger(Demo.class);
+
public static void main(String ...args) throws ManagedProcessException {
- DB db = DB.newEmbeddedDB(33306);
- db.start();
- db.createDB("juick");
- db.source("schema.sql");
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
- dataSource.setUrl("jdbc:mysql://localhost:33306/juick?autoReconnect=true&user=root");
- JdbcTemplate jdbc = new JdbcTemplate(dataSource);
- logger.info("initializing demo database");
+ final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
- Integer ugnich_id = UserQueries.createUser(jdbc, "ugnich", "secret");
- Integer ugn_mid = MessagesQueries.createMessage(jdbc, ugnich_id, "Hi, I am ugnich", null,
- new ArrayList<Tag>() {{add(TagQueries.getTag(jdbc, "yo", true)); add(TagQueries.getTag(jdbc, "people", true));}});
+ // setup configuration
+ applicationContext.register(DemoAppConfiguration.class);
+ // add CLI property source
+ applicationContext.getEnvironment().getPropertySources()
+ .addLast(new SimpleCommandLinePropertySource(args));
- Integer juick_id = UserQueries.createUser(jdbc, "juick", "secret");
- MessagesQueries.createMessage(jdbc, juick_id, "New demo juick was created", null,
- new ArrayList<Tag>() {{add(TagQueries.getTag(jdbc, "yo", true)); add(TagQueries.getTag(jdbc, "readonly", true));}});
- Integer freefd_id = UserQueries.createUser(jdbc, "freefd", "secret");
- MessagesQueries.createReply(jdbc, ugn_mid, 0, freefd_id, "I am freefd and this is my reply", null);
- MessagesQueries.recommendMessage(jdbc, ugn_mid, freefd_id);
- MessagesQueries.recommendMessage(jdbc, ugn_mid, juick_id);
- MessagesQueries.setMessagePopular(jdbc, ugn_mid, 1);
- PMQueries.createPM(jdbc, freefd_id, ugnich_id, "Hi ugnich!");
- jdbc.execute("UPDATE tags SET top=1");
- jline.TerminalFactory.registerFlavor(jline.TerminalFactory.Flavor.WINDOWS, UnsupportedTerminal.class);
- try (ConsoleReader reader = new ConsoleReader()) {
- reader.setPrompt("ugnich>");
- PrintWriter out = new PrintWriter(reader.getOutput());
- User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id).get();
- out.println(String.format("logged in as @%s", ugnich.getName()));
- out.flush();
- String input;
- JuickProtocol protocol = new JuickProtocol(jdbc, "http://localhost/");
- while ((input = reader.readLine()) != null) {
- ProtocolReply reply = protocol.getReply(ugnich, input);
- out.println(reply.getDescription());
- out.flush();
- }
- } catch (IOException | NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
+ // setup all the dependencies (refresh) and make them run (start)
+ applicationContext.refresh();
+ applicationContext.start();
+ DemoApp demoApp = new DemoApp(applicationContext);
+ demoApp.start();
}
}
diff --git a/juick-demo/src/main/java/com/juick/demo/DemoApp.java b/juick-demo/src/main/java/com/juick/demo/DemoApp.java
new file mode 100644
index 00000000..9d1d7926
--- /dev/null
+++ b/juick-demo/src/main/java/com/juick/demo/DemoApp.java
@@ -0,0 +1,82 @@
+package com.juick.demo;
+
+import com.juick.Tag;
+import com.juick.User;
+import com.juick.server.MessagesQueries;
+import com.juick.server.PMQueries;
+import com.juick.server.TagQueries;
+import com.juick.server.UserQueries;
+import com.juick.server.protocol.JuickProtocol;
+import com.juick.server.protocol.ProtocolReply;
+import com.juick.service.MessagesService;
+import com.juick.service.PMQueriesService;
+import com.juick.service.TagService;
+import com.juick.service.UserService;
+import jline.UnsupportedTerminal;
+import jline.console.ConsoleReader;
+import org.springframework.context.ApplicationContext;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Component;
+
+import javax.inject.Inject;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+
+/**
+ * Created by vitalyster on 19.12.2016.
+ */
+public class DemoApp {
+ UserService userService;
+ MessagesService messagesService;
+ PMQueriesService pmQueriesService;
+ TagService tagService;
+ JdbcTemplate jdbcTemplate;
+ JuickProtocol juickProtocol;
+
+ public DemoApp(ApplicationContext context) {
+ userService = context.getBean(UserService.class);
+ messagesService = context.getBean(MessagesService.class);
+ pmQueriesService = context.getBean(PMQueriesService.class);
+ tagService = context.getBean(TagService.class);
+ jdbcTemplate = context.getBean(JdbcTemplate.class);
+ juickProtocol = context.getBean(JuickProtocol.class);
+ }
+ public void start() {
+ Integer ugnich_id = userService.createUser("ugnich", "secret");
+ Integer ugn_mid = messagesService.createMessage(ugnich_id, "Hi, I am ugnich", null,
+ new ArrayList<Tag>() {{add(tagService.getTag("yo", true)); add(tagService.getTag("people", true));}});
+
+ Integer juick_id = userService.createUser("juick", "secret");
+ messagesService.createMessage(juick_id, "New demo juick was created", null,
+ new ArrayList<Tag>() {{add(tagService.getTag("yo", true)); add(tagService.getTag("readonly", true));}});
+ Integer freefd_id = userService.createUser("freefd", "secret");
+ messagesService.createReply(ugn_mid, 0, freefd_id, "I am freefd and this is my reply", null);
+ messagesService.recommendMessage(ugn_mid, freefd_id);
+ messagesService.recommendMessage(ugn_mid, juick_id);
+ messagesService.setMessagePopular(ugn_mid, 1);
+ pmQueriesService.createPM(freefd_id, ugnich_id, "Hi ugnich!");
+ jdbcTemplate.execute("UPDATE tags SET top=1");
+ jline.TerminalFactory.registerFlavor(jline.TerminalFactory.Flavor.WINDOWS, UnsupportedTerminal.class);
+ try (ConsoleReader reader = new ConsoleReader()) {
+ reader.setPrompt("ugnich>");
+ PrintWriter out = new PrintWriter(reader.getOutput());
+ User ugnich = userService.getUserByUID(ugnich_id).get();
+ out.println(String.format("logged in as @%s", ugnich.getName()));
+ out.flush();
+ String input;
+ while ((input = reader.readLine()) != null) {
+ ProtocolReply reply = juickProtocol.getReply(ugnich, input);
+ out.println(reply.getDescription());
+ out.flush();
+ }
+ } catch (IOException | NoSuchMethodException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/juick-demo/src/main/java/com/juick/demo/configuration/DemoAppConfiguration.java b/juick-demo/src/main/java/com/juick/demo/configuration/DemoAppConfiguration.java
new file mode 100644
index 00000000..6a7f697a
--- /dev/null
+++ b/juick-demo/src/main/java/com/juick/demo/configuration/DemoAppConfiguration.java
@@ -0,0 +1,90 @@
+package com.juick.demo.configuration;
+
+import ch.vorburger.exec.ManagedProcessException;
+import ch.vorburger.mariadb4j.DB;
+import com.juick.server.protocol.JuickProtocol;
+import com.juick.service.search.SearchService;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.TransactionManagementConfigurer;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Created by vitalyster on 19.12.2016.
+ */
+@Configuration
+@ComponentScan(basePackages = {"com.juick.demo", "com.juick.service", "com.juick.server.protocol"})
+public class DemoAppConfiguration implements ApplicationContextAware, TransactionManagementConfigurer {
+ private ApplicationContext applicationContext;
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+ this.applicationContext = applicationContext;
+ }
+ @Bean
+ public BasicDataSource dataSource() {
+ try {
+ DB db = DB.newEmbeddedDB(33306);
+ db.start();
+ db.createDB("juick");
+ db.source("schema.sql");
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName("com.mysql.jdbc.Driver");
+ dataSource.setUrl("jdbc:mysql://localhost:33306/juick?autoReconnect=true&user=root");
+
+ dataSource.setValidationQuery("select 1");
+
+ return dataSource;
+ } catch (ManagedProcessException e) {
+ return null;
+ }
+ }
+
+ @Bean
+ public PlatformTransactionManager transactionManager() {
+ return new DataSourceTransactionManager(dataSource());
+ }
+
+ @Override
+ public PlatformTransactionManager annotationDrivenTransactionManager() {
+ return transactionManager();
+ }
+
+ @Bean
+ @DependsOn("dataSource")
+ public JdbcTemplate jdbcTemplate() {
+ return new JdbcTemplate(dataSource());
+ }
+ @Bean
+ public SearchService emptySearchService() {
+ return new SearchService() {
+ @Override
+ public void setMaxResult(int maxResult) {
+ }
+
+ @Override
+ public List<Integer> searchInAllMessages(String searchString, int messageIdBefore) {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List<Integer> searchByStringAndUser(String searchString, int userId, int messageIdBefore) {
+ return Collections.emptyList();
+ }
+ };
+ }
+ @Bean
+ public JuickProtocol juickProtocol() {
+ return new JuickProtocol("http://localhost:8080/");
+ }
+}
diff --git a/juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java b/juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java
index 68c7c37c..7b155747 100644
--- a/juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java
+++ b/juick-server/src/main/java/com/juick/server/protocol/JuickProtocol.java
@@ -7,12 +7,12 @@ import com.juick.Message;
import com.juick.Tag;
import com.juick.User;
import com.juick.formatters.PlainTextFormatter;
-import com.juick.server.*;
import com.juick.server.helpers.TagStats;
import com.juick.server.protocol.annotation.UserCommand;
+import com.juick.service.*;
import com.juick.util.TagUtils;
-import org.springframework.jdbc.core.JdbcTemplate;
+import javax.inject.Inject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
@@ -25,13 +25,26 @@ import java.util.stream.Collectors;
*/
public class JuickProtocol {
- ObjectMapper json = new ObjectMapper();
- JdbcTemplate sql;
- String baseUri;
-
- public JuickProtocol(JdbcTemplate sql, String baseUri) {
- this.sql = sql;
+ private final ObjectMapper json;
+ private String baseUri;
+ @Inject
+ UserService userService;
+ @Inject
+ TagService tagService;
+ @Inject
+ MessagesService messagesService;
+ @Inject
+ SubscriptionService subscriptionService;
+ @Inject
+ PMQueriesService pmQueriesService;
+ @Inject
+ PrivacyQueriesService privacyQueriesService;
+ @Inject
+ ShowQueriesService showQueriesService;
+
+ public JuickProtocol(String baseUri) {
this.baseUri = baseUri;
+ json = new ObjectMapper();
json.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
json.setSerializationInclusion(JsonInclude.Include.NON_NULL);
json.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
@@ -71,21 +84,20 @@ public class JuickProtocol {
}
public ProtocolReply postMessage(User user, String input) throws JsonProcessingException {
- List<Tag> tags = TagQueries.fromString(sql, input, false);
+ List<Tag> tags = tagService.fromString(input, false);
String body = input.substring(TagUtils.toString(tags).length());
- int mid = MessagesQueries.createMessage(sql, user.getUid(), body, null, tags);
- SubscriptionsQueries.subscribeMessage(sql, mid, user.getUid());
- //app.events().publishEvent(new JuickMessageEvent(app.messages().getMessage(mid)));
+ int mid = messagesService.createMessage(user.getUid(), body, null, tags);
+ subscriptionService.subscribeMessage(mid, user.getUid());
return new ProtocolReply("New message posted.\n#" + mid + " " + baseUri + mid,
- Optional.of(json.writeValueAsString(Collections.singletonList(MessagesQueries.getMessage(sql, mid)))));
+ Optional.of(json.writeValueAsString(Collections.singletonList(messagesService.getMessage(mid)))));
}
@UserCommand(pattern = "^#(\\++)$", help = "#+ - Show last Juick messages (#++ - second page, ...)")
public ProtocolReply commandLast(User user, String... arguments) throws JsonProcessingException {
// number of + is the page count
int page = arguments[0].length() - 1;
- List<Integer> mids = MessagesQueries.getAll(sql, user.getUid(), page);
- List<Message> messages = MessagesQueries.getMessages(sql, mids);
+ List<Integer> mids = messagesService.getAll(user.getUid(), page);
+ List<Message> messages = messagesService.getMessages(mids);
return new ProtocolReply("Last messages: \n" + String.join("\n", messages.stream().map(PlainTextFormatter::formatPost)
.collect(Collectors.toList())), Optional.of(json.writeValueAsString(messages)));
}
@@ -96,8 +108,8 @@ public class JuickProtocol {
List<User> blusers;
List<String> bltags;
- blusers = UserQueries.getUserBLUsers(sql, user_from.getUid());
- bltags = TagQueries.getUserBLTags(sql, user_from.getUid());
+ blusers = userService.getUserBLUsers(user_from.getUid());
+ bltags = tagService.getUserBLTags(user_from.getUid());
String txt = "";
@@ -124,10 +136,10 @@ public class JuickProtocol {
@UserCommand(pattern = "^bl\\s+@([^\\s\\n\\+]+)", patternFlags = Pattern.CASE_INSENSITIVE,
help = "BL @username - add @username to your blacklist")
public ProtocolReply blacklistUser(User from, String... arguments) {
- User blUser = UserQueries.getUserByName(sql, arguments[0]);
+ User blUser = userService.getUserByName(arguments[0]);
if (blUser != null) {
- PrivacyQueries.PrivacyResult result = PrivacyQueries.blacklistUser(sql, from, blUser);
- if (result == PrivacyQueries.PrivacyResult.Added) {
+ PrivacyQueriesService.PrivacyResult result = privacyQueriesService.blacklistUser(from, blUser);
+ if (result == PrivacyQueriesService.PrivacyResult.Added) {
return new ProtocolReply("User added to your blacklist", Optional.empty());
} else {
return new ProtocolReply("User removed from your blacklist", Optional.empty());
@@ -139,12 +151,12 @@ public class JuickProtocol {
@UserCommand(pattern = "^bl\\s\\*(\\S+)$", patternFlags = Pattern.CASE_INSENSITIVE,
help = "BL *tag - add *tag to your blacklist")
public ProtocolReply blacklistTag(User from, String... arguments) {
- User blUser = UserQueries.getUserByName(sql, arguments[0]);
+ User blUser = userService.getUserByName(arguments[0]);
if (blUser != null) {
- Tag tag = TagQueries.getTag(sql, arguments[0], false);
+ Tag tag = tagService.getTag(arguments[0], false);
if (tag != null) {
- PrivacyQueries.PrivacyResult result = PrivacyQueries.blacklistTag(sql, from, tag);
- if (result == PrivacyQueries.PrivacyResult.Added) {
+ PrivacyQueriesService.PrivacyResult result = privacyQueriesService.blacklistTag(from, tag);
+ if (result == PrivacyQueriesService.PrivacyResult.Added) {
return new ProtocolReply("Tag added to your blacklist", Optional.empty());
} else {
return new ProtocolReply("Tag removed from your blacklist", Optional.empty());
@@ -158,7 +170,7 @@ public class JuickProtocol {
public ProtocolReply commandUsers(User currentUser, String... args) {
StringBuilder msg = new StringBuilder();
msg.append("Recommended blogs");
- List<String> recommendedUsers = ShowQueries.getRecommendedUsers(sql, currentUser);
+ List<String> recommendedUsers = showQueriesService.getRecommendedUsers(currentUser);
if (recommendedUsers.size() > 0) {
for (String user : recommendedUsers) {
msg.append("\n@").append(user);
@@ -167,7 +179,7 @@ public class JuickProtocol {
msg.append("\nNo recommendations now. Subscribe to more blogs. ;)");
}
msg.append("\n\nTop 10 personal blogs:");
- List<String> topUsers = ShowQueries.getTopUsers(sql);
+ List<String> topUsers = showQueriesService.getTopUsers();
if (topUsers.size() > 0) {
for (String user : topUsers) {
msg.append("\n@").append(user);
@@ -180,7 +192,7 @@ public class JuickProtocol {
@UserCommand(pattern = "\\*", help = "* - Show your tags")
public ProtocolReply commandTags(User currentUser, String... args) {
- List<TagStats> tags = TagQueries.getTagsStats(sql, currentUser.getUid());
+ List<TagStats> tags = tagService.getUserTagStats(currentUser.getUid());
String msg = "Your tags: (tag - messages)\n" +
tags.stream()
.map(t -> String.format("\n*%s - %d", t.getTag().getName(), t.getUsageCount())).collect(Collectors.joining());
@@ -189,9 +201,9 @@ public class JuickProtocol {
@UserCommand(pattern = "!", help = "! - Show your favorite messages")
public ProtocolReply commandFavorites(User currentUser, String... args) throws JsonProcessingException {
- List<Integer> mids = MessagesQueries.getUserRecommendations(sql, currentUser.getUid(), 0);
+ List<Integer> mids = messagesService.getUserRecommendations(currentUser.getUid(), 0);
if (mids.size() > 0) {
- List<Message> messages = MessagesQueries.getMessages(sql, mids);
+ List<Message> messages = messagesService.getMessages(mids);
return new ProtocolReply("Favorite messages: \n" + String.join("\n", messages.stream().map(PlainTextFormatter::formatPost)
.collect(Collectors.toList())), Optional.of(json.writeValueAsString(messages)));
}
@@ -201,11 +213,11 @@ public class JuickProtocol {
@UserCommand(pattern = "^\\@([^\\s\\n\\+]+)(\\+?)$",
help = "@username+ - Show user's info and last 10 messages (@username++ - second page, ..)")
public ProtocolReply commandUser(User user, String... arguments) throws JsonProcessingException {
- User blogUser = UserQueries.getUserByName(sql, arguments[0]);
+ User blogUser = userService.getUserByName(arguments[0]);
int page = arguments[1].length();
if (blogUser != null) {
- List<Integer> mids = MessagesQueries.getUserBlog(sql, blogUser.getUid(), 0, page);
- List<Message> messages = MessagesQueries.getMessages(sql, mids);
+ List<Integer> mids = messagesService.getUserBlog(blogUser.getUid(), 0, page);
+ List<Message> messages = messagesService.getMessages(mids);
return new ProtocolReply(String.format("Last messages from @%s:\n%s", arguments[0],
String.join("\n", messages.stream()
.map(Object::toString).collect(Collectors.toList()))),
@@ -219,7 +231,7 @@ public class JuickProtocol {
public ProtocolReply commandDel(User user, String... args) {
try {
int mid = Integer.parseInt(args[0]);
- if (MessagesQueries.deleteMessage(sql, user.getUid(), mid)) {
+ if (messagesService.deleteMessage(user.getUid(), mid)) {
return new ProtocolReply(String.format("Message %s deleted", mid), Optional.empty());
}
} catch (NumberFormatException e) {
@@ -231,7 +243,7 @@ public class JuickProtocol {
@UserCommand(pattern = "^\\s*login\\s*$", patternFlags = Pattern.CASE_INSENSITIVE,
help = "LOGIN - log in to Juick website")
public ProtocolReply commandLogin(User user, String... arguments) {
- return new ProtocolReply(baseUri + "?" + UserQueries.getHashByUID(sql, user.getUid()),
+ return new ProtocolReply(baseUri + "?" + userService.getHashByUID(user.getUid()),
Optional.empty());
}
@@ -239,8 +251,8 @@ public class JuickProtocol {
public ProtocolReply commandMyFeed(User user, String... arguments) throws JsonProcessingException {
// number of # is the page count
int page = arguments[0].length() - 1;
- List<Integer> mids = MessagesQueries.getMyFeed(sql, user.getUid(), page);
- List<Message> messages = MessagesQueries.getMessages(sql, mids);
+ List<Integer> mids = messagesService.getMyFeed(user.getUid(), page);
+ List<Message> messages = messagesService.getMessages(mids);
// TODO: add instructions for empty feed
return new ProtocolReply("Your feed: \n" + String.join("\n",
messages.stream().map(PlainTextFormatter::formatPost).collect(Collectors.toList())),
@@ -250,17 +262,17 @@ public class JuickProtocol {
@UserCommand(pattern = "^\\s*(on|off)\\s*$", patternFlags = Pattern.CASE_INSENSITIVE,
help = "ON/OFF - Enable/disable subscriptions delivery")
public ProtocolReply commandOnOff(User user, String[] input) {
- UserQueries.ActiveStatus newStatus;
+ UserService.ActiveStatus newStatus;
String retValUpdated;
if (input[0].toLowerCase().equals("on")) {
- newStatus = UserQueries.ActiveStatus.Active;
+ newStatus = UserService.ActiveStatus.Active;
retValUpdated = "Notifications are activated for " + user.getJid();
} else {
- newStatus = UserQueries.ActiveStatus.Inactive;
+ newStatus = UserService.ActiveStatus.Inactive;
retValUpdated = "Notifications are disabled for " + user.getJid();
}
- if (UserQueries.setActiveStatusForJID(sql, user.getJid(), newStatus)) {
+ if (userService.setActiveStatusForJID(user.getJid(), newStatus)) {
return new ProtocolReply(retValUpdated, Optional.empty());
} else {
return new ProtocolReply(String.format("Subscriptions status for %s was not changed", user.getJid()),
@@ -285,17 +297,17 @@ public class JuickProtocol {
boolean haveInRoster = false;
if (user_to.indexOf('@') > 0) {
- uid_to = UserQueries.getUIDbyJID(sql, user_to);
+ uid_to = userService.getUIDbyJID(user_to);
} else {
- uid_to = UserQueries.getUIDbyName(sql, user_to);
+ uid_to = userService.getUIDbyName(user_to);
}
if (uid_to > 0) {
- if (!UserQueries.isInBLAny(sql, uid_to, user_from.getUid())) {
- if (PMQueries.createPM(sql, user_from.getUid(), uid_to, body)) {
+ if (!userService.isInBLAny(uid_to, user_from.getUid())) {
+ if (pmQueriesService.createPM(user_from.getUid(), uid_to, body)) {
//jid_to = UserQueries.getJIDsbyUID(sql, uid_to);
if (jid_to != null) {
- haveInRoster = PMQueries.havePMinRoster(sql, user_from.getUid(), jid_to);
+ haveInRoster = pmQueriesService.havePMinRoster(user_from.getUid(), jid_to);
}
ret = 200;
} else {
@@ -347,10 +359,10 @@ public class JuickProtocol {
} catch (NumberFormatException e) {
return new ProtocolReply("Error", Optional.empty());
}
- Message msg = MessagesQueries.getMessage(sql, mid);
+ Message msg = messagesService.getMessage(mid);
if (msg != null) {
if (showReplies) {
- List<Message> replies = MessagesQueries.getReplies(sql, mid);
+ List<Message> replies = messagesService.getReplies(mid);
replies.add(0, msg);
return new ProtocolReply(String.join("\n",
replies.stream().map(PlainTextFormatter::formatPost).collect(Collectors.toList())),
@@ -377,18 +389,18 @@ public class JuickProtocol {
rid = 0;
}
String txt = args[5];
- List<Tag> messageTags = TagQueries.fromString(sql, txt, true);
+ List<Tag> messageTags = tagService.fromString(txt, true);
if (messageTags.size() > 0) {
- if (user.getUid() != MessagesQueries.getMessageAuthor(sql, mid).getUid()) {
+ if (user.getUid() != messagesService.getMessageAuthor(mid).getUid()) {
return new ProtocolReply("It is not your message", Optional.empty());
}
- TagQueries.updateTags(sql, mid, messageTags);
+ tagService.updateTags(mid, messageTags);
return new ProtocolReply("Tags are updated", Optional.empty());
} else {
- int newrid = MessagesQueries.createReply(sql, mid, rid, user.getUid(), txt, null);
+ int newrid = messagesService.createReply(mid, rid, user.getUid(), txt, null);
return new ProtocolReply("Reply posted.\n#" + mid + "/" + newrid + " "
+ baseUri + mid + "/" + newrid,
- Optional.of(json.writeValueAsString(Collections.singletonList(MessagesQueries.getReply(sql, mid, newrid)))));
+ Optional.of(json.writeValueAsString(Collections.singletonList(messagesService.getReply(mid, newrid)))));
}
}
@@ -403,11 +415,11 @@ public class JuickProtocol {
return new ProtocolReply("Error", Optional.empty());
}
if (subscribe) {
- if (SubscriptionsQueries.subscribeMessage(sql, mid, user.getUid())) {
+ if (subscriptionService.subscribeMessage(mid, user.getUid())) {
return new ProtocolReply("Subscribed", Optional.empty());
}
} else {
- if (SubscriptionsQueries.unSubscribeMessage(sql, mid, user.getUid())) {
+ if (subscriptionService.unSubscribeMessage(mid, user.getUid())) {
return new ProtocolReply("Unsubscribed from #" + mid, Optional.empty());
}
return new ProtocolReply("You was not subscribed to #" + mid, Optional.empty());
@@ -418,16 +430,16 @@ public class JuickProtocol {
patternFlags = Pattern.CASE_INSENSITIVE)
public ProtocolReply commandSubscribeUser(User user, String... args) {
boolean subscribe = args[0].equalsIgnoreCase("s");
- User toUser = UserQueries.getUserByName(sql, args[1]);
+ User toUser = userService.getUserByName(args[1]);
if (toUser.getUid() > 0) {
if (subscribe) {
- if (SubscriptionsQueries.subscribeUser(sql, user, toUser)) {
+ if (subscriptionService.subscribeUser(user, toUser)) {
return new ProtocolReply("Subscribed", Optional.empty());
// TODO: notification
// TODO: already subscribed case
}
} else {
- if (SubscriptionsQueries.unSubscribeUser(sql, user, toUser)) {
+ if (subscriptionService.unSubscribeUser(user, toUser)) {
return new ProtocolReply("Unsubscribed from @" + toUser.getName(), Optional.empty());
}
return new ProtocolReply("You was not subscribed to @" + toUser.getName(), Optional.empty());
@@ -439,13 +451,13 @@ public class JuickProtocol {
"\nU *tag - unsubscribe from tag", patternFlags = Pattern.CASE_INSENSITIVE)
public ProtocolReply commandSubscribeTag(User user, String... args) {
boolean subscribe = args[0].equalsIgnoreCase("s");
- Tag tag = TagQueries.getTag(sql, args[1], true);
+ Tag tag = tagService.getTag(args[1], true);
if (subscribe) {
- if (SubscriptionsQueries.subscribeTag(sql, user, tag)) {
+ if (subscriptionService.subscribeTag(user, tag)) {
return new ProtocolReply("Subscribed", Optional.empty());
}
} else {
- if (SubscriptionsQueries.unSubscribeTag(sql, user, tag)) {
+ if (subscriptionService.unSubscribeTag(user, tag)) {
return new ProtocolReply("Unsubscribed from " + tag.getName(), Optional.empty());
}
return new ProtocolReply("You was not subscribed to " + tag.getName(), Optional.empty());
@@ -462,4 +474,8 @@ public class JuickProtocol {
.collect(Collectors.toList());
return new ProtocolReply(String.join("\n", commandsHelp), Optional.empty());
}
+
+ public String getBaseUri() {
+ return baseUri;
+ }
}
diff --git a/juick-xmpp-bot/src/main/java/com/juick/components/XMPPBot.java b/juick-xmpp-bot/src/main/java/com/juick/components/XMPPBot.java
index 15ba073e..55ae0b7d 100644
--- a/juick-xmpp-bot/src/main/java/com/juick/components/XMPPBot.java
+++ b/juick-xmpp-bot/src/main/java/com/juick/components/XMPPBot.java
@@ -2,16 +2,15 @@ package com.juick.components;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.juick.User;
-import com.juick.server.UserQueries;
import com.juick.server.helpers.UserInfo;
import com.juick.server.protocol.JuickProtocol;
import com.juick.server.protocol.ProtocolReply;
+import com.juick.service.UserService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
-import org.springframework.jdbc.core.JdbcTemplate;
import rocks.xmpp.addr.Jid;
import rocks.xmpp.core.XmppException;
import rocks.xmpp.core.stanza.model.Message;
@@ -32,7 +31,7 @@ import java.net.URL;
public class XMPPBot implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(XMPPBot.class);
@Inject
- JdbcTemplate jdbc;
+ UserService userService;
private ExternalComponent component;
@@ -51,7 +50,7 @@ public class XMPPBot implements AutoCloseable {
ownVCard.setUrl(new URL("http://juick.com/"));
ownVCard.setPhoto(new VCard.Image("image/png", IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("vCard.png"))));
vCardManager.setVCard(ownVCard);
- JuickProtocol protocol = new JuickProtocol(jdbc, "http://juick.com/");
+ JuickProtocol protocol = new JuickProtocol("http://juick.com/");
component.addInboundMessageListener(e -> {
Message message = e.getMessage();
if (message.getType().equals(Message.Type.ERROR) || message.getType().equals(Message.Type.GROUPCHAT)) {
@@ -59,7 +58,7 @@ public class XMPPBot implements AutoCloseable {
}
String text = message.getBody().trim();
String command = text.toUpperCase();
- User user = UserQueries.getUserByJID(jdbc, message.getFrom().asBareJid().toString());
+ User user = userService.getUserByJID(message.getFrom().asBareJid().toString());
if (command.equals("VCARD")) {
try {
VCard vCard = vCardManager.getVCard(message.getFrom().asBareJid()).getResult();
@@ -67,7 +66,7 @@ public class XMPPBot implements AutoCloseable {
info.setFullName(vCard.getFormattedName());
info.setCountry(vCard.getAddresses().get(0).getCountry());
info.setUrl(vCard.getUrl().toString());
- UserQueries.updateUserInfo(jdbc, user, info);
+ userService.updateUserInfo(user, info);
component.sendMessage(new Message(message.getFrom(), Message.Type.CHAT, "vCard updated"));
} catch (XmppException vce) {
logger.warn("vcard exception", vce);
diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java
index 1c13c1a7..f72bcc02 100644
--- a/src/test/java/com/juick/tests/ApiTests.java
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -7,22 +7,33 @@ import com.juick.Message;
import com.juick.Tag;
import com.juick.User;
import com.juick.json.MessageSerializer;
-import com.juick.server.MessagesQueries;
-import com.juick.server.SubscriptionsQueries;
-import com.juick.server.TagQueries;
-import com.juick.server.UserQueries;
import com.juick.server.helpers.TagStats;
import com.juick.server.protocol.JuickProtocol;
import com.juick.server.protocol.ProtocolReply;
+import com.juick.service.MessagesService;
+import com.juick.service.SubscriptionService;
+import com.juick.service.TagService;
+import com.juick.service.UserService;
+import com.juick.service.search.SearchService;
import com.juick.www.PageTemplates;
+import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.TransactionManagementConfigurer;
+import javax.inject.Inject;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
@@ -36,68 +47,128 @@ import static org.junit.Assert.assertNotEquals;
/**
* Created by vt on 14.01.2016.
*/
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration
public class ApiTests {
- JdbcTemplate jdbc;
- DB db;
- @Before
- public void setupConnection() throws ManagedProcessException {
- db = DB.newEmbeddedDB(33306);
- db.start();
- db.createDB("juick");
- db.source("schema.sql");
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
- dataSource.setUrl("jdbc:mysql://localhost:33306/juick?autoReconnect=true&user=root");
- jdbc = new JdbcTemplate(dataSource);
- UserQueries.createUser(jdbc, "ugnich", "secret");
- UserQueries.createUser(jdbc, "juick", "secret");
- }
- @After
- public void teardown() throws ManagedProcessException {
- db.stop();
+ @Configuration
+ @ComponentScan(basePackages = {"com.juick.service", "com.juick.server.protocol"})
+ static class Config implements TransactionManagementConfigurer {
+ @Bean
+ public BasicDataSource dataSource() {
+ try {
+ DB db = DB.newEmbeddedDB(33306);
+ db.start();
+ db.createDB("juick");
+ db.source("schema.sql");
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName("com.mysql.jdbc.Driver");
+ dataSource.setUrl("jdbc:mysql://localhost:33306/juick?autoReconnect=true&user=root");
+
+ dataSource.setValidationQuery("select 1");
+
+ return dataSource;
+ } catch (ManagedProcessException e) {
+ return null;
+ }
+ }
+
+ @Bean
+ public PlatformTransactionManager transactionManager() {
+ return new DataSourceTransactionManager(dataSource());
+ }
+
+ @Override
+ public PlatformTransactionManager annotationDrivenTransactionManager() {
+ return transactionManager();
+ }
+
+ @Bean
+ @DependsOn("dataSource")
+ public JdbcTemplate jdbcTemplate() {
+ return new JdbcTemplate(dataSource());
+ }
+ @Bean
+ public SearchService emptySearchService() {
+ return new SearchService() {
+ @Override
+ public void setMaxResult(int maxResult) {
+ }
+
+ @Override
+ public List<Integer> searchInAllMessages(String searchString, int messageIdBefore) {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public List<Integer> searchByStringAndUser(String searchString, int userId, int messageIdBefore) {
+ return Collections.emptyList();
+ }
+ };
+ }
+ @Bean
+ public JuickProtocol juickProtocol() {
+ return new JuickProtocol("http://localhost:8080/");
+ }
}
-
+ @Inject
+ UserService userService;
+ @Inject
+ MessagesService messagesService;
+ @Inject
+ TagService tagService;
+ @Inject
+ SubscriptionService subscriptionService;
+ @Inject
+ JdbcTemplate jdbcTemplate;
+ @Inject
+ JuickProtocol juickProtocol;
+
+ @Before
+ public void setup() {
+ userService.createUser("ugnich", "secret");
+ userService.createUser("juick", "secret");
+ }
@Test
public void messageTests() {
- int user_id = UserQueries.createUser(jdbc, "mmmme", "secret");
- User user = UserQueries.getUserByUID(jdbc, user_id).orElse(new User());
+ int user_id = userService.createUser("mmmme", "secret");
+ User user = userService.getUserByUID(user_id).orElse(new User());
assertEquals("it should be me", "mmmme", user.getName());
- int mid = MessagesQueries.createMessage(jdbc, user_id, "yo", null, new ArrayList<>());
- Message msg = MessagesQueries.getMessage(jdbc, mid);
+ int mid = messagesService.createMessage(user_id, "yo", null, new ArrayList<>());
+ Message msg = messagesService.getMessage(mid);
assertEquals("yo", msg.getText());
Calendar calendar = Calendar.getInstance();
calendar.setTime(msg.getDate());
assertEquals(2016, calendar.get(Calendar.YEAR));
User me = msg.getUser();
assertEquals("mmmme", me.getName());
- assertEquals("mmmme", MessagesQueries.getMessageAuthor(jdbc, mid).getName());
- int tagID = TagQueries.createTag(jdbc, "weather");
- Tag tag = TagQueries.getTag(jdbc, tagID);
+ assertEquals("mmmme", messagesService.getMessageAuthor(mid).getName());
+ int tagID = tagService.createTag("weather");
+ Tag tag = tagService.getTag(tagID);
List<Tag> tagList = new ArrayList<>();
tagList.add(tag);
- int mid2 = MessagesQueries.createMessage(jdbc, user_id, "yo2", null, tagList);
- Message msg2 = MessagesQueries.getMessage(jdbc, mid2);
+ int mid2 = messagesService.createMessage(user_id, "yo2", null, tagList);
+ Message msg2 = messagesService.getMessage(mid2);
assertEquals(1, msg2.getTags().size());
- assertEquals("we already have ugnich", -1, UserQueries.createUser(jdbc, "ugnich", "x"));
- int ugnich_id = UserQueries.createUser(jdbc, "hugnich", "x");
- User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id).orElse(new User());
- int rid = MessagesQueries.createReply(jdbc, msg2.getMid(), 0, ugnich.getUid(), "bla-bla", null);
+ assertEquals("we already have ugnich", -1, userService.createUser("ugnich", "x"));
+ int ugnich_id = userService.createUser("hugnich", "x");
+ User ugnich = userService.getUserByUID(ugnich_id).orElse(new User());
+ int rid = messagesService.createReply(msg2.getMid(), 0, ugnich.getUid(), "bla-bla", null);
assertEquals(1, rid);
- Message msg3 = MessagesQueries.getMessage(jdbc, mid2);
+ Message msg3 = messagesService.getMessage(mid2);
assertEquals(1, msg3.getReplies());
assertEquals("weather", msg3.getTags().get(0).getName());
- assertEquals(ugnich.getUid(), UserQueries.checkPassword(jdbc, ugnich.getName(), "x"));
- assertEquals(-1, UserQueries.checkPassword(jdbc, ugnich.getName(), "xy"));
- SubscriptionsQueries.subscribeMessage(jdbc, msg.getMid(), ugnich.getUid());
- assertEquals(1, SubscriptionsQueries.getUsersSubscribedToComments(jdbc, msg.getMid(), user.getUid()).size());
- MessagesQueries.deleteMessage(jdbc, user_id, mid);
- MessagesQueries.deleteMessage(jdbc, user_id, mid2);
+ assertEquals(ugnich.getUid(), userService.checkPassword(ugnich.getName(), "x"));
+ assertEquals(-1, userService.checkPassword(ugnich.getName(), "xy"));
+ subscriptionService.subscribeMessage(msg.getMid(), ugnich.getUid());
+ assertEquals(1, subscriptionService.getUsersSubscribedToComments(msg.getMid(), user.getUid()).size());
+ messagesService.deleteMessage(user_id, mid);
+ messagesService.deleteMessage(user_id, mid2);
String htmlTagName = ">_<";
- Tag htmlTag = TagQueries.getTag(jdbc, htmlTagName, true);
+ Tag htmlTag = tagService.getTag(htmlTagName, true);
TagStats htmlTagStats = new TagStats();
htmlTagStats.setTag(htmlTag);
- String dbTagName = jdbc.queryForObject("select name from tags where name=?", String.class, StringEscapeUtils.escapeHtml4(htmlTagName));
+ String dbTagName = jdbcTemplate.queryForObject("select name from tags where name=?", String.class, StringEscapeUtils.escapeHtml4(htmlTagName));
assertNotEquals("db tags should be escaped", dbTagName, htmlTag.getName());
assertEquals("object tags should unescaped", htmlTag.getName(), StringEscapeUtils.unescapeHtml4(dbTagName));
assertEquals("template should encode escaped tag in url and show escaped tag in name",
@@ -106,97 +177,95 @@ public class ApiTests {
@Test
public void protocolTests() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, ParseException, JsonProcessingException {
- String baseUri = "http://localhost/";
- JuickProtocol protocol = new JuickProtocol(jdbc, baseUri);
MessageSerializer json = new MessageSerializer();
- assertEquals("juick user should have uid 2", 2, UserQueries.getUIDbyName(jdbc, "juick"));
- int uid = UserQueries.createUser(jdbc, "me", "secret");
- User user = UserQueries.getUserByUID(jdbc, uid).orElse(new User());
+ assertEquals("juick user should have uid 2", 2, userService.getUIDbyName("juick"));
+ int uid = userService.createUser("me", "secret");
+ User user = userService.getUserByUID(uid).orElse(new User());
String expectedMessage = "New message posted";
assertEquals("should be message", true,
- protocol.getReply(user, "*yo yoyo").getDescription().startsWith(expectedMessage));
- int mid = MessagesQueries.getUserBlog(jdbc, user.getUid(), -1, 0).stream().reduce((first, second) -> second).get();
+ juickProtocol.getReply(user, "*yo yoyo").getDescription().startsWith(expectedMessage));
+ int mid = messagesService.getUserBlog(user.getUid(), -1, 0).stream().reduce((first, second) -> second).get();
assertEquals("text should match", "yoyo",
- MessagesQueries.getMessage(jdbc, mid).getText());
+ messagesService.getMessage(mid).getText());
assertEquals("tag should match", "yo",
- MessagesQueries.getMessageTags(jdbc, mid).get(0).getTag().getName());
- assertNotEquals("should not be error", "Error", protocol.getReply(user, "#" + mid).getDescription());
- assertEquals("should be PONG", "PONG", protocol.getReply(user, " ping \n ").getDescription());
- int readerUid = UserQueries.createUser(jdbc, "dummyReader", "dummySecret");
- User readerUser = UserQueries.getUserByUID(jdbc, readerUid).orElse(new User());
+ tagService.getMessageTags(mid).get(0).getTag().getName());
+ assertNotEquals("should not be error", "Error", juickProtocol.getReply(user, "#" + mid).getDescription());
+ assertEquals("should be PONG", "PONG", juickProtocol.getReply(user, " ping \n ").getDescription());
+ int readerUid = userService.createUser("dummyReader", "dummySecret");
+ User readerUser = userService.getUserByUID(readerUid).orElse(new User());
assertEquals("should be subscribed", "Subscribed",
- protocol.getReply(readerUser, "S #" + mid).getDescription());
+ juickProtocol.getReply(readerUser, "S #" + mid).getDescription());
assertEquals("number of subscribed users should match", 1,
- SubscriptionsQueries.getUsersSubscribedToComments(jdbc, mid, uid).size());
+ subscriptionService.getUsersSubscribedToComments(mid, uid).size());
assertEquals("should be subscribed", "Subscribed",
- protocol.getReply(readerUser, "S @" + user.getName()).getDescription());
- List<User> friends = UserQueries.getUserFriends(jdbc, readerUid);
+ juickProtocol.getReply(readerUser, "S @" + user.getName()).getDescription());
+ List<User> friends = userService.getUserFriends(readerUid);
assertEquals("number of friend users should match", 2,
friends.size());
assertEquals("number of reader users should match", 1,
- UserQueries.getUserReaders(jdbc, uid).size());
+ userService.getUserReaders(uid).size());
String expectedReply = "Reply posted.\n#" + mid + "/1 "
- +baseUri + mid + "/1";
+ + juickProtocol.getBaseUri() + mid + "/1";
String expectedSecondReply = "Reply posted.\n#" + mid + "/2 "
- + baseUri + mid + "/2";
+ + juickProtocol.getBaseUri() + mid + "/2";
assertEquals("should be reply", expectedReply,
- protocol.getReply(user, "#" + mid + " yoyo").getDescription());
+ juickProtocol.getReply(user, "#" + mid + " yoyo").getDescription());
assertEquals("should be second reply", expectedSecondReply,
- protocol.getReply(user, "#" + mid + "/1 yoyo").getDescription());
- Message reply = MessagesQueries.getReplies(jdbc, mid).stream().filter(m -> m.getRid() == 2).findFirst()
+ juickProtocol.getReply(user, "#" + mid + "/1 yoyo").getDescription());
+ Message reply = messagesService.getReplies(mid).stream().filter(m -> m.getRid() == 2).findFirst()
.orElse(new Message());
assertEquals("should be reply to first comment", 1, reply.getReplyto());
- String jsonReply = protocol.getReply(user, "#" + mid).getJson().orElse("");
+ String jsonReply = juickProtocol.getReply(user, "#" + mid).getJson().orElse("");
JSONArray jsonMessages = new JSONArray(jsonReply);
Message receivedMsg = json.deserialize(jsonMessages.getJSONObject(0));
assertEquals("json should match text", "yoyo", receivedMsg.getText());
assertEquals("array length should match", 1, jsonMessages.length());
- jsonReply = protocol.getReply(user, "#" + mid+"+").getJson().orElse("");
+ jsonReply = juickProtocol.getReply(user, "#" + mid+"+").getJson().orElse("");
jsonMessages = new JSONArray(jsonReply);
assertEquals("array length should match", 3, jsonMessages.length());
assertNotEquals("tags should NOT be updated", "Tags are updated",
- protocol.getReply(readerUser, "#" + mid + " *yo *there").getDescription());
+ juickProtocol.getReply(readerUser, "#" + mid + " *yo *there").getDescription());
assertEquals("tags should be updated", "Tags are updated",
- protocol.getReply(user, "#" + mid + " *there").getDescription());
+ juickProtocol.getReply(user, "#" + mid + " *there").getDescription());
assertEquals("number of tags should match", 2,
- MessagesQueries.getMessageTags(jdbc, mid).size());
+ tagService.getMessageTags(mid).size());
assertEquals("tags should be updated", "Tags are updated",
- protocol.getReply(user, "#" + mid + " *there").getDescription());
+ juickProtocol.getReply(user, "#" + mid + " *there").getDescription());
assertEquals("number of tags should match", 1,
- MessagesQueries.getMessageTags(jdbc, mid).size());
- int taggerUid = UserQueries.createUser(jdbc, "dummyTagger", "dummySecret");
- User taggerUser = UserQueries.getUserByUID(jdbc, taggerUid).orElse(new User());
+ tagService.getMessageTags(mid).size());
+ int taggerUid = userService.createUser("dummyTagger", "dummySecret");
+ User taggerUser = userService.getUserByUID(taggerUid).orElse(new User());
assertEquals("should be subscribed", "Subscribed",
- protocol.getReply(taggerUser, "S *yo").getDescription());
+ juickProtocol.getReply(taggerUser, "S *yo").getDescription());
assertEquals("number of subscribed users should match", 2,
- SubscriptionsQueries.getSubscribedUsers(jdbc, uid, mid).size());
+ subscriptionService.getSubscribedUsers(uid, mid).size());
assertEquals("should be unsubscribed", "Unsubscribed from yo",
- protocol.getReply(taggerUser, "U *yo").getDescription());
+ juickProtocol.getReply(taggerUser, "U *yo").getDescription());
assertEquals("number of subscribed users should match", 1,
- SubscriptionsQueries.getSubscribedUsers(jdbc, uid, mid).size());
+ subscriptionService.getSubscribedUsers(uid, mid).size());
assertEquals("number of readers should match", 1,
- UserQueries.getUserReaders(jdbc, uid).size());
- ProtocolReply readerFeed = protocol.getReply(readerUser, "#");
+ userService.getUserReaders(uid).size());
+ ProtocolReply readerFeed = juickProtocol.getReply(readerUser, "#");
assertEquals("description should match", true, readerFeed.getDescription().startsWith("Your feed"));
String readerUserFeed = readerFeed.getJson().orElse("");
JSONArray readerUserFeedMessages = new JSONArray(readerUserFeed);
assertEquals("messages count should match", 1, readerUserFeedMessages.length());
assertEquals("should be unsubscribed", "Unsubscribed from @" + user.getName(),
- protocol.getReply(readerUser, "U @" + user.getName()).getDescription());
+ juickProtocol.getReply(readerUser, "U @" + user.getName()).getDescription());
assertEquals("number of readers should match", 0,
- UserQueries.getUserReaders(jdbc, uid).size());
+ userService.getUserReaders(uid).size());
assertEquals("number of friends should match", 1,
- UserQueries.getUserFriends(jdbc, uid).size());
+ userService.getUserFriends(uid).size());
assertEquals("should be unsubscribed", "Unsubscribed from #" + mid,
- protocol.getReply(readerUser, "u #" + mid).getDescription());
+ juickProtocol.getReply(readerUser, "u #" + mid).getDescription());
assertEquals("number of subscribed users should match", 0,
- SubscriptionsQueries.getUsersSubscribedToComments(jdbc, mid, uid).size());
+ subscriptionService.getUsersSubscribedToComments(mid, uid).size());
assertNotEquals("should NOT be deleted", String.format("Message %s deleted", mid),
- protocol.getReply(readerUser, "D #" + mid).getDescription());
+ juickProtocol.getReply(readerUser, "D #" + mid).getDescription());
assertEquals("should be deleted", String.format("Message %s deleted", mid),
- protocol.getReply(user, "D #" + mid).getDescription());
- assertEquals("should not have messages", 0, MessagesQueries.getAll(jdbc, user.getUid(), 0).size());
- String allFeed = protocol.getReply(readerUser, "#").getJson().orElse("");
+ juickProtocol.getReply(user, "D #" + mid).getDescription());
+ assertEquals("should not have messages", 0, messagesService.getAll(user.getUid(), 0).size());
+ String allFeed = juickProtocol.getReply(readerUser, "#").getJson().orElse("");
JSONArray allFeedMessages = new JSONArray(allFeed);
assertEquals("messages count should match", 0, allFeedMessages.length());
}