Setting the server earlier than before

Also added cookies from ChatServer
This commit is contained in:
Norbi Peti 2017-05-31 21:09:08 +02:00
parent f1a20c1498
commit e14d786417
5 changed files with 195 additions and 10 deletions

View file

@ -13,10 +13,16 @@ import buttondevteam.website.page.*;
public class ButtonWebsiteModule extends JavaPlugin {
private static HttpServer server;
@Override
public void onEnable() {
public ButtonWebsiteModule() {
try {
server = HttpServer.create(new InetSocketAddress((InetAddress) null, 8080), 10);
} catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while starting the webserver!", e);
}
}
@Override
public void onEnable() {
addPage(new IndexPage());
Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
@ -24,9 +30,6 @@ public class ButtonWebsiteModule extends JavaPlugin {
((Runnable) server::start).run(); // Totally normal way of calling a method
this.getLogger().info("Webserver started");
});
} catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while starting the webserver!", e);
}
}
/**

View file

@ -0,0 +1,32 @@
package buttondevteam.website.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 buttondevteam.website.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

@ -4,7 +4,14 @@ import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.logging.Level;
import org.apache.commons.io.IOUtils;
import org.bukkit.Bukkit;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@ -57,4 +64,85 @@ public class IOHelper {
return null;
}
}
/**
* Sends login headers and sets the session id on the user
*
* @param exchange
* @param user
*/
/*public static void LoginUser(HttpExchange exchange, User user) {
Bukkit.getLogger().fine("Logging in user: " + user);
// provider.SetValues(() ->
// user.setSessionid(UUID.randomUUID().toString()));
user.setSessionid(UUID.randomUUID().toString());
new Cookies(2).add(new Cookie("user_id", user.getId() + "")).add(new Cookie("session_id", user.getSessionid()))
.SendHeaders(exchange);
Bukkit.getLogger().fine("Logged in user.");
}
public static void LogoutUser(HttpExchange exchange, User user) {
user.setSessionid(new UUID(0, 0).toString());
SendLogoutHeaders(exchange);
}
private static void SendLogoutHeaders(HttpExchange exchange) {
String expiretime = "Sat, 19 Mar 2016 23:33:00 GMT";
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 {
exchange.getResponseHeaders().add("Location", url);
IOHelper.SendResponse(303, "<a href=\"" + url + "\">If you can see this, click here to continue</a>", exchange);
}
public static Cookies GetCookies(HttpExchange exchange) {
if (!exchange.getRequestHeaders().containsKey("Cookie"))
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) {
String[] kv = s.split("\\=");
if (kv.length < 2)
continue;
map.put(kv[0], kv[1]);
}
}
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, 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 {
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()), 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"))))
LoginUser(exchange, user);
return user;
} else
SendLogoutHeaders(exchange);
return null;
}*/
}

View file

@ -5,6 +5,7 @@ import org.apache.commons.io.output.ByteArrayOutputStream;
import com.sun.net.httpserver.*;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.website.io.IOHelper;
import buttondevteam.website.io.Response;
@ -23,7 +24,7 @@ public abstract class Page implements HttpHandler {
IOHelper.SendResponse(404, "404 Not found", exchange);
}
} catch (Exception e) {
e.printStackTrace();
TBMCCoreAPI.SendException("Internal Server Error in ButtonWebsiteModule!", e);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream str = new PrintStream(baos);