Organized data, created index.js, fixed IDs...

This commit is contained in:
Norbi Peti 2016-08-05 13:39:31 +02:00
parent 9b83b24fae
commit 334bc54f6a
19 changed files with 215 additions and 125 deletions

View file

@ -8,13 +8,7 @@
<script src="js/register.js"></script>
<meta charset="UTF-8"/>
<link rel="stylesheet" href="css/style.css"/>
<script>
$(document).ready(function () {
var cmsgs = document.getElementById("channelmessages");
if (cmsgs != null && cmsgs.childElementCount > 0)
cmsgs.lastElementChild.scrollIntoView(false);
}); //TODO: Move to an index.js
</script>
<script src="js/index.js"></script>
</head>
<body>
<div id="errormsg">

9
pages/js/index.js Normal file
View file

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

View file

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

View file

@ -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<LoaderCollection<Conversation>>() {
}.getType(), new LoaderCollectionSerializer<Conversation>());
@ -44,44 +45,18 @@ public class Main {
}.getType(), new LoaderRefSerializer<User>());
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");
}

View file

@ -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 <T extends SavedData> 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 extends SavedData> T load(Class<T> cl, long id) {
return loadFromFile(new File(cl.getName() + "-" + id), cl);
return loadFromFile(new File(datafolder, getFileName(cl, id)), cl);
}
public static <T extends SavedData> LoaderCollection<T> load(Class<T> cl) {
String[] filenames = new File(".").list(new FilenameFilter() {
public static <T extends SavedData> LoaderCollection<T> getAll(Class<T> 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<T> rets = new LoaderCollection<T>(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<File, Object> 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 extends SavedData> T loadFromFile(File file, Class<T> 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 <T extends SavedData> 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 <T extends SavedData> boolean remove(Class<T> 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<File, Object> item : cache.entrySet()) {
DataManager.save((SavedData) item.getValue());
}
}
private static HashMap<Class<? extends SavedData>, Long> nextids;
public static Map<Class<? extends SavedData>, Long> getNextIDs() {
return Collections.unmodifiableMap(nextids);
}
public static void setNextID(Class<? extends SavedData> cl, Long id) {
nextids.put(cl, id);
}
@SuppressWarnings("unchecked")
private static HashMap<Class<? extends SavedData>, 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<>();
while ((line = reader.readLine()) != null) {
String[] spl = line.split("\\=");
ret.put((Class<? extends SavedData>) Class.forName(packagename + "." + spl[0]), Long.parseLong(spl[1]));
}
return ret;
} catch (Exception e) {
e.printStackTrace();
}
return new HashMap<>();
}
private static void saveNextIDs(HashMap<Class<? extends SavedData>, Long> ids) {
try {
File file = new File("data", "idlist.ini");
String contents = "";
for (Entry<Class<? extends SavedData>, 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 <T extends SavedData> String getFileName(Class<T> cl, Long id) {
if (id != null)
return cl.getSimpleName() + "-" + id + ".json";
else
return cl.getSimpleName() + "-";
}
}

View file

@ -86,8 +86,6 @@ public class LoaderCollection<T extends SavedData> implements List<T>, 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<T extends SavedData> implements List<T>, Serializa
@Override
public List<T> subList(int fromIndex, int toIndex) {
// TODO Auto-generated method stub
return new LoaderCollection<T>(this, fromIndex, toIndex);
}

View file

@ -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<T extends SavedData> extends TypeAdapter<LoaderCollection<T>> {
@Override
public void write(JsonWriter out, LoaderCollection<T> 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<List<Long>>() {
}.getType(), out);
out.name("class").value(value.cl.getName());
out.name("class").value(value.cl.getSimpleName());
out.endObject();
}
@SuppressWarnings("unchecked")
@Override
public LoaderCollection<T> read(JsonReader in) throws IOException {
if (in.peek().equals(JsonToken.NULL)) {
in.nextNull();
return null;
}
in.beginObject();
in.nextName();
List<Long> list = new Gson().fromJson(in, new TypeToken<List<Long>>() {
@ -37,12 +46,12 @@ public class LoaderCollectionSerializer<T extends SavedData> extends TypeAdapter
}
Class<T> cl;
try {
cl = (Class<T>) Class.forName(in.nextString());
cl = (Class<T>) Class.forName(DataManager.getPackageName() + "." + in.nextString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
LoaderCollection<T> col = new LoaderCollection<T>(cl); // TODO
LoaderCollection<T> col = new LoaderCollection<T>(cl);
col.idlist.addAll(list);
in.endObject();
return col;

View file

@ -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<T extends SavedData> extends TypeAdapter<LoaderRef<T>> {
@Override
public void write(JsonWriter out, LoaderRef<T> 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<T extends SavedData> extends TypeAdapter<Loader
@SuppressWarnings("unchecked")
@Override
public LoaderRef<T> 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<T extends SavedData> extends TypeAdapter<Loader
}
Class<T> cl;
try {
cl = (Class<T>) Class.forName(in.nextString());
cl = (Class<T>) Class.forName(DataManager.getPackageName() + "." + in.nextString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
LoaderRef<T> col = new LoaderRef<T>(cl, id); // TODO
LoaderRef<T> col = new LoaderRef<T>(cl, id);
in.endObject();
return col;
}

View file

@ -50,4 +50,7 @@ public class Conversation extends SavedData {
public void setId(long id) {
this.id = id;
}
private Conversation() {
}
}

View file

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

View file

@ -42,4 +42,7 @@ public class MessageChunk extends SavedData {
public void setId(long id) {
this.id = id;
}
private MessageChunk() {
}
}

View file

@ -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 extends SavedData> T create(Class<T> cl) {
T obj;
try {
Constructor<T> 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;
}
}

View file

@ -93,11 +93,11 @@ public class User extends SavedData {
return conversations;
}
public User() {
private User() {
}
public static LoaderCollection<User> getUsers() {
return DataManager.load(User.class);
return DataManager.getAll(User.class);
}
@Override

View file

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

View file

@ -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("<username />", 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<Conversation> 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() {

View file

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

View file

@ -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, "<p>Please log in to send messages</p>", exchange);
return; // TODO: Fix sending messages
return;
}
JsonObject obj = IOHelper.GetPOSTJSON(exchange);
if (obj == null) {
/*
* IOHelper.SendResponse(400,
* "<h1>400 Bad request</h1><p>Not a JSON string!</p><p>" +
* IOHelper.GetPOST(exchange) + "</p>", exchange);
* IOHelper.SendResponse(400, "<h1>400 Bad request</h1><p>Not a JSON string!</p><p>" + IOHelper.GetPOST(exchange) + "</p>", exchange);
*/
IOHelper.SendResponse(400, "JSONERROR", exchange);
return;
@ -67,16 +66,14 @@ public class ReceiveMessageAjaxPage extends Page {
+ conversation + " is not found.</p>", 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,

View file

@ -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 += "<p>An user with this name already exists</p>";
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/

View file

@ -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, "<p>Please log in to send messages</p>", exchange);
return; // TODO: Fix sending messages
return;
}
JsonObject obj = IOHelper.GetPOSTJSON(exchange);
if (obj == null) {
/*
* IOHelper.SendResponse(400,
* "<h1>400 Bad request</h1><p>Not a JSON string!</p><p>" +
* IOHelper.GetPOST(exchange) + "</p>", exchange);
*/
IOHelper.SendResponse(400, "JSONERROR", exchange);
IOHelper.SendResponse(400,
"<h1>400 Bad request</h1><p>Not a JSON string!</p><p>" + IOHelper.GetPOST(exchange) + "</p>",
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.</p>", 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,