From e12c0fee36e75a382051d4b701232a6121dd19b3 Mon Sep 17 00:00:00 2001 From: NorbiPeti Date: Fri, 12 Aug 2016 12:09:23 +0200 Subject: [PATCH] Fixes and improvements - Fixed automatic creation of users with a wrong cookie - Fixed message chunk creation - Fixed JS --- pages/js/sendmessage.js | 4 +-- src/io/github/norbipeti/chat/server/Main.java | 14 ++++---- .../chat/server/data/DataManager.java | 31 ++++++++++------- .../chat/server/data/LoaderCollection.java | 34 +++++++++---------- .../chat/server/data/LoaderIterator.java | 6 ++-- .../chat/server/data/LoaderListIterator.java | 8 ++--- .../norbipeti/chat/server/data/LoaderRef.java | 6 ++-- .../chat/server/db/domain/ManagedData.java | 3 +- .../chat/server/db/domain/Message.java | 5 ++- .../chat/server/db/domain/MessageChunk.java | 1 - .../norbipeti/chat/server/io/IOHelper.java | 8 +++-- .../norbipeti/chat/server/page/IndexPage.java | 2 +- .../server/page/ReceiveMessageAjaxPage.java | 10 ------ .../chat/server/page/SendMessageAjaxPage.java | 2 -- 14 files changed, 64 insertions(+), 70 deletions(-) diff --git a/pages/js/sendmessage.js b/pages/js/sendmessage.js index d9165cb..67d55d9 100644 --- a/pages/js/sendmessage.js +++ b/pages/js/sendmessage.js @@ -1,5 +1,5 @@ var sendmsg = function sendmsg(msginputta) { - window.jsonobj = JSON.stringify({"message": msginputta.value, "conversation": window.convid}); + window.jsonobj = JSON.stringify({ "message": msginputta.value, "conversation": window.convid }); console.log(window.jsonobj); $.ajax({ url: "/sendmessage", data: window.jsonobj, method: "POST", success: respfunc, error: respfunc @@ -15,7 +15,7 @@ var respfunc = function respfunc(result) { sendmsg(msginput); } else { - showError. + showError(result.responseText); msginput.disabled = false; } } diff --git a/src/io/github/norbipeti/chat/server/Main.java b/src/io/github/norbipeti/chat/server/Main.java index 854a730..ff2cb51 100644 --- a/src/io/github/norbipeti/chat/server/Main.java +++ b/src/io/github/norbipeti/chat/server/Main.java @@ -20,7 +20,6 @@ import io.github.norbipeti.chat.server.db.domain.*; import io.github.norbipeti.chat.server.io.DataType; import io.github.norbipeti.chat.server.page.*; import io.vertx.core.Vertx; -import io.vertx.core.http.HttpServerOptions; public class Main { public static Gson gson; @@ -77,17 +76,16 @@ public class Main { } } server.start(); - LogManager.getLogger().info("Starting websocket server..."); - Vertx vertx = Vertx.vertx(); - io.vertx.core.http.HttpServer socketserver = vertx.createHttpServer(); - socketserver.websocketHandler(websocket -> { - websocket.writeFinalTextFrame("Hello"); // TODO - }); - socketserver.listen(8180); + /* + * LogManager.getLogger().info("Starting websocket server..."); Vertx vertx = Vertx.vertx(); io.vertx.core.http.HttpServer socketserver = vertx.createHttpServer(); + * socketserver.websocketHandler(websocket -> { websocket.writeFinalTextFrame("Hello"); // TODO }); socketserver.listen(8180); + */ LogManager.getLogger().log(Level.INFO, "Ready... Press Enter to stop."); System.in.read(); LogManager.getLogger().log(Level.INFO, "Stopping..."); server.stop(1); + // socketserver.close(); + // vertx.close(); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/io/github/norbipeti/chat/server/data/DataManager.java b/src/io/github/norbipeti/chat/server/data/DataManager.java index 627a040..b854e25 100644 --- a/src/io/github/norbipeti/chat/server/data/DataManager.java +++ b/src/io/github/norbipeti/chat/server/data/DataManager.java @@ -12,6 +12,7 @@ import java.util.Map.Entry; import com.google.common.io.Files; import io.github.norbipeti.chat.server.Main; +import io.github.norbipeti.chat.server.db.domain.ManagedData; import io.github.norbipeti.chat.server.db.domain.SavedData; public final class DataManager { @@ -30,8 +31,8 @@ public final class DataManager { } } - public static T load(Class cl, long id) { - return loadFromFile(new File(datafolder, getFileName(cl, id)), cl); + public static T load(Class cl, long id, boolean create) { + return loadFromFile(new File(datafolder, getFileName(cl, id)), cl, create); } public static LoaderCollection getAll(Class cl) { @@ -59,11 +60,14 @@ public final class DataManager { // TODO: Handle unloading of used objects (prevent detached objects) @SuppressWarnings("unchecked") - private static T loadFromFile(File file, Class cl) { + private static T loadFromFile(File file, Class cl, boolean create) { try { if (!file.exists()) { - T obj = SavedData.create(cl); - return obj; + if (create) { + T obj = SavedData.create(cl); + return obj; + } else + return null; } if (cache.containsKey(file)) return (T) cache.get(file); @@ -112,28 +116,29 @@ public final class DataManager { } } - private static HashMap, Long> nextids; + private static HashMap, Long> nextids; - public static Map, Long> getNextIDs() { + public static Map, Long> getNextIDs() { return Collections.unmodifiableMap(nextids); } - public static void setNextID(Class cl, Long id) { + public static void setNextID(Class cl, Long id) { nextids.put(cl, id); } @SuppressWarnings("unchecked") - private static HashMap, Long> loadNextIDs() { + 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<>(); + 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])); + ret.put((Class) Class.forName(packagename + "." + spl[0]), + Long.parseLong(spl[1])); } return ret; } catch (Exception e) { @@ -142,11 +147,11 @@ public final class DataManager { return new HashMap<>(); } - private static void saveNextIDs(HashMap, Long> ids) { + private static void saveNextIDs(HashMap, Long> ids) { try { File file = new File("data", "idlist.ini"); String contents = ""; - for (Entry, Long> item : ids.entrySet()) { + for (Entry, Long> item : ids.entrySet()) { contents += item.getKey().getSimpleName() + "=" + item.getValue() + "\n"; } Files.write(contents, file, StandardCharsets.UTF_8); diff --git a/src/io/github/norbipeti/chat/server/data/LoaderCollection.java b/src/io/github/norbipeti/chat/server/data/LoaderCollection.java index f7859f6..c43b032 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderCollection.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderCollection.java @@ -7,7 +7,7 @@ import java.util.List; import java.util.ListIterator; import java.util.stream.Collectors; -import io.github.norbipeti.chat.server.db.domain.ManagedData; +import io.github.norbipeti.chat.server.db.domain.SavedData; /** *

@@ -21,7 +21,7 @@ import io.github.norbipeti.chat.server.db.domain.ManagedData; * * @param */ -public class LoaderCollection extends Loader implements List { +public class LoaderCollection extends Loader implements List { private static final long serialVersionUID = 5426152406394894301L; List idlist; Class cl; @@ -69,7 +69,7 @@ public class LoaderCollection extends Loader implements L @Override public boolean addAll(Collection c) { return idlist.addAll(c.stream().map((data) -> { - ManagedData cde = ((ManagedData) data); + SavedData cde = ((SavedData) data); DataManager.save(cde); return cde.getId(); }).collect(Collectors.toList())); @@ -78,7 +78,7 @@ public class LoaderCollection extends Loader implements L @Override public boolean addAll(int index, Collection c) { return idlist.addAll(index, c.stream().map((data) -> { - ManagedData cde = ((ManagedData) data); + SavedData cde = ((SavedData) data); DataManager.save(cde); return cde.getId(); }).collect(Collectors.toList())); @@ -101,7 +101,7 @@ public class LoaderCollection extends Loader implements L @Override public T get(int index) { - return DataManager.load(cl, idlist.get(index)); + return DataManager.load(cl, idlist.get(index), true); } @Override @@ -137,9 +137,9 @@ public class LoaderCollection extends Loader implements L */ @Override public boolean remove(Object o) { - if (ManagedData.class.isAssignableFrom(o.getClass())) { - DataManager.remove((ManagedData) o); - return idlist.remove(((ManagedData) o).getId()); + if (SavedData.class.isAssignableFrom(o.getClass())) { + DataManager.remove((SavedData) o); + return idlist.remove(((SavedData) o).getId()); } if (Long.class.isAssignableFrom(o.getClass())) DataManager.remove(cl, (Long) o); @@ -148,15 +148,15 @@ public class LoaderCollection extends Loader implements L @Override public T remove(int index) { - return DataManager.load(cl, idlist.remove(index)); + return DataManager.load(cl, idlist.remove(index), true); } @Override public boolean removeAll(Collection c) { boolean success = false; for (Object item : c) { - if (ManagedData.class.isAssignableFrom(item.getClass())) { - if (idlist.remove(((ManagedData) item).getId())) { + if (SavedData.class.isAssignableFrom(item.getClass())) { + if (idlist.remove(((SavedData) item).getId())) { success = true; break; } @@ -174,8 +174,8 @@ public class LoaderCollection extends Loader implements L public boolean retainAll(Collection c) { List list = new ArrayList(); for (Object item : c) { - if (ManagedData.class.isAssignableFrom(item.getClass())) { - list.add(((ManagedData) item).getId()); + if (SavedData.class.isAssignableFrom(item.getClass())) { + list.add(((SavedData) item).getId()); } else if (Long.class.isAssignableFrom(item.getClass())) { list.add((Long) item); } @@ -185,7 +185,7 @@ public class LoaderCollection extends Loader implements L @Override public T set(int index, T element) { - return DataManager.load(cl, idlist.set(index, element.getId())); + return DataManager.load(cl, idlist.set(index, element.getId()), true); } @Override @@ -201,14 +201,14 @@ public class LoaderCollection extends Loader implements L @Override public Object[] toArray() { return idlist.stream().map((data) -> { - return DataManager.load(cl, data); + return DataManager.load(cl, data, true); }).collect(Collectors.toList()).toArray(); } @Override public U[] toArray(U[] a) { return idlist.stream().map((data) -> { - return DataManager.load(cl, data); + return DataManager.load(cl, data, true); }).collect(Collectors.toList()).toArray(a); } @@ -221,7 +221,7 @@ public class LoaderCollection extends Loader implements L StringBuilder sb = new StringBuilder("["); for (Long item : idlist) { if (loaditems) - sb.append(DataManager.load(cl, item)); + sb.append(DataManager.load(cl, item, true)); else sb.append(item); } diff --git a/src/io/github/norbipeti/chat/server/data/LoaderIterator.java b/src/io/github/norbipeti/chat/server/data/LoaderIterator.java index eb6148a..63ac619 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderIterator.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderIterator.java @@ -1,9 +1,9 @@ package io.github.norbipeti.chat.server.data; import java.util.Iterator; -import io.github.norbipeti.chat.server.db.domain.ManagedData; +import io.github.norbipeti.chat.server.db.domain.SavedData; -public final class LoaderIterator implements Iterator { +public final class LoaderIterator implements Iterator { private Iterator iterator; private T lastitem; private Class cl; @@ -20,7 +20,7 @@ public final class LoaderIterator implements Iterator @Override public T next() { - return lastitem = DataManager.load(cl, iterator.next()); + return lastitem = DataManager.load(cl, iterator.next(), true); } @Override diff --git a/src/io/github/norbipeti/chat/server/data/LoaderListIterator.java b/src/io/github/norbipeti/chat/server/data/LoaderListIterator.java index 29449b4..b8a70fc 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderListIterator.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderListIterator.java @@ -2,9 +2,9 @@ package io.github.norbipeti.chat.server.data; import java.util.ListIterator; -import io.github.norbipeti.chat.server.db.domain.ManagedData; +import io.github.norbipeti.chat.server.db.domain.SavedData; -public final class LoaderListIterator implements ListIterator { +public final class LoaderListIterator implements ListIterator { private ListIterator listiterator; private T lastitem; private Class cl; @@ -21,7 +21,7 @@ public final class LoaderListIterator implements ListIter @Override public T next() { - return lastitem = DataManager.load(cl, listiterator.next()); + return lastitem = DataManager.load(cl, listiterator.next(), true); } @Override @@ -49,7 +49,7 @@ public final class LoaderListIterator implements ListIter @Override public T previous() { - return DataManager.load(cl, listiterator.previous()); + return DataManager.load(cl, listiterator.previous(), true); } @Override diff --git a/src/io/github/norbipeti/chat/server/data/LoaderRef.java b/src/io/github/norbipeti/chat/server/data/LoaderRef.java index 0b4a462..e604d90 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderRef.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderRef.java @@ -1,6 +1,6 @@ package io.github.norbipeti.chat.server.data; -import io.github.norbipeti.chat.server.db.domain.ManagedData; +import io.github.norbipeti.chat.server.db.domain.SavedData; /** *

@@ -13,7 +13,7 @@ import io.github.norbipeti.chat.server.db.domain.ManagedData; * @author Norbi * @param The type of the stored object */ -public class LoaderRef extends Loader { +public class LoaderRef extends Loader { private static final long serialVersionUID = 8458570738734235320L; Class cl; Long id; @@ -30,6 +30,6 @@ public class LoaderRef extends Loader { } public T get() { - return DataManager.load(cl, id); + return DataManager.load(cl, id, true); } } diff --git a/src/io/github/norbipeti/chat/server/db/domain/ManagedData.java b/src/io/github/norbipeti/chat/server/db/domain/ManagedData.java index e4a865e..5ddeb02 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/ManagedData.java +++ b/src/io/github/norbipeti/chat/server/db/domain/ManagedData.java @@ -30,7 +30,8 @@ public abstract class ManagedData implements Serializable { obj.setId(DataManager.getNextIDs().getOrDefault(obj.getClass(), 0L)); DataManager.setNextID(obj.getClass(), obj.getId() + 1); obj.init(); - DataManager.save(obj); + if (SavedData.class.isAssignableFrom(cl)) + DataManager.save((SavedData) obj); return obj; } } 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 33bf698..f004e34 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/Message.java +++ b/src/io/github/norbipeti/chat/server/db/domain/Message.java @@ -1,6 +1,5 @@ package io.github.norbipeti.chat.server.db.domain; -import java.io.Serializable; import java.util.Date; import javax.persistence.*; @@ -67,7 +66,6 @@ public class Message extends ManagedData { } private void setConv(Conversation parent) { - Message msg = this; int size = parent.getMesssageChunks().size(); MessageChunk chunk; if (size == 0 || parent.getMesssageChunks().get(size - 1).getMessages().size() >= MESSAGE_LIMIT_PER_CHUNK) { @@ -76,7 +74,8 @@ public class Message extends ManagedData { parent.getMesssageChunks().add(chunk); } else chunk = parent.getMesssageChunks().get(size - 1); - msg.messagechunk = new LoaderRef(chunk); + this.messagechunk = new LoaderRef(chunk); + chunk.getMessages().add(this); } public long getId() { 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 f475313..a5832fb 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java +++ b/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java @@ -11,7 +11,6 @@ public class MessageChunk extends SavedData { private Long id; private List messages = new ArrayList<>(); private LoaderRef conversation; - private Long nextmsgid = 0L; public List getMessages() { return messages; diff --git a/src/io/github/norbipeti/chat/server/io/IOHelper.java b/src/io/github/norbipeti/chat/server/io/IOHelper.java index ead0113..2537993 100644 --- a/src/io/github/norbipeti/chat/server/io/IOHelper.java +++ b/src/io/github/norbipeti/chat/server/io/IOHelper.java @@ -21,6 +21,7 @@ import org.apache.logging.log4j.LogManager; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.net.httpserver.HttpExchange; @@ -100,7 +101,10 @@ public class IOHelper { public static JsonObject GetPOSTJSON(HttpExchange exchange) { try { String content = GetPOST(exchange); - JsonObject obj = new JsonParser().parse(content).getAsJsonObject(); + JsonElement e = new JsonParser().parse(content); + if (e == null) + return null; + JsonObject obj = e.getAsJsonObject(); return obj; } catch (Exception e) { e.printStackTrace(); @@ -189,7 +193,7 @@ public class IOHelper { Cookies cookies = GetCookies(exchange); if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id")) return null; - User user = DataManager.load(User.class, Long.parseLong(cookies.get("user_id").getValue())); + User user = DataManager.load(User.class, Long.parseLong(cookies.get("user_id").getValue()), false); if (user != null && cookies.get("session_id") != null && cookies.get("session_id").getValue().equals(user.getSessionid())) { if (cookies.getExpireTimeParsed().minusYears(1).isBefore(ZonedDateTime.now(ZoneId.of("GMT")))) diff --git a/src/io/github/norbipeti/chat/server/page/IndexPage.java b/src/io/github/norbipeti/chat/server/page/IndexPage.java index 5379298..1937cd5 100644 --- a/src/io/github/norbipeti/chat/server/page/IndexPage.java +++ b/src/io/github/norbipeti/chat/server/page/IndexPage.java @@ -66,7 +66,7 @@ public class IndexPage extends Page { header.appendElement("span").addClass("converttime") .text(isoFormat.format(message.getTime()) + "+00:00"); Element body = msgelement.appendElement("p"); - body.text(message.getMessage()); // TODO: Use JavaScript to convert time + body.text(message.getMessage()); } } return doc; diff --git a/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java b/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java index 2ac0d65..1621354 100644 --- a/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/ReceiveMessageAjaxPage.java @@ -1,19 +1,9 @@ package io.github.norbipeti.chat.server.page; import java.io.IOException; -import java.util.Date; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; import com.google.gson.JsonObject; import com.sun.net.httpserver.HttpExchange; -import io.github.norbipeti.chat.server.Main; -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.ManagedData; import io.github.norbipeti.chat.server.db.domain.User; import io.github.norbipeti.chat.server.io.IOHelper; diff --git a/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java b/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java index c0f701a..c30e74e 100644 --- a/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java @@ -11,7 +11,6 @@ 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.ManagedData; import io.github.norbipeti.chat.server.db.domain.User; import io.github.norbipeti.chat.server.io.IOHelper; @@ -33,7 +32,6 @@ public class SendMessageAjaxPage extends Page { JsonObject obj = IOHelper.GetPOSTJSON(exchange); if (obj == null) { IOHelper.SendResponse(400, "JSONERROR: " + IOHelper.GetPOST(exchange), exchange); - // IOHelper.SendResponse(400, "JSONERROR", exchange); return; } if (!obj.has("message") || !obj.has("conversation")) {