diff --git a/pages/index.html b/pages/index.html index 5b7cd6e..bdf6917 100644 --- a/pages/index.html +++ b/pages/index.html @@ -8,13 +8,7 @@ - +
diff --git a/pages/js/index.js b/pages/js/index.js new file mode 100644 index 0000000..823878a --- /dev/null +++ b/pages/js/index.js @@ -0,0 +1,9 @@ +/** + * Created by Norbi on 2016-08-05. + */ + +$(document).ready(function () { + var cmsgs = document.getElementById("channelmessages"); + if (cmsgs != null && cmsgs.childElementCount > 0) + cmsgs.lastElementChild.scrollIntoView(false); +}); diff --git a/pages/js/message.js b/pages/js/message.js index eee0559..4c98778 100644 --- a/pages/js/message.js +++ b/pages/js/message.js @@ -2,7 +2,7 @@ var sendmsg = function sendmsg(msginputta) { window.jsonobj = JSON.stringify({"message": msginputta.value, "conversation": window.convid}); console.log(window.jsonobj); $.ajax({ - url: "/message", data: window.jsonobj, method: "POST", success: respfunc, error: respfunc + url: "/sendmessage", data: window.jsonobj, method: "POST", success: respfunc, error: respfunc }); }; diff --git a/src/io/github/norbipeti/chat/server/Main.java b/src/io/github/norbipeti/chat/server/Main.java index 1c2fde9..7c74e35 100644 --- a/src/io/github/norbipeti/chat/server/Main.java +++ b/src/io/github/norbipeti/chat/server/Main.java @@ -29,6 +29,7 @@ public class Main { // https://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/ // https://docs.oracle.com/javase/8/docs/api/ LogManager.getLogger().log(Level.INFO, "Loading files..."); + DataManager.init(); final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(new TypeToken>() { }.getType(), new LoaderCollectionSerializer()); @@ -44,44 +45,18 @@ public class Main { }.getType(), new LoaderRefSerializer()); gson = gsonBuilder.create(); /* - * User user = new User(); user.setName("asd"); - * user.setEmail("test@test.com"); User user2 = new User(); - * user2.setName("Teszt"); user2.setEmail("test2@test.com"); // user - * = provider.save(user); // user2 = provider.save(user2); - * user.getContacts().add(user2); user2.getContacts().add(user); - * LogManager.getLogger().log(Level.DEBUG, "1st's contact: " + - * user.getContacts().get(0)); - * LogManager.getLogger().log(Level.DEBUG, "2nd's contact: " + - * user2.getContacts().get(0)); Conversation conversation = new - * Conversation(); conversation.getUsers().add(user); - * user.getConversations().add(conversation); - * LogManager.getLogger().debug("User: " + user); - * conversation.getUsers().add(user2); - * LogManager.getLogger().debug("User2: " + user2); - * user2.getConversations().add(conversation); Message msg = new - * Message(); msg.setSender(user); msg.setTime(new Date()); - * msg.setMessage("Teszt 1"); conversation.getMesssages().add(msg); - * Message msg2 = new Message(); msg2.setSender(user2); - * msg2.setTime(new Date()); msg2.setMessage("Teszt 2"); - * conversation.getMesssages().add(msg2); // provider.save(user); // - * provider.save(user2);s User loggedinuser = new User(); - * loggedinuser.setName("NorbiPeti"); - * loggedinuser.setSessionid("093b1395-8c31-4f3b-ba67-828a755af92e") - * ; loggedinuser.setEmail("sznp@asd.com"); - * loggedinuser.getContacts().add(user2); - * conversation.getUsers().add(loggedinuser); - * loggedinuser.getConversations().add(conversation); - * DataManager.save(user); DataManager.save(user2); - * DataManager.save(loggedinuser); DataManager.save(conversation); + * User user = new User(); user.setName("asd"); user.setEmail("test@test.com"); User user2 = new User(); user2.setName("Teszt"); user2.setEmail("test2@test.com"); // user = + * provider.save(user); // user2 = provider.save(user2); user.getContacts().add(user2); user2.getContacts().add(user); LogManager.getLogger().log(Level.DEBUG, "1st's contact: " + + * user.getContacts().get(0)); LogManager.getLogger().log(Level.DEBUG, "2nd's contact: " + user2.getContacts().get(0)); Conversation conversation = new Conversation(); + * conversation.getUsers().add(user); user.getConversations().add(conversation); LogManager.getLogger().debug("User: " + user); conversation.getUsers().add(user2); + * LogManager.getLogger().debug("User2: " + user2); user2.getConversations().add(conversation); Message msg = new Message(); msg.setSender(user); msg.setTime(new Date()); + * msg.setMessage("Teszt 1"); conversation.getMesssages().add(msg); Message msg2 = new Message(); msg2.setSender(user2); msg2.setTime(new Date()); msg2.setMessage("Teszt 2"); + * conversation.getMesssages().add(msg2); // provider.save(user); // provider.save(user2);s User loggedinuser = new User(); loggedinuser.setName("NorbiPeti"); + * loggedinuser.setSessionid("093b1395-8c31-4f3b-ba67-828a755af92e") ; loggedinuser.setEmail("sznp@asd.com"); loggedinuser.getContacts().add(user2); + * conversation.getUsers().add(loggedinuser); loggedinuser.getConversations().add(conversation); DataManager.save(user); DataManager.save(user2); DataManager.save(loggedinuser); + * DataManager.save(conversation); */ - - LogManager.getLogger().log(Level.INFO, "Starting webserver..."); // TODO: - // Separate - // IDs - // for - // conversations - // and - // users + LogManager.getLogger().log(Level.INFO, "Starting webserver..."); // TODO: Separate IDs for conversations and users HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 10); Reflections rf = new Reflections( new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(Page.class.getClassLoader())) @@ -105,11 +80,10 @@ public class Main { System.in.read(); LogManager.getLogger().log(Level.INFO, "Stopping..."); server.stop(1); - } catch ( - - Exception e) { + } catch (Exception e) { e.printStackTrace(); } + DataManager.save(); LogManager.getLogger().log(Level.INFO, "Stopped"); } diff --git a/src/io/github/norbipeti/chat/server/data/DataManager.java b/src/io/github/norbipeti/chat/server/data/DataManager.java index 1d5c162..ae10b01 100644 --- a/src/io/github/norbipeti/chat/server/data/DataManager.java +++ b/src/io/github/norbipeti/chat/server/data/DataManager.java @@ -5,8 +5,10 @@ import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import com.google.common.io.Files; import io.github.norbipeti.chat.server.Main; @@ -16,13 +18,12 @@ public final class DataManager { private DataManager() { } + private static final File datafolder = new File("data"); + public static void save(T object) { try { - File file = new File(object.getClass().getName() + "-" + object.getId()); - while (file.exists()) { - object.setId(object.getId() + 1); - file = new File(object.getClass().getName() + "-" + object.getId()); - } + File file = new File(datafolder, getFileName(object.getClass(), object.getId())); + cache.put(file, object); Files.write(Main.gson.toJson(object), file, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); @@ -30,33 +31,39 @@ public final class DataManager { } public static T load(Class cl, long id) { - return loadFromFile(new File(cl.getName() + "-" + id), cl); + return loadFromFile(new File(datafolder, getFileName(cl, id)), cl); } - public static LoaderCollection load(Class cl) { - String[] filenames = new File(".").list(new FilenameFilter() { + public static LoaderCollection getAll(Class cl) { + String[] filenames = datafolder.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { - return name.startsWith(cl.getName() + "-"); + return name.startsWith(getFileName(cl, null)); } }); LoaderCollection rets = new LoaderCollection(cl, filenames.length); for (int i = 0; i < filenames.length; i++) { - rets.add(loadFromFile(new File(filenames[i]), cl)); + try { + rets.idlist.add(Long.parseLong(filenames[i].split("\\-")[1].split("\\.")[0])); + } catch (NumberFormatException e) { + e.printStackTrace(); + } } return rets; } private static Map cache = new HashMap<>(); // TODO: Remove objects from the cache over time - // TODO: Save the object when it happens + // TODO: Save the object when it gets removed from cache and when the app stops @SuppressWarnings("unchecked") private static T loadFromFile(File file, Class cl) { try { - if (!file.exists()) - return cl.newInstance(); + if (!file.exists()) { + T obj = cl.newInstance(); + return obj; + } if (cache.containsKey(file)) return (T) cache.get(file); BufferedReader reader = Files.newReader(file, StandardCharsets.UTF_8); @@ -67,7 +74,9 @@ public final class DataManager { T obj = Main.gson.fromJson(objstr, cl); cache.put(file, obj); return obj; - } catch (Exception e) { + } catch ( + + Exception e) { e.printStackTrace(); } return null; @@ -76,10 +85,79 @@ public final class DataManager { public static boolean remove(T obj) { if (cache.containsValue(obj)) cache.values().remove(obj); - return new File(obj.getClass().getName() + "-" + obj.getId()).delete(); + return new File(obj.getClass().getSimpleName() + "-" + obj.getId()).delete(); } public static boolean remove(Class cl, Long id) { return new File(cl.getName() + "-" + id).delete(); } + + public static void init() { + packagename = SavedData.class.getPackage().getName(); + datafolder.mkdir(); + nextids = loadNextIDs(); + } + + private static String packagename; + + public static String getPackageName() { + return packagename; + } + + public static void save() { + saveNextIDs(nextids); + for (Entry item : cache.entrySet()) { + DataManager.save((SavedData) item.getValue()); + } + } + + private static HashMap, Long> nextids; + + public static Map, Long> getNextIDs() { + return Collections.unmodifiableMap(nextids); + } + + public static void setNextID(Class cl, Long id) { + nextids.put(cl, id); + } + + @SuppressWarnings("unchecked") + private static HashMap, Long> loadNextIDs() { + try { + File file = new File("data", "idlist.ini"); + if (!file.exists()) + return new HashMap<>(); + BufferedReader reader = Files.newReader(file, StandardCharsets.UTF_8); + String line; + HashMap, Long> ret = new HashMap<>(); + while ((line = reader.readLine()) != null) { + String[] spl = line.split("\\="); + ret.put((Class) Class.forName(packagename + "." + spl[0]), Long.parseLong(spl[1])); + } + return ret; + } catch (Exception e) { + e.printStackTrace(); + } + return new HashMap<>(); + } + + private static void saveNextIDs(HashMap, Long> ids) { + try { + File file = new File("data", "idlist.ini"); + String contents = ""; + for (Entry, Long> item : ids.entrySet()) { + contents += item.getKey().getName() + "=" + item.getValue() + "\n"; + } + Files.write(contents, file, StandardCharsets.UTF_8); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static String getFileName(Class cl, Long id) { + if (id != null) + return cl.getSimpleName() + "-" + id + ".json"; + else + return cl.getSimpleName() + "-"; + } } diff --git a/src/io/github/norbipeti/chat/server/data/LoaderCollection.java b/src/io/github/norbipeti/chat/server/data/LoaderCollection.java index a50b457..1bdda29 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderCollection.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderCollection.java @@ -86,8 +86,6 @@ public class LoaderCollection implements List, Serializa @Override public void clear() { - for (Long id : idlist) - DataManager.remove(cl, id); // TODO: Move out to a main list idlist.clear(); } @@ -197,7 +195,6 @@ public class LoaderCollection implements List, Serializa @Override public List subList(int fromIndex, int toIndex) { - // TODO Auto-generated method stub return new LoaderCollection(this, fromIndex, toIndex); } diff --git a/src/io/github/norbipeti/chat/server/data/LoaderCollectionSerializer.java b/src/io/github/norbipeti/chat/server/data/LoaderCollectionSerializer.java index 77c7a70..cbab388 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderCollectionSerializer.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderCollectionSerializer.java @@ -7,26 +7,35 @@ import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import io.github.norbipeti.chat.server.db.domain.SavedData; -//@SuppressWarnings("rawtypes") +// @SuppressWarnings("rawtypes") public class LoaderCollectionSerializer extends TypeAdapter> { @Override public void write(JsonWriter out, LoaderCollection value) throws IOException { - out.beginObject(); + if (value == null) { + out.nullValue(); + return; + } + out.beginObject(); // TODO: http://stackoverflow.com/a/17300227 out.name("items"); new Gson().toJson(value.idlist, new TypeToken>() { }.getType(), out); - out.name("class").value(value.cl.getName()); + out.name("class").value(value.cl.getSimpleName()); out.endObject(); } @SuppressWarnings("unchecked") @Override public LoaderCollection read(JsonReader in) throws IOException { + if (in.peek().equals(JsonToken.NULL)) { + in.nextNull(); + return null; + } in.beginObject(); in.nextName(); List list = new Gson().fromJson(in, new TypeToken>() { @@ -37,12 +46,12 @@ public class LoaderCollectionSerializer extends TypeAdapter } Class cl; try { - cl = (Class) Class.forName(in.nextString()); + cl = (Class) Class.forName(DataManager.getPackageName() + "." + in.nextString()); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } - LoaderCollection col = new LoaderCollection(cl); // TODO + LoaderCollection col = new LoaderCollection(cl); col.idlist.addAll(list); in.endObject(); return col; diff --git a/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java b/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java index 8a3e0c1..c2a4699 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java @@ -3,19 +3,24 @@ package io.github.norbipeti.chat.server.data; import java.io.IOException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import io.github.norbipeti.chat.server.db.domain.SavedData; -//@SuppressWarnings("rawtypes") +// @SuppressWarnings("rawtypes") public class LoaderRefSerializer extends TypeAdapter> { @Override public void write(JsonWriter out, LoaderRef value) throws IOException { + if (value == null) { + out.nullValue(); + return; + } out.beginObject(); out.name("id"); out.value(value.id); - out.name("class").value(value.cl.getName()); + out.name("class").value(value.cl.getSimpleName()); out.endObject(); } @@ -23,6 +28,10 @@ public class LoaderRefSerializer extends TypeAdapter read(JsonReader in) throws IOException { + if (in.peek().equals(JsonToken.NULL)) { + in.nextNull(); + return null; + } in.beginObject(); in.nextName(); long id = in.nextLong(); @@ -32,12 +41,12 @@ public class LoaderRefSerializer extends TypeAdapter cl; try { - cl = (Class) Class.forName(in.nextString()); + cl = (Class) Class.forName(DataManager.getPackageName() + "." + in.nextString()); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } - LoaderRef col = new LoaderRef(cl, id); // TODO + LoaderRef col = new LoaderRef(cl, id); in.endObject(); return col; } diff --git a/src/io/github/norbipeti/chat/server/db/domain/Conversation.java b/src/io/github/norbipeti/chat/server/db/domain/Conversation.java index 38d73b5..312cfc5 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/Conversation.java +++ b/src/io/github/norbipeti/chat/server/db/domain/Conversation.java @@ -50,4 +50,7 @@ public class Conversation extends SavedData { public void setId(long id) { this.id = id; } + + private Conversation() { + } } diff --git a/src/io/github/norbipeti/chat/server/db/domain/Message.java b/src/io/github/norbipeti/chat/server/db/domain/Message.java index 93c0062..4a3611e 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/Message.java +++ b/src/io/github/norbipeti/chat/server/db/domain/Message.java @@ -65,8 +65,6 @@ public class Message implements Serializable { } /* - * public Long getId() { return id; } - * - * public void setId(Long id) { this.id = id; } + * public Long getId() { return id; } public void setId(Long id) { this.id = id; } */ } diff --git a/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java b/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java index cf4d4bc..f669501 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java +++ b/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java @@ -42,4 +42,7 @@ public class MessageChunk extends SavedData { public void setId(long id) { this.id = id; } + + private MessageChunk() { + } } diff --git a/src/io/github/norbipeti/chat/server/db/domain/SavedData.java b/src/io/github/norbipeti/chat/server/db/domain/SavedData.java index e6344e4..75a7e10 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/SavedData.java +++ b/src/io/github/norbipeti/chat/server/db/domain/SavedData.java @@ -1,10 +1,33 @@ package io.github.norbipeti.chat.server.db.domain; import java.io.Serializable; +import java.lang.reflect.Constructor; + +import io.github.norbipeti.chat.server.data.DataManager; @SuppressWarnings("serial") public abstract class SavedData implements Serializable { public abstract long getId(); public abstract void setId(long id); + + protected SavedData() { + } + + public static T create(Class cl) { + T obj; + try { + Constructor constructor = cl.getDeclaredConstructor(new Class[0]); + constructor.setAccessible(true); + obj = constructor.newInstance(); + constructor.setAccessible(false); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + obj.setId(DataManager.getNextIDs().getOrDefault(obj.getClass(), 0L)); + DataManager.setNextID(obj.getClass(), obj.getId() + 1); + DataManager.save(obj); + return obj; + } } diff --git a/src/io/github/norbipeti/chat/server/db/domain/User.java b/src/io/github/norbipeti/chat/server/db/domain/User.java index 8cfdff0..c7a80ff 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/User.java +++ b/src/io/github/norbipeti/chat/server/db/domain/User.java @@ -93,11 +93,11 @@ public class User extends SavedData { return conversations; } - public User() { + private User() { } public static LoaderCollection getUsers() { - return DataManager.load(User.class); + return DataManager.getAll(User.class); } @Override diff --git a/src/io/github/norbipeti/chat/server/io/IOHelper.java b/src/io/github/norbipeti/chat/server/io/IOHelper.java index b6ffa5e..dbe7eb0 100644 --- a/src/io/github/norbipeti/chat/server/io/IOHelper.java +++ b/src/io/github/norbipeti/chat/server/io/IOHelper.java @@ -7,11 +7,8 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.time.LocalDateTime; -import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -136,6 +133,7 @@ public class IOHelper { user.setSessionid(UUID.randomUUID().toString()); new Cookies(2).add(new Cookie("user_id", user.getId() + "")).add(new Cookie("session_id", user.getSessionid())) .SendHeaders(exchange); + LogManager.getLogger().debug("Logged in user."); } public static void LogoutUser(HttpExchange exchange, User user) { @@ -182,8 +180,7 @@ public class IOHelper { } /** - * Get logged in user. It may also send logout headers if the cookies are - * invalid, or login headers to keep the user logged in. + * Get logged in user. It may also send logout headers if the cookies are invalid, or login headers to keep the user logged in. * * @param exchange * @return The logged in user or null if not logged in. diff --git a/src/io/github/norbipeti/chat/server/page/IndexPage.java b/src/io/github/norbipeti/chat/server/page/IndexPage.java index fc97c7c..35be43b 100644 --- a/src/io/github/norbipeti/chat/server/page/IndexPage.java +++ b/src/io/github/norbipeti/chat/server/page/IndexPage.java @@ -9,9 +9,11 @@ import org.jsoup.nodes.Element; import com.sun.net.httpserver.HttpExchange; import io.github.norbipeti.chat.server.data.DataManager; +import io.github.norbipeti.chat.server.data.LoaderCollection; import io.github.norbipeti.chat.server.db.domain.Conversation; import io.github.norbipeti.chat.server.db.domain.Message; import io.github.norbipeti.chat.server.db.domain.MessageChunk; +import io.github.norbipeti.chat.server.db.domain.SavedData; import io.github.norbipeti.chat.server.db.domain.User; import io.github.norbipeti.chat.server.io.IOHelper; @@ -21,9 +23,9 @@ public class IndexPage extends Page { public void handlePage(HttpExchange exchange) throws IOException { final User user = IOHelper.GetLoggedInUser(exchange); /* - * final User user = new User(); user.setEmail("test@test.com"); - * user.setName("Norbi"); user.setId(3L); + * final User user = new User(); user.setEmail("test@test.com"); user.setName("Norbi"); user.setId(3L); */ + LogManager.getLogger().debug("Logged in user: " + user); if (user == null) IOHelper.SendModifiedPage(200, this, (doc) -> { doc.getElementById("userbox").remove(); @@ -37,19 +39,25 @@ public class IndexPage extends Page { Element userbox = doc.getElementById("userbox"); userbox.html(userbox.html().replace("", user.getName())); Element channelmessages = doc.getElementById("channelmessages"); - LogManager.getLogger().log(Level.INFO, "Conversations: " + DataManager.load(Conversation.class).size()); + LogManager.getLogger().log(Level.INFO, + "Conversations: " + DataManager.getAll(Conversation.class).size()); LogManager.getLogger().log(Level.INFO, "User conversations: " + user.getConversations().size()); LogManager.getLogger().log(Level.INFO, "Username: " + user.getName()); - if (user.getConversations().size() == 0) - user.getConversations().add(DataManager.load(Conversation.class).get(0)); + if (user.getConversations().size() == 0) { + LoaderCollection convs = DataManager.getAll(Conversation.class); + if (convs.size() == 0) { + Conversation c = SavedData.create(Conversation.class); + convs.add(c); // TODO: Handle no conversation open + } + user.getConversations().add(convs.get(0)); + } Conversation conv = user.getConversations().get(0); Element cide = channelmessages.appendElement("p"); cide.attr("style", "display: none"); cide.attr("id", "convidp"); cide.text(Long.toString(conv.getId())); LogManager.getLogger().log(Level.INFO, "Messages: " + conv.getMesssageChunks().size()); - for (MessageChunk chunk : conv.getMesssageChunks()) { // TODO: - // Reverse + for (MessageChunk chunk : conv.getMesssageChunks()) { // TODO: Reverse for (Message message : chunk.getMessages()) { Element msgelement = channelmessages.appendElement("div"); Element header = msgelement.appendElement("p"); @@ -60,14 +68,7 @@ public class IndexPage extends Page { } return doc; }, exchange); - } // TODO: - // Validation - // at - // registration - // (no - // special - // chars, - // etc.) + } // TODO: Validation at registration (no special chars, etc.) @Override public String GetName() { diff --git a/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java b/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java index 7418a08..cad7ce4 100644 --- a/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java @@ -20,7 +20,7 @@ public class LoginAjaxPage extends Page { return; } User loginuser = null; - for (User user : DataManager.load(User.class)) { + for (User user : DataManager.getAll(User.class)) { if (user.getEmail().equals(post.get("email").getAsString())) { loginuser = user; break; diff --git a/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java b/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java index 4d2fa71..374e2ae 100644 --- a/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java @@ -12,14 +12,15 @@ import io.github.norbipeti.chat.server.data.LoaderCollection; import io.github.norbipeti.chat.server.db.domain.Conversation; import io.github.norbipeti.chat.server.db.domain.Message; import io.github.norbipeti.chat.server.db.domain.MessageChunk; +import io.github.norbipeti.chat.server.db.domain.SavedData; import io.github.norbipeti.chat.server.db.domain.User; import io.github.norbipeti.chat.server.io.IOHelper; public class ReceiveMessageAjaxPage extends Page { @Override - public String GetName() { //TODO - return "message"; //TODO: Update cookie every once in a while + public String GetName() { + return "receivemessage"; // TODO: Update cookie every once in a while } @Override @@ -27,14 +28,12 @@ public class ReceiveMessageAjaxPage extends Page { User user = IOHelper.GetLoggedInUser(exchange); if (user == null) { IOHelper.SendResponse(403, "

Please log in to send messages

", exchange); - return; // TODO: Fix sending messages + return; } JsonObject obj = IOHelper.GetPOSTJSON(exchange); if (obj == null) { /* - * IOHelper.SendResponse(400, - * "

400 Bad request

Not a JSON string!

" + - * IOHelper.GetPOST(exchange) + "

", exchange); + * IOHelper.SendResponse(400, "

400 Bad request

Not a JSON string!

" + IOHelper.GetPOST(exchange) + "

", exchange); */ IOHelper.SendResponse(400, "JSONERROR", exchange); return; @@ -67,16 +66,14 @@ public class ReceiveMessageAjaxPage extends Page { + conversation + " is not found.

", exchange); return; } - MessageChunk chunk = new MessageChunk(); // TODO: Automatize + MessageChunk chunk = SavedData.create(MessageChunk.class); chunk.setConversation(conv); Message msg = new Message(); msg.setSender(user); msg.setMessage(message); msg.setTime(new Date()); - msg.setMessageChunk(chunk); // TODO: Store relations at one side or - // both); + msg.setMessageChunk(chunk); chunk.getMessages().add(msg); - //DataManager.save(chunk); - TODO conv.getMesssageChunks().add(chunk); DataManager.save(conv); LogManager.getLogger().log(Level.DEBUG, diff --git a/src/io/github/norbipeti/chat/server/page/RegisterAjaxPage.java b/src/io/github/norbipeti/chat/server/page/RegisterAjaxPage.java index e34579c..bb7ff17 100644 --- a/src/io/github/norbipeti/chat/server/page/RegisterAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/RegisterAjaxPage.java @@ -7,6 +7,7 @@ import com.google.gson.JsonObject; import com.sun.net.httpserver.HttpExchange; import io.github.norbipeti.chat.server.data.DataManager; +import io.github.norbipeti.chat.server.db.domain.SavedData; import io.github.norbipeti.chat.server.db.domain.User; import io.github.norbipeti.chat.server.io.IOHelper; @@ -21,7 +22,7 @@ public class RegisterAjaxPage extends Page { IOHelper.SendResponse(200, (doc) -> doc.html(msg).ownerDocument(), exchange); return; // TODO: Use JavaScript too, for error checks } - for (User user : DataManager.load(User.class)) { // TODO: Optimize + for (User user : DataManager.getAll(User.class)) { // TODO: Optimize if (post.get("email").equals(user.getEmail())) { errormsg += "

An user with this name already exists

"; break; @@ -34,7 +35,7 @@ public class RegisterAjaxPage extends Page { IOHelper.SendResponse(200, (doc) -> doc.html(msg).ownerDocument(), exchange); return; } - User user = new User(); + User user = SavedData.create(User.class); user.setName(post.get("name").getAsString()); user.setEmail(post.get("email").getAsString()); user.setSalt(BCrypt.gensalt()); // http://www.mindrot.org/projects/jBCrypt/ diff --git a/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java b/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java index afbb3c4..57c5ce8 100644 --- a/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java @@ -12,6 +12,7 @@ import io.github.norbipeti.chat.server.data.LoaderCollection; import io.github.norbipeti.chat.server.db.domain.Conversation; import io.github.norbipeti.chat.server.db.domain.Message; import io.github.norbipeti.chat.server.db.domain.MessageChunk; +import io.github.norbipeti.chat.server.db.domain.SavedData; import io.github.norbipeti.chat.server.db.domain.User; import io.github.norbipeti.chat.server.io.IOHelper; @@ -19,7 +20,7 @@ public class SendMessageAjaxPage extends Page { @Override public String GetName() { - return "message"; + return "sendmessage"; } @Override @@ -27,16 +28,14 @@ public class SendMessageAjaxPage extends Page { User user = IOHelper.GetLoggedInUser(exchange); if (user == null) { IOHelper.SendResponse(403, "

Please log in to send messages

", exchange); - return; // TODO: Fix sending messages + return; } JsonObject obj = IOHelper.GetPOSTJSON(exchange); if (obj == null) { - /* - * IOHelper.SendResponse(400, - * "

400 Bad request

Not a JSON string!

" + - * IOHelper.GetPOST(exchange) + "

", exchange); - */ - IOHelper.SendResponse(400, "JSONERROR", exchange); + IOHelper.SendResponse(400, + "

400 Bad request

Not a JSON string!

" + IOHelper.GetPOST(exchange) + "

", + exchange); + // IOHelper.SendResponse(400, "JSONERROR", exchange); return; } if (!obj.has("message") || !obj.has("conversation")) { @@ -67,16 +66,14 @@ public class SendMessageAjaxPage extends Page { + conversation + " is not found.

", exchange); return; } - MessageChunk chunk = new MessageChunk(); // TODO: Automatize + MessageChunk chunk = SavedData.create(MessageChunk.class); // TODO: Automatize chunk.setConversation(conv); Message msg = new Message(); msg.setSender(user); msg.setMessage(message); msg.setTime(new Date()); - msg.setMessageChunk(chunk); // TODO: Store relations at one side or - // both); + msg.setMessageChunk(chunk); // TODO: Store relations at one side or both chunk.getMessages().add(msg); - // DataManager.save(chunk); - TODO conv.getMesssageChunks().add(chunk); DataManager.save(conv); LogManager.getLogger().log(Level.DEBUG,