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"/>
<script>
$(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>
</head>
<body>

View file

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

View file

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

View file

@ -18,8 +18,10 @@ public final class DataManager {
public static <T extends SavedData> 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();
}

View file

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

View file

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

View file

@ -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<Message> messages = new ArrayList<>();
private LoaderRef<Conversation> conversation;
@ -30,4 +32,14 @@ public class MessageChunk extends SavedData {
public void setConversation(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")
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);
}

View file

@ -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<User> getUsers() {
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.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<String, String> 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<String, String> GetPOSTKeyValues(HttpExchange exchange) {
try {
String[] content = GetPOST(exchange).split("\\&");
HashMap<String, String> 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, "<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"))
return new HashMap<>();
HashMap<String, String> map = new HashMap<>();
return new Cookies();
Map<String, String> 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<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
* 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<String, String> 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;
}

View file

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

View file

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