Merge remote-tracking branch 'origin/4.0.0-BungeeCord-Support' into 4.0.0-BungeeCord-Support

# Conflicts:
#	Plan/src/main/java/com/djrapitops/plan/Plan.java
This commit is contained in:
Rsl1122 2017-08-20 10:46:39 +03:00
commit e3712f0e4c
32 changed files with 519 additions and 183 deletions

View File

@ -77,7 +77,6 @@ public class Log {
* @param messages All messages to add to the debug log. * @param messages All messages to add to the debug log.
* @return full debug complex so far. * @return full debug complex so far.
*/ */
@SafeVarargs
public static DebugInfo debug(String task, String... messages) { public static DebugInfo debug(String task, String... messages) {
DebugInfo debug = getDebug(task); DebugInfo debug = getDebug(task);
long time = MiscUtils.getTime(); long time = MiscUtils.getTime();

View File

@ -40,9 +40,12 @@ import main.java.com.djrapitops.plan.database.databases.SQLiteDB;
import main.java.com.djrapitops.plan.locale.Locale; import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg; import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.webserver.WebServer; import main.java.com.djrapitops.plan.ui.webserver.WebServer;
import main.java.com.djrapitops.plan.ui.webserver.api.bukkit.*;
import main.java.com.djrapitops.plan.utilities.Benchmark; import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.Check; import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.metrics.BStats;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPIManager;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -173,6 +176,7 @@ public class Plan extends BukkitPlugin<Plan> {
if (analysisRefreshTaskIsEnabled) { if (analysisRefreshTaskIsEnabled) {
startAnalysisRefreshTask(analysisRefreshMinutes); startAnalysisRefreshTask(analysisRefreshMinutes);
} }
Benchmark.stop("Enable", "Analysis refresh task registration"); Benchmark.stop("Enable", "Analysis refresh task registration");
Benchmark.start("WebServer Initialization"); Benchmark.start("WebServer Initialization");
@ -184,6 +188,7 @@ public class Plan extends BukkitPlugin<Plan> {
uiServer = new WebServer(this); uiServer = new WebServer(this);
if (webserverIsEnabled) { if (webserverIsEnabled) {
registerWebAPIs();
uiServer.initServer(); uiServer.initServer();
if (!uiServer.isEnabled()) { if (!uiServer.isEnabled()) {
@ -197,6 +202,7 @@ public class Plan extends BukkitPlugin<Plan> {
if (!usingAlternativeIP && serverVariableHolder.getIp().isEmpty()) { if (!usingAlternativeIP && serverVariableHolder.getIp().isEmpty()) {
Log.infoColor(Locale.get(Msg.ENABLE_NOTIFY_EMPTY_IP).toString()); Log.infoColor(Locale.get(Msg.ENABLE_NOTIFY_EMPTY_IP).toString());
} }
Benchmark.stop("Enable", "WebServer Initialization"); Benchmark.stop("Enable", "WebServer Initialization");
registerCommand(new PlanCommand(this)); registerCommand(new PlanCommand(this));
@ -293,6 +299,14 @@ public class Plan extends BukkitPlugin<Plan> {
Benchmark.stop("Enable", "Register Listeners"); Benchmark.stop("Enable", "Register Listeners");
} }
private void registerWebAPIs() {
WebAPIManager.registerNewAPI("analytics", new AnalyticsWebAPI());
WebAPIManager.registerNewAPI("analyze", new AnalyzeWebAPI());
WebAPIManager.registerNewAPI("configure", new ConfigureWebAPI());
WebAPIManager.registerNewAPI("inspection", new InspectionWebAPI());
WebAPIManager.registerNewAPI("inspect", new InspectWebAPI());
}
/** /**
* Initializes the database according to settings in the config. * Initializes the database according to settings in the config.
* <p> * <p>
@ -300,7 +314,7 @@ public class Plan extends BukkitPlugin<Plan> {
* *
* @return true if init was successful, false if not. * @return true if init was successful, false if not.
*/ */
public boolean initDatabase() { private boolean initDatabase() {
databases = new HashSet<>(); databases = new HashSet<>();
databases.add(new MySQLDB(this)); databases.add(new MySQLDB(this));
databases.add(new SQLiteDB(this)); databases.add(new SQLiteDB(this));

View File

@ -9,14 +9,11 @@ import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions; import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.command.ConditionUtils; import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler; import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale; import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg; import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.text.TextUI;
import main.java.com.djrapitops.plan.utilities.Check; import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -95,52 +92,4 @@ public class AnalyzeCommand extends SubCommand {
analysisCache.sendAnalysisMessage(sender); analysisCache.sendAnalysisMessage(sender);
} }
} }
private void runMessageSenderTask(ISender sender) {
plugin.getRunnableFactory().createNew("AnalysisMessageSenderTask", new AbsRunnable() {
private int timesRun = 0;
@Override
public void run() {
timesRun++;
if (analysisCache.isCached() && (!analysisCache.isAnalysisBeingRun() || !analysisCache.isAnalysisEnabled())) {
sendAnalysisMessage(sender);
this.cancel();
return;
}
if (timesRun > 10) {
Log.debug("Command Timeout Message, Analysis.");
sender.sendMessage(Locale.get(Msg.CMD_FAIL_TIMEOUT).parse("Analysis"));
this.cancel();
}
}
}).runTaskTimer(TimeAmount.SECOND.ticks(), 5 * TimeAmount.SECOND.ticks());
}
/**
* Used to send the message after /plan analysis.
* <p>
* Final because
*
* @param sender Command sender.
*/
private void sendAnalysisMessage(ISender sender) {
boolean textUI = Settings.USE_ALTERNATIVE_UI.isTrue();
sender.sendMessage(Locale.get(Msg.CMD_HEADER_ANALYZE).toString());
if (textUI) {
sender.sendMessage(TextUI.getAnalysisMessages());
} else {
// Link
String url = HtmlUtils.getServerAnalysisUrlWithProtocol();
String message = Locale.get(Msg.CMD_INFO_LINK).toString();
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
}
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
}
} }

View File

@ -72,24 +72,7 @@ public abstract class RawData {
* @param value Any value the placeholder should be replaced with. * @param value Any value the placeholder should be replaced with.
*/ */
public void addValue(String placeholder, Serializable value) { public void addValue(String placeholder, Serializable value) {
replaceMap.put(addPlaceholderSigns(placeholder), value.toString()); replaceMap.put(placeholder, value.toString());
}
private String addPlaceholderSigns(String placeholder) {
StringBuilder newPlaceholder = new StringBuilder();
if (placeholder.charAt(0) != '%') {
newPlaceholder.append("%");
}
newPlaceholder.append(placeholder);
int lastIndex = placeholder.length() - 1;
if (placeholder.charAt(lastIndex) != '%') {
newPlaceholder.append("%");
}
return newPlaceholder.toString();
} }
/** /**
@ -102,12 +85,12 @@ public abstract class RawData {
} }
/** /**
* Used to get the value for a placeholder with or without the % symbols. * Used to get the value for a placeholder without the placeholder prefix and suffix.
* *
* @param key placeholder with or without % symbols. * @param key placeholder without the prefix and suffix
* @return Value the placeholder should be replaced with or null. * @return Value the placeholder should be replaced with or null.
*/ */
public String get(String key) { public String get(String key) {
return replaceMap.get(addPlaceholderSigns(key)); return replaceMap.get(key);
} }
} }

View File

@ -64,9 +64,7 @@ public class AnalysisCacheHandler {
cache = data; cache = data;
for (UUID uuid : notifyWhenCached) { for (UUID uuid : notifyWhenCached) {
Optional<IPlayer> player = plugin.fetch().getPlayer(uuid); Optional<IPlayer> player = plugin.fetch().getPlayer(uuid);
if (player.isPresent()) { player.ifPresent(this::sendAnalysisMessage);
sendAnalysisMessage(player.get());
}
} }
notifyWhenCached.clear(); notifyWhenCached.clear();
} }

View File

@ -5,6 +5,7 @@ import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData; import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.database.Database; import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.ui.webserver.response.InspectPageResponse; import main.java.com.djrapitops.plan.ui.webserver.response.InspectPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.JsonResponse;
import main.java.com.djrapitops.plan.utilities.HtmlUtils; import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.ExportUtility; import main.java.com.djrapitops.plan.utilities.analysis.ExportUtility;
@ -46,9 +47,13 @@ public class InspectCacheHandler {
*/ */
public void cache(UUID uuid) { public void cache(UUID uuid) {
DBCallableProcessor cacher = data -> { DBCallableProcessor cacher = data -> {
cache.put(uuid, new UserData(data)); UserData userData = new UserData(data);
cache.put(uuid, userData);
cacheTimes.put(uuid, MiscUtils.getTime()); cacheTimes.put(uuid, MiscUtils.getTime());
PageCacheHandler.cachePage("inspectPage: " + uuid.toString(), () -> new InspectPageResponse(Plan.getInstance().getUiServer().getDataReqHandler(), uuid));
PageCacheHandler.cachePage("inspectPage: " + uuid, () -> new InspectPageResponse(Plan.getInstance().getUiServer().getDataReqHandler(), uuid));
PageCacheHandler.cachePage("inspectionJson: " + uuid, () -> new JsonResponse(userData));
try { try {
ExportUtility.writeInspectHtml(data, ExportUtility.getPlayersFolder(ExportUtility.getFolder()), HtmlUtils.getStringFromResource("player.html")); ExportUtility.writeInspectHtml(data, ExportUtility.getPlayersFolder(ExportUtility.getFolder()), HtmlUtils.getStringFromResource("player.html"));

View File

@ -44,7 +44,7 @@ public class PageCacheHandler {
* @return The Response that was cached or created by the {@link PageLoader loader} * @return The Response that was cached or created by the {@link PageLoader loader}
*/ */
public static Response loadPage(String identifier, PageLoader loader) { public static Response loadPage(String identifier, PageLoader loader) {
Response response = pageCache.getIfPresent(identifier); Response response = loadPage(identifier);
if (response != null) { if (response != null) {
return response; return response;
@ -57,6 +57,16 @@ public class PageCacheHandler {
return response; return response;
} }
/**
* Loads the page from the page cache.
*
* @param identifier The identifier of the page
* @return The Response that was cached or {@code null} if it wasn't
*/
public static Response loadPage(String identifier) {
return pageCache.getIfPresent(identifier);
}
/** /**
* Puts the page into the page cache. * Puts the page into the page cache.
* <p> * <p>

View File

@ -43,20 +43,20 @@ public class PlanCommandPreprocessListener implements Listener {
return; return;
} }
String commandName = event.getMessage().split(" ")[0].toLowerCase(); String commandName = event.getMessage().substring(1).split(" ")[0].toLowerCase();
boolean doNotLogUnknownCommands = Settings.DO_NOT_LOG_UNKNOWN_COMMANDS.isTrue(); boolean doNotLogUnknownCommands = Settings.DO_NOT_LOG_UNKNOWN_COMMANDS.isTrue();
boolean combineCommandAliasesToMainCommand = Settings.COMBINE_COMMAND_ALIASES_TO_MAIN_COMMAND.isTrue(); boolean combineCommandAliasesToMainCommand = Settings.COMBINE_COMMAND_ALIASES_TO_MAIN_COMMAND.isTrue();
if (doNotLogUnknownCommands || combineCommandAliasesToMainCommand) { if (doNotLogUnknownCommands || combineCommandAliasesToMainCommand) {
Command command = plugin.getServer().getPluginCommand(commandName.substring(1, commandName.length())); Command command = plugin.getServer().getPluginCommand(commandName);
if (command == null) { if (command == null) {
if (doNotLogUnknownCommands) { if (doNotLogUnknownCommands) {
Log.debug("Ignored command, command is unknown"); Log.debug("Ignored command, command is unknown");
return; return;
} }
} else if (combineCommandAliasesToMainCommand) { } else if (combineCommandAliasesToMainCommand) {
commandName = "/" + command.getName(); commandName = command.getName();
} }
} }

View File

@ -27,11 +27,11 @@ public class Select extends SqlParser {
public Select where(String... conditions) { public Select where(String... conditions) {
append(" WHERE "); append(" WHERE ");
for (int i = 0; i < conditions.length; i++) { for (String condition : conditions) {
if (this.conditions > 0) { if (this.conditions > 0) {
append(" AND "); append(" AND ");
} }
append("(").append(conditions[i]).append(")"); append("(").append(condition).append(")");
this.conditions++; this.conditions++;
} }
return this; return this;

View File

@ -66,9 +66,14 @@ public class PlayersTableCreator {
} }
private static String getActivityString(boolean isBanned, boolean isUnknown, boolean isActive) { private static String getActivityString(boolean isBanned, boolean isUnknown, boolean isActive) {
return isBanned ? "Banned" if (isBanned) {
: (isUnknown ? "Unknown" return "Banned";
: (isActive ? "Active" }
: "Inactive"));
if (isUnknown) {
return "Unknown";
}
return isActive ? "Active" : "Inactive";
} }
} }

View File

@ -12,10 +12,14 @@ import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg; import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.DataRequestHandler; import main.java.com.djrapitops.plan.ui.html.DataRequestHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.*; import main.java.com.djrapitops.plan.ui.webserver.response.*;
import main.java.com.djrapitops.plan.ui.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.JsonResponse;
import main.java.com.djrapitops.plan.utilities.Benchmark; import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.HtmlUtils; import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil; import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility; import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPIManager;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import javax.net.ssl.*; import javax.net.ssl.*;
@ -26,12 +30,11 @@ import java.nio.file.Paths;
import java.security.*; import java.security.*;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.Base64; import java.util.*;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
/** /**
@ -84,11 +87,30 @@ public class WebServer {
@Override @Override
public void handle(HttpExchange exchange) throws IOException { public void handle(HttpExchange exchange) throws IOException {
try { try {
Headers responseHeaders = exchange.getResponseHeaders();
URI uri = exchange.getRequestURI(); URI uri = exchange.getRequestURI();
String target = uri.toString(); String target = uri.toString();
Headers responseHeaders = exchange.getResponseHeaders(); boolean apiRequest = "POST".equals(exchange.getRequestMethod());
responseHeaders.set("Content-Type", "text/html;"); Response response = null;
String type = "text/html;";
if (apiRequest) {
response = getAPIResponse(target, exchange);
if (response instanceof JsonResponse) {
type = "application/json;";
}
}
responseHeaders.set("Content-Type", type);
if (apiRequest) {
sendData(responseHeaders, exchange, response);
return;
}
WebUser user = null; WebUser user = null;
if (usingHttps) { if (usingHttps) {
@ -100,21 +122,9 @@ public class WebServer {
} }
} }
responseHeaders.set("Content-Encoding", "gzip"); response = getResponse(target, user);
Response response = getResponse(target, user); sendData(responseHeaders, exchange, response);
String content = response.getContent();
exchange.sendResponseHeaders(response.getCode(), 0);
try (GZIPOutputStream out = new GZIPOutputStream(exchange.getResponseBody());
ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes())) {
byte[] buffer = new byte[2048];
int count;
while ((count = bis.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
}
} catch (Exception e) { } catch (Exception e) {
Log.toLog(this.getClass().getName(), e); Log.toLog(this.getClass().getName(), e);
throw e; throw e;
@ -136,6 +146,20 @@ public class WebServer {
} }
} }
private void sendData(Headers header, HttpExchange exchange, Response response) throws IOException {
header.set("Content-Encoding", "gzip");
exchange.sendResponseHeaders(response.getCode(), 0);
try (GZIPOutputStream out = new GZIPOutputStream(exchange.getResponseBody());
ByteArrayInputStream bis = new ByteArrayInputStream(response.getContent().getBytes())) {
byte[] buffer = new byte[2048];
int count;
while ((count = bis.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
}
}
private WebUser getUser(Headers requestHeaders) { private WebUser getUser(Headers requestHeaders) {
Benchmark.start("getUser"); Benchmark.start("getUser");
try { try {
@ -243,6 +267,73 @@ public class WebServer {
return startSuccessful; return startSuccessful;
} }
private String readPOSTRequest(HttpExchange exchange) throws IOException {
byte[] bytes;
try (InputStream in = exchange.getRequestBody()) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int n = in.read(buf); n > 0; n = in.read(buf)) {
out.write(buf, 0, n);
}
bytes = out.toByteArray();
}
try {
return new String(bytes, "ISO-8859-1");
} catch (Exception e) {
return null;
}
}
private Response getAPIResponse(String target, HttpExchange exchange) throws IOException {
String[] args = target.split("/");
if (args.length < 3) {
String error = "API Method not specified";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
String method = args[2];
String response = readPOSTRequest(exchange);
if (response == null) {
String error = "Error at reading the POST request." +
"Note that the Encoding must be ISO-8859-1.";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
Map<String, String> variables = readVariables(response);
//TODO ADD CHECK IF SERVER KEY VALID
Plan plan = Plan.getInstance();
WebAPI api = WebAPIManager.getAPI(method);
if (api == null) {
String error = "API Method not found";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
try {
return api.onResponse(plan, variables);
} catch (Exception ex) {
Log.toLog("WebServer.getAPIResponse", ex);
return new InternalErrorResponse(ex, "An error while processing the request happened");
}
}
private Map<String, String> readVariables(String response) {
String[] variables = response.split("&");
return Arrays.stream(variables)
.map(variable -> variable.split("=", 2))
.filter(splittedVariables -> splittedVariables.length == 2)
.collect(Collectors.toMap(splittedVariables -> splittedVariables[0], splittedVariables -> splittedVariables[1], (a, b) -> b));
}
private Response getResponse(String target, WebUser user) { private Response getResponse(String target, WebUser user) {
if ("/favicon.ico".equals(target)) { if ("/favicon.ico".equals(target)) {
return PageCacheHandler.loadPage("Redirect: favicon", () -> new RedirectResponse("https://puu.sh/tK0KL/6aa2ba141b.ico")); return PageCacheHandler.loadPage("Redirect: favicon", () -> new RedirectResponse("https://puu.sh/tK0KL/6aa2ba141b.ico"));
@ -259,6 +350,7 @@ public class WebServer {
return forbiddenResponse(permLevel, required); return forbiddenResponse(permLevel, required);
} }
} }
String[] args = target.split("/"); String[] args = target.split("/");
if (args.length < 2) { if (args.length < 2) {
return rootPageResponse(user); return rootPageResponse(user);
@ -294,6 +386,7 @@ public class WebServer {
if (user == null) { if (user == null) {
return notFoundResponse(); return notFoundResponse();
} }
switch (user.getPermLevel()) { switch (user.getPermLevel()) {
case 0: case 0:
return serverResponse(); return serverResponse();
@ -333,7 +426,7 @@ public class WebServer {
return PageCacheHandler.loadPage("notFound: " + error, () -> new NotFoundResponse(error)); return PageCacheHandler.loadPage("notFound: " + error, () -> new NotFoundResponse(error));
} }
return PageCacheHandler.loadPage("inspectPage: " + uuid.toString(), () -> new InspectPageResponse(dataReqHandler, uuid)); return PageCacheHandler.loadPage("inspectPage: " + uuid, () -> new InspectPageResponse(dataReqHandler, uuid));
} }
private Response notFoundResponse() { private Response notFoundResponse() {

View File

@ -0,0 +1,29 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.api.bukkit;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import main.java.com.djrapitops.plan.ui.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import java.util.Map;
/**
* @author Fuzzlemann
*/
public class AnalyticsWebAPI implements WebAPI {
@Override
public Response onResponse(Plan plan, Map<String, String> variables) {
String identifier = "analysisJson";
if (!PageCacheHandler.isCached(identifier)) {
return PageCacheHandler.loadPage("No Analysis Data", () -> new BadRequestResponse("No analysis data available"));
}
return PageCacheHandler.loadPage(identifier);
}
}

View File

@ -0,0 +1,24 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.api.bukkit;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import main.java.com.djrapitops.plan.ui.webserver.response.api.SuccessResponse;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import java.util.Map;
/**
* @author Fuzzlemann
*/
public class AnalyzeWebAPI implements WebAPI {
@Override
public Response onResponse(Plan plan, Map<String, String> variables) {
plan.getAnalysisCache().updateCache();
return PageCacheHandler.loadPage("success", SuccessResponse::new);
}
}

View File

@ -0,0 +1,48 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.api.bukkit;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import main.java.com.djrapitops.plan.ui.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.SuccessResponse;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.Map;
/**
* @author Fuzzlemann
*/
public class ConfigureWebAPI implements WebAPI {
@Override
public Response onResponse(Plan plan, Map<String, String> variables) {
String key = variables.get("configKey");
if (key == null) {
String error = "Config Key null";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
String value = variables.get("configValue");
if (value == null) {
String error = "Config Value null";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
if (value.equals("null")) {
value = null;
}
FileConfiguration config = plan.getConfig();
config.set(key, value);
plan.saveConfig();
return PageCacheHandler.loadPage("success", SuccessResponse::new);
}
}

View File

@ -0,0 +1,42 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.api.bukkit;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import main.java.com.djrapitops.plan.ui.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.SuccessResponse;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import java.util.Map;
import java.util.UUID;
/**
* @author Fuzzlemann
*/
public class InspectWebAPI implements WebAPI {
@Override
public Response onResponse(Plan plan, Map<String, String> variables) {
String playerString = variables.get("player");
if (playerString == null) {
String error = "Player String not included";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
UUID uuid = UUIDUtility.getUUIDOf(playerString);
if (uuid == null) {
String error = "UUID not found";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
Plan.getInstance().getInspectCache().cache(uuid);
return PageCacheHandler.loadPage("success", SuccessResponse::new);
}
}

View File

@ -0,0 +1,48 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.api.bukkit;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import main.java.com.djrapitops.plan.ui.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.JsonResponse;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import java.util.Map;
import java.util.UUID;
/**
* @author Fuzzlemann
*/
public class InspectionWebAPI implements WebAPI {
@Override
public Response onResponse(Plan plan, Map<String, String> variables) {
String playerString = variables.get("player");
if (playerString == null) {
String error = "Player String not included";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
UUID uuid = UUIDUtility.getUUIDOf(playerString);
if (uuid == null) {
String error = "UUID not found";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
UserData userData = plan.getInspectCache().getFromCache(uuid);
if (userData == null) {
String error = "User not cached";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
return PageCacheHandler.loadPage("inspectionJson: " + uuid, () -> new JsonResponse(plan.getInspectCache().getFromCache(uuid)));
}
}

View File

@ -9,18 +9,23 @@ import main.java.com.djrapitops.plan.ui.html.Html;
public class InternalErrorResponse extends Response { public class InternalErrorResponse extends Response {
public InternalErrorResponse(Throwable e, String cause) { public InternalErrorResponse(Throwable e, String cause) {
super.setHeader("HTTP/1.1 500 Internal Error");
StringBuilder content = new StringBuilder(); StringBuilder content = new StringBuilder();
super.setHeader("HTTP/1.1 500 Internal Error");
content.append("<h1>500 Internal Error occurred</h1>"); content.append("<h1>500 Internal Error occurred</h1>");
content.append("<p>Please report this issue here: </p>"); content.append("<p>Please report this issue here: </p>");
content.append(Html.LINK.parse("https://github.com/Rsl1122/Plan-PlayerAnalytics/issues", "Issues")); content.append(Html.LINK.parse("https://github.com/Rsl1122/Plan-PlayerAnalytics/issues", "Issues"));
content.append("<p>"); content.append("<p>");
content.append(e).append(" | ").append(cause); content.append(e).append(" | ").append(cause);
for (Object element : e.getStackTrace()) {
for (StackTraceElement element : e.getStackTrace()) {
content.append("<br>"); content.append("<br>");
content.append(" ").append(element); content.append(" ").append(element);
} }
content.append("</p>"); content.append("</p>");
super.setContent(content.toString()); super.setContent(content.toString());
} }
} }

View File

@ -0,0 +1,18 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.response.api;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
/**
* @author Fuzzlemann
*/
public class BadRequestResponse extends Response {
public BadRequestResponse(String error) {
super.setHeader("HTTP/1.1 400 Bad Request");
super.setContent(error);
}
}

View File

@ -0,0 +1,21 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.response.api;
import com.google.gson.Gson;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
/**
* @author Fuzzlemann
*/
public class JsonResponse extends Response {
public <T> JsonResponse(T object) {
Gson gson = new Gson();
super.setHeader("HTTP/1.1 200 OK");
super.setContent(gson.toJson(object));
}
}

View File

@ -0,0 +1,18 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.ui.webserver.response.api;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
/**
* @author Fuzzlemann
*/
public class SuccessResponse extends Response {
public SuccessResponse() {
super.setHeader("HTTP/1.1 200 OK");
super.setContent("Success");
}
}

View File

@ -7,6 +7,7 @@ import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.Html; import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.ui.webserver.WebServer; import main.java.com.djrapitops.plan.ui.webserver.WebServer;
import main.java.com.djrapitops.plan.utilities.file.FileUtil; import main.java.com.djrapitops.plan.utilities.file.FileUtil;
import org.apache.commons.lang.text.StrSubstitutor;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.Serializable; import java.io.Serializable;
@ -40,14 +41,9 @@ public class HtmlUtils {
* @return * @return
*/ */
public static String replacePlaceholders(String html, Map<String, Serializable> replaceMap) { public static String replacePlaceholders(String html, Map<String, Serializable> replaceMap) {
for (Map.Entry<String, Serializable> entrySet : replaceMap.entrySet()) { StrSubstitutor sub = new StrSubstitutor(replaceMap);
String placeholder = entrySet.getKey();
String replacer = entrySet.getValue().toString();
html = html.replace(placeholder, replacer); return sub.replace(html);
}
return html;
} }
/** /**

View File

@ -20,6 +20,7 @@ import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.tables.PlayersTableCreator; import main.java.com.djrapitops.plan.ui.html.tables.PlayersTableCreator;
import main.java.com.djrapitops.plan.ui.webserver.response.AnalysisPageResponse; import main.java.com.djrapitops.plan.ui.webserver.response.AnalysisPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.PlayersPageResponse; import main.java.com.djrapitops.plan.ui.webserver.response.PlayersPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.JsonResponse;
import main.java.com.djrapitops.plan.utilities.Benchmark; import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.HtmlUtils; import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
@ -165,8 +166,9 @@ public class Analysis {
Log.info(Locale.get(Msg.ANALYSIS_FINISHED).parse(String.valueOf(time), HtmlUtils.getServerAnalysisUrlWithProtocol())); Log.info(Locale.get(Msg.ANALYSIS_FINISHED).parse(String.valueOf(time), HtmlUtils.getServerAnalysisUrlWithProtocol()));
} }
PageCacheHandler.removeIf(identifier -> identifier.startsWith("inspectPage: ")); PageCacheHandler.removeIf(identifier -> identifier.startsWith("inspectPage: ") || identifier.startsWith("inspectionJson: "));
PageCacheHandler.cachePage("analysisPage", () -> new AnalysisPageResponse(plugin.getUiServer().getDataReqHandler())); PageCacheHandler.cachePage("analysisPage", () -> new AnalysisPageResponse(plugin.getUiServer().getDataReqHandler()));
PageCacheHandler.cachePage("analysisJson", () -> new JsonResponse(analysisData));
PageCacheHandler.cachePage("players", () -> new PlayersPageResponse(plugin)); PageCacheHandler.cachePage("players", () -> new PlayersPageResponse(plugin));
ExportUtility.export(analysisData, rawData); ExportUtility.export(analysisData, rawData);

View File

@ -18,8 +18,7 @@ public class DumpLog {
* @param header The name of the header * @param header The name of the header
*/ */
public void addHeader(String header) { public void addHeader(String header) {
addLine(""); addLines("", "--- " + header + " ---");
addLine("--- " + header + " ---");
} }
/** /**

View File

@ -145,7 +145,7 @@ public class DumpUtils {
List<String> plugins = Arrays.stream(server.getPluginManager().getPlugins()) List<String> plugins = Arrays.stream(server.getPluginManager().getPlugins())
.map(Plugin::getDescription) .map(Plugin::getDescription)
.map(description -> description.getName() + " " + description.getVersion()) .map(description -> description.getName() + " " + description.getVersion())
.sorted() .sorted(String::compareToIgnoreCase)
.collect(Collectors.toList()); .collect(Collectors.toList());
log.addHeader("Server Details"); log.addHeader("Server Details");

View File

@ -0,0 +1,18 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.utilities.webserver.api;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import java.util.Map;
/**
* @author Fuzzlemann
*/
public interface WebAPI {
Response onResponse(Plan plan, Map<String, String> variables);
}

View File

@ -0,0 +1,31 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.utilities.webserver.api;
import java.util.HashMap;
import java.util.Map;
/**
* @author Fuzzlemann
*/
public class WebAPIManager {
/**
* Constructor used to hide the public constructor
*/
private WebAPIManager() {
throw new IllegalStateException("Utility class");
}
private static Map<String, WebAPI> registry = new HashMap<>();
public static void registerNewAPI(String method, WebAPI api) {
registry.put(method.toLowerCase(), api);
}
public static WebAPI getAPI(String method) {
return registry.get(method.toLowerCase());
}
}

View File

@ -74,5 +74,4 @@ public class SettingsTest {
public void testGetPath() { public void testGetPath() {
assertEquals("Settings.WebServer.Enabled", Settings.WEBSERVER_ENABLED.getPath()); assertEquals("Settings.WebServer.Enabled", Settings.WEBSERVER_ENABLED.getPath());
} }
} }

View File

@ -106,14 +106,11 @@ public class DataCacheQueueTest {
public void testGetQueue_cache() { public void testGetQueue_cache() {
List<Integer> calls = new ArrayList<>(); List<Integer> calls = new ArrayList<>();
List<Integer> errors = new ArrayList<>(); List<Integer> errors = new ArrayList<>();
handler.getUserDataForProcessing(new DBCallableProcessor() { handler.getUserDataForProcessing(data -> {
@Override if (data.equals(data1)) {
public void process(UserData data) { calls.add(1);
if (data.equals(data1)) { } else {
calls.add(1); errors.add(1);
} else {
errors.add(1);
}
} }
}, uuid1); }, uuid1);
while (calls.size() < 1) { while (calls.size() < 1) {
@ -131,14 +128,11 @@ public class DataCacheQueueTest {
public void testGetQueue_dontCache() { public void testGetQueue_dontCache() {
List<Integer> getCalls = new ArrayList<>(); List<Integer> getCalls = new ArrayList<>();
List<Integer> errors = new ArrayList<>(); List<Integer> errors = new ArrayList<>();
handler.getUserDataForProcessing(new DBCallableProcessor() { handler.getUserDataForProcessing(data -> {
@Override if (data.equals(data1)) {
public void process(UserData data) { getCalls.add(1);
if (data.equals(data1)) { } else {
getCalls.add(1); errors.add(1);
} else {
errors.add(1);
}
} }
}, uuid1, false); }, uuid1, false);
while (getCalls.size() < 1) { while (getCalls.size() < 1) {

View File

@ -5,21 +5,21 @@
*/ */
package test.java.main.java.com.djrapitops.plan.utilities; package test.java.main.java.com.djrapitops.plan.utilities;
import com.google.common.collect.ImmutableMap;
import main.java.com.djrapitops.plan.utilities.HtmlUtils; import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.RandomData;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rsl1122 * @author Rsl1122
@ -28,62 +28,50 @@ import static org.junit.Assert.assertTrue;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class HtmlUtilsTest { public class HtmlUtilsTest {
/**
*
*/
public HtmlUtilsTest() {
}
/**
*
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws Exception
*/
@Test @Test
public void testGetHtmlStringFromResource() throws Exception { public void testGetHtmlStringFromResource() throws Exception {
TestInit.init(); TestInit.init();
String fileName = "player.html"; String fileName = "player.html";
String result = HtmlUtils.getStringFromResource(fileName); String result = HtmlUtils.getStringFromResource(fileName);
assertTrue("Result empty", !result.isEmpty());
assertFalse("Result empty", result.isEmpty());
} }
/**
*
*/
@Test @Test
public void testReplacePlaceholders() { public void testReplacePlaceholders() {
String html = "%test%"; String randomString = RandomData.randomString(100);
Map<String, Serializable> replaceMap = new HashMap<>(); String randomIdentifier = RandomData.randomString(5);
replaceMap.put("%test%", "Success");
String expResult = "Success"; String html = "${" + randomIdentifier + "}" + randomString;
Map<String, Serializable> replaceMap = ImmutableMap.of(randomIdentifier, "Success");
String expResult = "Success" + randomString;
String result = HtmlUtils.replacePlaceholders(html, replaceMap); String result = HtmlUtils.replacePlaceholders(html, replaceMap);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
/**
*
*/
@Test @Test
public void testReplacePlaceholdersBackslash() { public void testReplacePlaceholdersBackslash() {
Map<String, Serializable> replace = new HashMap<>(); String randomIdentifier = RandomData.randomString(5);
replace.put("%test%", "/\\");
String result = HtmlUtils.replacePlaceholders("%test% alright %test%", replace); Map<String, Serializable> replace = ImmutableMap.of(randomIdentifier, "/\\");
String exp = "/\\ alright /\\";
assertEquals(result, exp); String expResult = "/\\ alright /\\";
String result = HtmlUtils.replacePlaceholders("${" + randomIdentifier + "} alright ${" + randomIdentifier + "}", replace);
assertEquals(result, expResult);
} }
/**
*
*/
@Test @Test
public void testRemoveXSS() { public void testRemoveXSS() {
String xss = "<script></script><!--"; String randomString = RandomData.randomString(10);
boolean passed = HtmlUtils.removeXSS(xss).length() < xss.length();
assertEquals(true, passed); String xss = "<script>" + randomString + "</script><!--";
String result = HtmlUtils.removeXSS(xss);
assertEquals(randomString, result);
} }
} }

View File

@ -10,6 +10,7 @@ import org.junit.Test;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
@ -46,7 +47,7 @@ public class MathUtilsTest {
*/ */
@Test @Test
public void testAverageIntEmpty() { public void testAverageIntEmpty() {
List<Integer> l = new ArrayList<>(); List<Integer> l = Collections.emptyList();
double exp = 0; double exp = 0;
double result = MathUtils.averageInt(l.stream()); double result = MathUtils.averageInt(l.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0); assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);

View File

@ -46,7 +46,6 @@ public class HastebinTest {
/* Ignored */ /* Ignored */
} }
Log.info(link);
testLink.set(link); testLink.set(link);
}); });

View File

@ -139,7 +139,7 @@ public class TestInit {
@Override @Override
public ITask runTask() { public ITask runTask() {
new Thread(() -> runnable.run()).start(); new Thread(runnable::run).start();
return null; return null;
} }