Fixes and improvements

- Fixed automatic creation of users with a wrong cookie
- Fixed message chunk creation
- Fixed JS
This commit is contained in:
Norbi Peti 2016-08-12 12:09:23 +02:00
parent 319a2a9aa1
commit e12c0fee36
14 changed files with 64 additions and 70 deletions

View file

@ -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;
}
}

View file

@ -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();
}

View file

@ -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 extends SavedData> T load(Class<T> cl, long id) {
return loadFromFile(new File(datafolder, getFileName(cl, id)), cl);
public static <T extends SavedData> T load(Class<T> cl, long id, boolean create) {
return loadFromFile(new File(datafolder, getFileName(cl, id)), cl, create);
}
public static <T extends SavedData> LoaderCollection<T> getAll(Class<T> cl) {
@ -59,11 +60,14 @@ public final class DataManager {
// TODO: Handle unloading of used objects (prevent detached objects)
@SuppressWarnings("unchecked")
private static <T extends SavedData> T loadFromFile(File file, Class<T> cl) {
private static <T extends SavedData> T loadFromFile(File file, Class<T> 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<Class<? extends SavedData>, Long> nextids;
private static HashMap<Class<? extends ManagedData>, Long> nextids;
public static Map<Class<? extends SavedData>, Long> getNextIDs() {
public static Map<Class<? extends ManagedData>, Long> getNextIDs() {
return Collections.unmodifiableMap(nextids);
}
public static void setNextID(Class<? extends SavedData> cl, Long id) {
public static void setNextID(Class<? extends ManagedData> cl, Long id) {
nextids.put(cl, id);
}
@SuppressWarnings("unchecked")
private static HashMap<Class<? extends SavedData>, Long> loadNextIDs() {
private static HashMap<Class<? extends ManagedData>, 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<Class<? extends SavedData>, Long> ret = new HashMap<>();
HashMap<Class<? extends ManagedData>, Long> ret = new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] spl = line.split("\\=");
ret.put((Class<? extends SavedData>) Class.forName(packagename + "." + spl[0]), Long.parseLong(spl[1]));
ret.put((Class<? extends ManagedData>) 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<Class<? extends SavedData>, Long> ids) {
private static void saveNextIDs(HashMap<Class<? extends ManagedData>, Long> ids) {
try {
File file = new File("data", "idlist.ini");
String contents = "";
for (Entry<Class<? extends SavedData>, Long> item : ids.entrySet()) {
for (Entry<Class<? extends ManagedData>, Long> item : ids.entrySet()) {
contents += item.getKey().getSimpleName() + "=" + item.getValue() + "\n";
}
Files.write(contents, file, StandardCharsets.UTF_8);

View file

@ -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;
/**
* <p>
@ -21,7 +21,7 @@ import io.github.norbipeti.chat.server.db.domain.ManagedData;
*
* @param <T>
*/
public class LoaderCollection<T extends ManagedData> extends Loader implements List<T> {
public class LoaderCollection<T extends SavedData> extends Loader implements List<T> {
private static final long serialVersionUID = 5426152406394894301L;
List<Long> idlist;
Class<T> cl;
@ -69,7 +69,7 @@ public class LoaderCollection<T extends ManagedData> extends Loader implements L
@Override
public boolean addAll(Collection<? extends T> 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<T extends ManagedData> extends Loader implements L
@Override
public boolean addAll(int index, Collection<? extends T> 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<T extends ManagedData> 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<T extends ManagedData> 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<T extends ManagedData> 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<T extends ManagedData> extends Loader implements L
public boolean retainAll(Collection<?> c) {
List<Long> list = new ArrayList<Long>();
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<T extends ManagedData> 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<T extends ManagedData> 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> 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<T extends ManagedData> 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);
}

View file

@ -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<T extends ManagedData> implements Iterator<T> {
public final class LoaderIterator<T extends SavedData> implements Iterator<T> {
private Iterator<Long> iterator;
private T lastitem;
private Class<T> cl;
@ -20,7 +20,7 @@ public final class LoaderIterator<T extends ManagedData> implements Iterator<T>
@Override
public T next() {
return lastitem = DataManager.load(cl, iterator.next());
return lastitem = DataManager.load(cl, iterator.next(), true);
}
@Override

View file

@ -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<T extends ManagedData> implements ListIterator<T> {
public final class LoaderListIterator<T extends SavedData> implements ListIterator<T> {
private ListIterator<Long> listiterator;
private T lastitem;
private Class<T> cl;
@ -21,7 +21,7 @@ public final class LoaderListIterator<T extends ManagedData> 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<T extends ManagedData> implements ListIter
@Override
public T previous() {
return DataManager.load(cl, listiterator.previous());
return DataManager.load(cl, listiterator.previous(), true);
}
@Override

View file

@ -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;
/**
* <p>
@ -13,7 +13,7 @@ import io.github.norbipeti.chat.server.db.domain.ManagedData;
* @author Norbi
* @param <T> The type of the stored object
*/
public class LoaderRef<T extends ManagedData> extends Loader {
public class LoaderRef<T extends SavedData> extends Loader {
private static final long serialVersionUID = 8458570738734235320L;
Class<T> cl;
Long id;
@ -30,6 +30,6 @@ public class LoaderRef<T extends ManagedData> extends Loader {
}
public T get() {
return DataManager.load(cl, id);
return DataManager.load(cl, id, true);
}
}

View file

@ -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;
}
}

View file

@ -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<MessageChunk>(chunk);
this.messagechunk = new LoaderRef<MessageChunk>(chunk);
chunk.getMessages().add(this);
}
public long getId() {

View file

@ -11,7 +11,6 @@ public class MessageChunk extends SavedData {
private Long id;
private List<Message> messages = new ArrayList<>();
private LoaderRef<Conversation> conversation;
private Long nextmsgid = 0L;
public List<Message> getMessages() {
return messages;

View file

@ -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"))))

View file

@ -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;

View file

@ -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;

View file

@ -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")) {