From 0f54d6ddb80e775f0f26ac5d262536067fe7277c Mon Sep 17 00:00:00 2001 From: NorbiPeti Date: Thu, 4 Aug 2016 15:10:46 +0200 Subject: [PATCH] Added Cookie(s) classes and did fixes --- pages/index.html | 6 +- pages/js/message.js | 4 +- src/io/github/norbipeti/chat/server/Main.java | 1 - .../chat/server/data/DataManager.java | 6 +- .../chat/server/data/LoaderRefSerializer.java | 4 -- .../chat/server/db/domain/Conversation.java | 17 +++-- .../chat/server/db/domain/MessageChunk.java | 12 ++++ .../chat/server/db/domain/SavedData.java | 12 +--- .../norbipeti/chat/server/db/domain/User.java | 16 +++-- .../norbipeti/chat/server/io/Cookie.java | 32 +++++++++ .../norbipeti/chat/server/io/Cookies.java | 61 ++++++++++++++++ .../norbipeti/chat/server/io/IOHelper.java | 71 ++++++++++++------- .../chat/server/page/LoginAjaxPage.java | 2 +- .../chat/server/page/SendMessageAjaxPage.java | 2 +- 14 files changed, 189 insertions(+), 57 deletions(-) create mode 100644 src/io/github/norbipeti/chat/server/io/Cookie.java create mode 100644 src/io/github/norbipeti/chat/server/io/Cookies.java diff --git a/pages/index.html b/pages/index.html index a03ab85..64460ec 100644 --- a/pages/index.html +++ b/pages/index.html @@ -10,8 +10,10 @@ diff --git a/pages/js/message.js b/pages/js/message.js index 5b26814..eee0559 100644 --- a/pages/js/message.js +++ b/pages/js/message.js @@ -16,12 +16,12 @@ var respfunc = function respfunc(result) { else { var errormsg = document.getElementById("errormsg"); errormsg.innerHTML = result.responseText; - errormsg.style = "display: block"; + errormsg.style = "display: block"; //TODO: Hide errormsg after a while (index.js) msginput.disabled = false; } } else - location.reload(true); + location.reload(true); //TODO: Don't referesh on message send }; var sendmsgonenter = function sendmsgonenter(e) { diff --git a/src/io/github/norbipeti/chat/server/Main.java b/src/io/github/norbipeti/chat/server/Main.java index dd0c6a5..1c2fde9 100644 --- a/src/io/github/norbipeti/chat/server/Main.java +++ b/src/io/github/norbipeti/chat/server/Main.java @@ -3,7 +3,6 @@ package io.github.norbipeti.chat.server; import java.lang.reflect.Modifier; import java.net.InetAddress; import java.net.InetSocketAddress; -import java.util.Date; import java.util.Set; import org.apache.logging.log4j.Level; diff --git a/src/io/github/norbipeti/chat/server/data/DataManager.java b/src/io/github/norbipeti/chat/server/data/DataManager.java index 83e5448..6be0cdb 100644 --- a/src/io/github/norbipeti/chat/server/data/DataManager.java +++ b/src/io/github/norbipeti/chat/server/data/DataManager.java @@ -18,8 +18,10 @@ public final class DataManager { public static void save(T object) { try { - Files.write(Main.gson.toJson(object), new File(object.getClass().getName() + "-" + object.getId()), - StandardCharsets.UTF_8); + File file = new File(object.getClass().getName() + "-" + object.getId()); + while (file.exists()) + object.setId(object.getId() + 1); + Files.write(Main.gson.toJson(object), file, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java b/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java index d11353c..8a3e0c1 100644 --- a/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java +++ b/src/io/github/norbipeti/chat/server/data/LoaderRefSerializer.java @@ -1,11 +1,7 @@ package io.github.norbipeti.chat.server.data; import java.io.IOException; -import java.util.List; - -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.JsonWriter; 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 a01d60a..38d73b5 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/Conversation.java +++ b/src/io/github/norbipeti/chat/server/db/domain/Conversation.java @@ -8,10 +8,11 @@ import io.github.norbipeti.chat.server.data.LoaderCollection; @Table(name = "CONVERSATION") public class Conversation extends SavedData { private static final long serialVersionUID = 5058682475353799722L; + private static Long nextid = 0L; // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "ID", unique = true, nullable = false) - // private Long id; + private Long id = nextid++; @ElementCollection(fetch = FetchType.EAGER) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "conversation") private LoaderCollection messsagechunks = new LoaderCollection<>(MessageChunk.class); @@ -40,9 +41,13 @@ public class Conversation extends SavedData { return users; } - /* - * public Long getId() { return id; } - * - * public void setId(Long id) { this.id = id; } - */ + @Override + public long getId() { + return id; + } + + @Override + 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 4457577..cf4d4bc 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java +++ b/src/io/github/norbipeti/chat/server/db/domain/MessageChunk.java @@ -7,6 +7,8 @@ import io.github.norbipeti.chat.server.data.LoaderRef; public class MessageChunk extends SavedData { private static final long serialVersionUID = -1665300779209348467L; + private static Long nextid = 0L; + private Long id = nextid++; private List messages = new ArrayList<>(); private LoaderRef conversation; @@ -30,4 +32,14 @@ public class MessageChunk extends SavedData { public void setConversation(Conversation conversation) { this.conversation = new LoaderRef(conversation); } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } } 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 b90ecc5..e6344e4 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/SavedData.java +++ b/src/io/github/norbipeti/chat/server/db/domain/SavedData.java @@ -4,15 +4,7 @@ import java.io.Serializable; @SuppressWarnings("serial") public abstract class SavedData implements Serializable { - private static long nextID = 0; + public abstract long getId(); - private long id; - - public long getId() { - return id; - } - - protected SavedData() { - id = nextID++; - } + public abstract void setId(long id); } 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 5221b71..8cfdff0 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/User.java +++ b/src/io/github/norbipeti/chat/server/db/domain/User.java @@ -11,10 +11,8 @@ import io.github.norbipeti.chat.server.data.LoaderCollection; @Table(name = "\"USER\"") public class User extends SavedData { private static final long serialVersionUID = 2862762084164225666L; - // @Id - // @GeneratedValue(strategy = GenerationType.IDENTITY) - // @Column(name = "ID", unique = true, nullable = false) - // private Long id; + private static Long nextid = 0L; + private Long id = nextid++; private String name; private String email; private String password; @@ -101,4 +99,14 @@ public class User extends SavedData { public static LoaderCollection getUsers() { return DataManager.load(User.class); } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } } diff --git a/src/io/github/norbipeti/chat/server/io/Cookie.java b/src/io/github/norbipeti/chat/server/io/Cookie.java new file mode 100644 index 0000000..7de81d6 --- /dev/null +++ b/src/io/github/norbipeti/chat/server/io/Cookie.java @@ -0,0 +1,32 @@ +package io.github.norbipeti.chat.server.io; + +public class Cookie { + private String name; + private String value; + + public Cookie(String name, String value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public String toString() { + return "Cookie [name=" + name + ", value=" + value + "]"; + } +} diff --git a/src/io/github/norbipeti/chat/server/io/Cookies.java b/src/io/github/norbipeti/chat/server/io/Cookies.java new file mode 100644 index 0000000..a7fdefe --- /dev/null +++ b/src/io/github/norbipeti/chat/server/io/Cookies.java @@ -0,0 +1,61 @@ +package io.github.norbipeti.chat.server.io; + +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 com.sun.net.httpserver.HttpExchange; + +public class Cookies extends HashMap { + private static final long serialVersionUID = -328053564170765287L; + + private String expiretime; + + public Cookies(int addyears) { + super(); + this.expiretime = ZonedDateTime.now(ZoneId.of("GMT")).plus(Period.of(addyears, 0, 0)) + .format(DateTimeFormatter.RFC_1123_DATE_TIME); + } + + public Cookies(String expiretime) { + super(); + this.expiretime = expiretime; + } + + public Cookies() { + super(); + this.expiretime = ZonedDateTime.now(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME); + } + + public void SendHeaders(HttpExchange exchange) { + for (Entry item : entrySet()) + exchange.getResponseHeaders().add("Set-Cookie", + item.getKey() + "=" + item.getValue().getValue() + "; expires=" + expiretime); + exchange.getResponseHeaders().add("Set-Cookie", "expiretime=" + expiretime + "; expires=" + expiretime); + } + + public Cookies add(Cookie cookie) { + this.put(cookie.getName(), cookie); + return this; + } + + public String getExpireTime() { + return expiretime; + } + + public ZonedDateTime getExpireTimeParsed() { + return ZonedDateTime.parse(expiretime, DateTimeFormatter.RFC_1123_DATE_TIME); + } + + public void setExpireTime(LocalDateTime expiretime) { + this.expiretime = expiretime.format(DateTimeFormatter.RFC_1123_DATE_TIME); + } + + @Override + public String toString() { + return "Cookies [expiretime=" + expiretime + ", " + super.toString() + "]"; + } +} diff --git a/src/io/github/norbipeti/chat/server/io/IOHelper.java b/src/io/github/norbipeti/chat/server/io/IOHelper.java index 12f45c3..b6ffa5e 100644 --- a/src/io/github/norbipeti/chat/server/io/IOHelper.java +++ b/src/io/github/norbipeti/chat/server/io/IOHelper.java @@ -7,11 +7,14 @@ 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; import java.util.UUID; import java.util.function.Function; @@ -67,11 +70,22 @@ public class IOHelper { return content; } - public static HashMap GetPOST(HttpExchange exchange) throws IOException { - if (exchange.getRequestBody().available() == 0) - return new HashMap<>(); + public static String GetPOST(HttpExchange exchange) { try { - String[] content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1).split("\\&"); + if (exchange.getRequestBody().available() == 0) + return ""; + String content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1); + return content; + } catch (Exception e) { + e.printStackTrace(); + return ""; + } + } + + @Deprecated + public static HashMap GetPOSTKeyValues(HttpExchange exchange) { + try { + String[] content = GetPOST(exchange).split("\\&"); HashMap vars = new HashMap<>(); for (String var : content) { String[] spl = var.split("\\="); @@ -87,11 +101,9 @@ public class IOHelper { } } - public static JsonObject GetPOSTJSON(HttpExchange exchange) throws IOException { - if (exchange.getRequestBody().available() == 0) - return null; + public static JsonObject GetPOSTJSON(HttpExchange exchange) { try { - String content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1); + String content = GetPOST(exchange); JsonObject obj = new JsonParser().parse(content).getAsJsonObject(); return obj; } catch (Exception e) { @@ -122,11 +134,8 @@ public class IOHelper { // provider.SetValues(() -> // user.setSessionid(UUID.randomUUID().toString())); user.setSessionid(UUID.randomUUID().toString()); - ZonedDateTime expiretime = ZonedDateTime.now(ZoneId.of("GMT")).plus(Period.of(2, 0, 0)); - exchange.getResponseHeaders().add("Set-Cookie", - "user_id=" + user.getId() + "; expires=" + expiretime.format(DateTimeFormatter.RFC_1123_DATE_TIME)); - exchange.getResponseHeaders().add("Set-Cookie", "session_id=" + user.getSessionid() + "; expires=" - + expiretime.format(DateTimeFormatter.RFC_1123_DATE_TIME)); + new Cookies(2).add(new Cookie("user_id", user.getId() + "")).add(new Cookie("session_id", user.getSessionid())) + .SendHeaders(exchange); } public static void LogoutUser(HttpExchange exchange, User user) { @@ -136,8 +145,8 @@ public class IOHelper { private static void SendLogoutHeaders(HttpExchange exchange) { String expiretime = "Sat, 19 Mar 2016 23:33:00 GMT"; - exchange.getResponseHeaders().add("Set-Cookie", "user_id=del; expires=" + expiretime); - exchange.getResponseHeaders().add("Set-Cookie", "session_id=del; expires=" + expiretime); + new Cookies(expiretime).add(new Cookie("user_id", "del")).add(new Cookie("session_id", "del")) + .SendHeaders(exchange); } public static void Redirect(String url, HttpExchange exchange) throws IOException { @@ -145,10 +154,10 @@ public class IOHelper { IOHelper.SendResponse(303, "If you can see this, click here to continue", exchange); } - public static HashMap GetCookies(HttpExchange exchange) { + public static Cookies GetCookies(HttpExchange exchange) { if (!exchange.getRequestHeaders().containsKey("Cookie")) - return new HashMap<>(); - HashMap map = new HashMap<>(); + return new Cookies(); + Map map = new HashMap<>(); for (String cheader : exchange.getRequestHeaders().get("Cookie")) { String[] spl = cheader.split("\\;\\s*"); for (String s : spl) { @@ -158,25 +167,39 @@ public class IOHelper { map.put(kv[0], kv[1]); } } - return map; + if (!map.containsKey("expiretime")) + return new Cookies(); + Cookies cookies = null; + try { + cookies = new Cookies(map.get("expiretime")); + for (Entry item : map.entrySet()) + if (!item.getKey().equalsIgnoreCase("expiretime")) + cookies.put(item.getKey(), new Cookie(item.getKey(), item.getValue())); + } catch (Exception e) { + return new Cookies(); + } + return cookies; } /** * Get logged in user. It may also send logout headers if the cookies are - * invalid. + * invalid, or login headers to keep the user logged in. * * @param exchange * @return The logged in user or null if not logged in. * @throws IOException */ public static User GetLoggedInUser(HttpExchange exchange) throws IOException { - HashMap cookies = GetCookies(exchange); + 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"))); - if (user != null && cookies.get("session_id") != null && cookies.get("session_id").equals(user.getSessionid())) + User user = DataManager.load(User.class, Long.parseLong(cookies.get("user_id").getValue())); + 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")))) + LoginUser(exchange, user); return user; - else + } else SendLogoutHeaders(exchange); return null; } diff --git a/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java b/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java index 3f656cc..7418a08 100644 --- a/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/LoginAjaxPage.java @@ -21,7 +21,7 @@ public class LoginAjaxPage extends Page { } User loginuser = null; for (User user : DataManager.load(User.class)) { - if (user.getEmail().equals(post.get("email"))) { + if (user.getEmail().equals(post.get("email").getAsString())) { loginuser = user; break; } diff --git a/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java b/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java index ac82126..afbb3c4 100644 --- a/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/SendMessageAjaxPage.java @@ -76,7 +76,7 @@ public class SendMessageAjaxPage extends Page { msg.setMessageChunk(chunk); // TODO: Store relations at one side or // both); chunk.getMessages().add(msg); - //DataManager.save(chunk); - TODO + // DataManager.save(chunk); - TODO conv.getMesssageChunks().add(chunk); DataManager.save(conv); LogManager.getLogger().log(Level.DEBUG,