Added Cookie(s) classes and did fixes

This commit is contained in:
Norbi Peti 2016-08-04 15:10:46 +02:00
parent 2fdd37385c
commit 0f54d6ddb8
14 changed files with 189 additions and 57 deletions

View file

@ -10,8 +10,10 @@
<link rel="stylesheet" href="css/style.css"/> <link rel="stylesheet" href="css/style.css"/>
<script> <script>
$(document).ready(function () { $(document).ready(function () {
document.getElementById("channelmessages").lastElementChild.scrollIntoView(false); var cmsgs = document.getElementById("channelmessages");
}); if (cmsgs.elements.length > 0)
cmsgs.lastElementChild.scrollIntoView(false);
}); //TODO: Move to an index.js
</script> </script>
</head> </head>
<body> <body>

View file

@ -16,12 +16,12 @@ var respfunc = function respfunc(result) {
else { else {
var errormsg = document.getElementById("errormsg"); var errormsg = document.getElementById("errormsg");
errormsg.innerHTML = result.responseText; errormsg.innerHTML = result.responseText;
errormsg.style = "display: block"; errormsg.style = "display: block"; //TODO: Hide errormsg after a while (index.js)
msginput.disabled = false; msginput.disabled = false;
} }
} }
else else
location.reload(true); location.reload(true); //TODO: Don't referesh on message send
}; };
var sendmsgonenter = function sendmsgonenter(e) { var sendmsgonenter = function sendmsgonenter(e) {

View file

@ -3,7 +3,6 @@ package io.github.norbipeti.chat.server;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.Date;
import java.util.Set; import java.util.Set;
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Level;

View file

@ -18,8 +18,10 @@ public final class DataManager {
public static <T extends SavedData> void save(T object) { public static <T extends SavedData> void save(T object) {
try { try {
Files.write(Main.gson.toJson(object), new File(object.getClass().getName() + "-" + object.getId()), File file = new File(object.getClass().getName() + "-" + object.getId());
StandardCharsets.UTF_8); while (file.exists())
object.setId(object.getId() + 1);
Files.write(Main.gson.toJson(object), file, StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }

View file

@ -1,11 +1,7 @@
package io.github.norbipeti.chat.server.data; package io.github.norbipeti.chat.server.data;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;

View file

@ -8,10 +8,11 @@ import io.github.norbipeti.chat.server.data.LoaderCollection;
@Table(name = "CONVERSATION") @Table(name = "CONVERSATION")
public class Conversation extends SavedData { public class Conversation extends SavedData {
private static final long serialVersionUID = 5058682475353799722L; private static final long serialVersionUID = 5058682475353799722L;
private static Long nextid = 0L;
// @Id // @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY) // @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "ID", unique = true, nullable = false) // @Column(name = "ID", unique = true, nullable = false)
// private Long id; private Long id = nextid++;
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "conversation") @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "conversation")
private LoaderCollection<MessageChunk> messsagechunks = new LoaderCollection<>(MessageChunk.class); private LoaderCollection<MessageChunk> messsagechunks = new LoaderCollection<>(MessageChunk.class);
@ -40,9 +41,13 @@ public class Conversation extends SavedData {
return users; return users;
} }
/* @Override
* public Long getId() { return id; } public long getId() {
* return id;
* public void setId(Long id) { this.id = id; } }
*/
@Override
public void setId(long id) {
this.id = id;
}
} }

View file

@ -7,6 +7,8 @@ import io.github.norbipeti.chat.server.data.LoaderRef;
public class MessageChunk extends SavedData { public class MessageChunk extends SavedData {
private static final long serialVersionUID = -1665300779209348467L; private static final long serialVersionUID = -1665300779209348467L;
private static Long nextid = 0L;
private Long id = nextid++;
private List<Message> messages = new ArrayList<>(); private List<Message> messages = new ArrayList<>();
private LoaderRef<Conversation> conversation; private LoaderRef<Conversation> conversation;
@ -30,4 +32,14 @@ public class MessageChunk extends SavedData {
public void setConversation(Conversation conversation) { public void setConversation(Conversation conversation) {
this.conversation = new LoaderRef<Conversation>(conversation); this.conversation = new LoaderRef<Conversation>(conversation);
} }
@Override
public long getId() {
return id;
}
@Override
public void setId(long id) {
this.id = id;
}
} }

View file

@ -4,15 +4,7 @@ import java.io.Serializable;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public abstract class SavedData implements Serializable { public abstract class SavedData implements Serializable {
private static long nextID = 0; public abstract long getId();
private long id; public abstract void setId(long id);
public long getId() {
return id;
}
protected SavedData() {
id = nextID++;
}
} }

View file

@ -11,10 +11,8 @@ import io.github.norbipeti.chat.server.data.LoaderCollection;
@Table(name = "\"USER\"") @Table(name = "\"USER\"")
public class User extends SavedData { public class User extends SavedData {
private static final long serialVersionUID = 2862762084164225666L; private static final long serialVersionUID = 2862762084164225666L;
// @Id private static Long nextid = 0L;
// @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id = nextid++;
// @Column(name = "ID", unique = true, nullable = false)
// private Long id;
private String name; private String name;
private String email; private String email;
private String password; private String password;
@ -101,4 +99,14 @@ public class User extends SavedData {
public static LoaderCollection<User> getUsers() { public static LoaderCollection<User> getUsers() {
return DataManager.load(User.class); return DataManager.load(User.class);
} }
@Override
public long getId() {
return id;
}
@Override
public void setId(long id) {
this.id = id;
}
} }

View file

@ -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 + "]";
}
}

View file

@ -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<String, Cookie> {
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<String, Cookie> 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() + "]";
}
}

View file

@ -7,11 +7,14 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.Period; import java.time.Period;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID; import java.util.UUID;
import java.util.function.Function; import java.util.function.Function;
@ -67,11 +70,22 @@ public class IOHelper {
return content; return content;
} }
public static HashMap<String, String> GetPOST(HttpExchange exchange) throws IOException { public static String GetPOST(HttpExchange exchange) {
if (exchange.getRequestBody().available() == 0)
return new HashMap<>();
try { 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<String, String> GetPOSTKeyValues(HttpExchange exchange) {
try {
String[] content = GetPOST(exchange).split("\\&");
HashMap<String, String> vars = new HashMap<>(); HashMap<String, String> vars = new HashMap<>();
for (String var : content) { for (String var : content) {
String[] spl = var.split("\\="); String[] spl = var.split("\\=");
@ -87,11 +101,9 @@ public class IOHelper {
} }
} }
public static JsonObject GetPOSTJSON(HttpExchange exchange) throws IOException { public static JsonObject GetPOSTJSON(HttpExchange exchange) {
if (exchange.getRequestBody().available() == 0)
return null;
try { try {
String content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1); String content = GetPOST(exchange);
JsonObject obj = new JsonParser().parse(content).getAsJsonObject(); JsonObject obj = new JsonParser().parse(content).getAsJsonObject();
return obj; return obj;
} catch (Exception e) { } catch (Exception e) {
@ -122,11 +134,8 @@ public class IOHelper {
// provider.SetValues(() -> // provider.SetValues(() ->
// user.setSessionid(UUID.randomUUID().toString())); // user.setSessionid(UUID.randomUUID().toString()));
user.setSessionid(UUID.randomUUID().toString()); user.setSessionid(UUID.randomUUID().toString());
ZonedDateTime expiretime = ZonedDateTime.now(ZoneId.of("GMT")).plus(Period.of(2, 0, 0)); new Cookies(2).add(new Cookie("user_id", user.getId() + "")).add(new Cookie("session_id", user.getSessionid()))
exchange.getResponseHeaders().add("Set-Cookie", .SendHeaders(exchange);
"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));
} }
public static void LogoutUser(HttpExchange exchange, User user) { public static void LogoutUser(HttpExchange exchange, User user) {
@ -136,8 +145,8 @@ public class IOHelper {
private static void SendLogoutHeaders(HttpExchange exchange) { private static void SendLogoutHeaders(HttpExchange exchange) {
String expiretime = "Sat, 19 Mar 2016 23:33:00 GMT"; String expiretime = "Sat, 19 Mar 2016 23:33:00 GMT";
exchange.getResponseHeaders().add("Set-Cookie", "user_id=del; expires=" + expiretime); new Cookies(expiretime).add(new Cookie("user_id", "del")).add(new Cookie("session_id", "del"))
exchange.getResponseHeaders().add("Set-Cookie", "session_id=del; expires=" + expiretime); .SendHeaders(exchange);
} }
public static void Redirect(String url, HttpExchange exchange) throws IOException { public static void Redirect(String url, HttpExchange exchange) throws IOException {
@ -145,10 +154,10 @@ public class IOHelper {
IOHelper.SendResponse(303, "<a href=\"" + url + "\">If you can see this, click here to continue</a>", exchange); IOHelper.SendResponse(303, "<a href=\"" + url + "\">If you can see this, click here to continue</a>", exchange);
} }
public static HashMap<String, String> GetCookies(HttpExchange exchange) { public static Cookies GetCookies(HttpExchange exchange) {
if (!exchange.getRequestHeaders().containsKey("Cookie")) if (!exchange.getRequestHeaders().containsKey("Cookie"))
return new HashMap<>(); return new Cookies();
HashMap<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
for (String cheader : exchange.getRequestHeaders().get("Cookie")) { for (String cheader : exchange.getRequestHeaders().get("Cookie")) {
String[] spl = cheader.split("\\;\\s*"); String[] spl = cheader.split("\\;\\s*");
for (String s : spl) { for (String s : spl) {
@ -158,25 +167,39 @@ public class IOHelper {
map.put(kv[0], kv[1]); 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<String, String> 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 * 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 * @param exchange
* @return The logged in user or null if not logged in. * @return The logged in user or null if not logged in.
* @throws IOException * @throws IOException
*/ */
public static User GetLoggedInUser(HttpExchange exchange) throws IOException { public static User GetLoggedInUser(HttpExchange exchange) throws IOException {
HashMap<String, String> cookies = GetCookies(exchange); Cookies cookies = GetCookies(exchange);
if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id")) if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id"))
return null; return null;
User user = DataManager.load(User.class, Long.parseLong(cookies.get("user_id"))); 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").equals(user.getSessionid())) 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; return user;
else } else
SendLogoutHeaders(exchange); SendLogoutHeaders(exchange);
return null; return null;
} }

View file

@ -21,7 +21,7 @@ public class LoginAjaxPage extends Page {
} }
User loginuser = null; User loginuser = null;
for (User user : DataManager.load(User.class)) { for (User user : DataManager.load(User.class)) {
if (user.getEmail().equals(post.get("email"))) { if (user.getEmail().equals(post.get("email").getAsString())) {
loginuser = user; loginuser = user;
break; break;
} }

View file

@ -76,7 +76,7 @@ public class SendMessageAjaxPage extends Page {
msg.setMessageChunk(chunk); // TODO: Store relations at one side or msg.setMessageChunk(chunk); // TODO: Store relations at one side or
// both); // both);
chunk.getMessages().add(msg); chunk.getMessages().add(msg);
//DataManager.save(chunk); - TODO // DataManager.save(chunk); - TODO
conv.getMesssageChunks().add(chunk); conv.getMesssageChunks().add(chunk);
DataManager.save(conv); DataManager.save(conv);
LogManager.getLogger().log(Level.DEBUG, LogManager.getLogger().log(Level.DEBUG,