More WebAPI stuff:

- Changed post request key verification to verify that sender exists in the db. This allows any plugin to call Plan WebAPI on the same server.
This commit is contained in:
Rsl1122 2017-09-16 18:22:05 +03:00
parent fb717387d2
commit f5c6b1c994
18 changed files with 315 additions and 92 deletions

View File

@ -0,0 +1,16 @@
/*
* 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.api.exceptions;
/**
* Thrown when WebAPI gets a 403 response.
*
* @author Rsl1122
*/
public class WebAPIForbiddenException extends WebAPIException {
public WebAPIForbiddenException(String url) {
super("Forbidden: " + url);
}
}

View File

@ -0,0 +1,16 @@
/*
* 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.api.exceptions;
/**
* //TODO Class Javadoc Comment
*
* @author Rsl1122
*/
public class WebAPINotFoundException extends WebAPIException {
public WebAPINotFoundException() {
super("Not Found");
}
}

View File

@ -15,6 +15,7 @@ import main.java.com.djrapitops.plan.systems.webserver.webapi.WebAPI;
import main.java.com.djrapitops.plan.systems.webserver.webapi.bukkit.InspectWebAPI; import main.java.com.djrapitops.plan.systems.webserver.webapi.bukkit.InspectWebAPI;
import main.java.com.djrapitops.plan.utilities.Check; import main.java.com.djrapitops.plan.utilities.Check;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
/** /**
@ -40,11 +41,17 @@ public class DevCommand extends SubCommand {
switch (feature) { switch (feature) {
case "webapi": case "webapi":
if (!Check.isTrue(args.length >= 2, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString(), sender)) { if (!Check.isTrue(args.length >= 2, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString(), sender)) {
return true; break;
} }
if (!webapi(args[1])) { if (!webapi(args[1] + "webapi")) {
sender.sendMessage("[Plan] No such API / Exception occurred."); sender.sendMessage("[Plan] No such API / Exception occurred.");
} }
case "web":
Optional<String> bungeeConnectionAddress = plugin.getServerInfoManager().getBungeeConnectionAddress();
String accessAddress = plugin.getWebServer().getAccessAddress();
sender.sendMessage((plugin.getInfoManager().isUsingBungeeWebServer() && bungeeConnectionAddress.isPresent())
? "Bungee: " + bungeeConnectionAddress.get() : "Local: " + accessAddress);
break;
default: default:
break; break;
} }
@ -58,9 +65,9 @@ public class DevCommand extends SubCommand {
} }
try { try {
if (api instanceof InspectWebAPI) { if (api instanceof InspectWebAPI) {
((InspectWebAPI) api).sendRequest(plugin.getWebServer().getAccessAddress(), Plan.getServerUUID(), UUID.randomUUID()); ((InspectWebAPI) api).sendRequest(plugin.getWebServer().getAccessAddress(), UUID.randomUUID());
} else { } else {
api.sendRequest(plugin.getWebServer().getAccessAddress(), Plan.getServerUUID()); api.sendRequest(plugin.getWebServer().getAccessAddress());
} }
return true; return true;
} catch (WebAPIException e) { } catch (WebAPIException e) {

View File

@ -302,4 +302,24 @@ public class ServerTable extends Table {
close(statement); close(statement);
} }
} }
public List<UUID> getServerUUIDs() throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName, columnServerUUID)
.where(columnServerName + "!=?")
.toString());
statement.setString(1, "BungeeCord");
set = statement.executeQuery();
List<UUID> uuids = new ArrayList<>();
while (set.next()) {
uuids.add(UUID.fromString(set.getString(columnServerUUID)));
}
return uuids;
} finally {
endTransaction(statement);
close(set, statement);
}
}
} }

View File

@ -7,6 +7,8 @@ package main.java.com.djrapitops.plan.systems.info;
import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.api.exceptions.ParseException; import main.java.com.djrapitops.plan.api.exceptions.ParseException;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIConnectionFailException;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIException;
import main.java.com.djrapitops.plan.command.commands.AnalyzeCommand; import main.java.com.djrapitops.plan.command.commands.AnalyzeCommand;
import main.java.com.djrapitops.plan.data.AnalysisData; import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.additional.HookHandler; import main.java.com.djrapitops.plan.data.additional.HookHandler;
@ -16,8 +18,12 @@ import main.java.com.djrapitops.plan.systems.info.parsing.AnalysisPageParser;
import main.java.com.djrapitops.plan.systems.info.parsing.InspectPageParser; import main.java.com.djrapitops.plan.systems.info.parsing.InspectPageParser;
import main.java.com.djrapitops.plan.systems.processing.Processor; import main.java.com.djrapitops.plan.systems.processing.Processor;
import main.java.com.djrapitops.plan.systems.webserver.PageCache; import main.java.com.djrapitops.plan.systems.webserver.PageCache;
import main.java.com.djrapitops.plan.systems.webserver.response.AnalysisPageResponse;
import main.java.com.djrapitops.plan.systems.webserver.response.InspectPageResponse; import main.java.com.djrapitops.plan.systems.webserver.response.InspectPageResponse;
import main.java.com.djrapitops.plan.systems.webserver.response.Response; import main.java.com.djrapitops.plan.systems.webserver.response.Response;
import main.java.com.djrapitops.plan.systems.webserver.webapi.WebAPIManager;
import main.java.com.djrapitops.plan.systems.webserver.webapi.bungee.IsCachedWebAPI;
import main.java.com.djrapitops.plan.systems.webserver.webapi.universal.PingWebAPI;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.Analysis; import main.java.com.djrapitops.plan.utilities.analysis.Analysis;
import main.java.com.djrapitops.plan.utilities.html.HtmlStructure; import main.java.com.djrapitops.plan.utilities.html.HtmlStructure;
@ -51,9 +57,9 @@ public class BukkitInformationManager extends InformationManager {
Optional<String> bungeeConnectionAddress = plugin.getServerInfoManager().getBungeeConnectionAddress(); Optional<String> bungeeConnectionAddress = plugin.getServerInfoManager().getBungeeConnectionAddress();
if (bungeeConnectionAddress.isPresent()) { if (bungeeConnectionAddress.isPresent()) {
webServerAddress = bungeeConnectionAddress.get(); webServerAddress = bungeeConnectionAddress.get();
attemptConnection(); usingBungeeWebServer = attemptConnection();
} else { } else {
usingBungeeWebServer = false;
} }
} }
@ -78,7 +84,7 @@ public class BukkitInformationManager extends InformationManager {
public void cacheInspectPluginsTab(UUID uuid) { public void cacheInspectPluginsTab(UUID uuid) {
if (usingBungeeWebServer) { if (usingBungeeWebServer) {
// TODO plugin tab request on bungee // TODO plugin tab request on bungee
} } else {
String serverName = plugin.getServerInfoManager().getServerName(); String serverName = plugin.getServerInfoManager().getServerName();
HookHandler hookHandler = plugin.getHookHandler(); HookHandler hookHandler = plugin.getHookHandler();
List<PluginData> plugins = hookHandler.getAdditionalDataSources(); List<PluginData> plugins = hookHandler.getAdditionalDataSources();
@ -86,6 +92,7 @@ public class BukkitInformationManager extends InformationManager {
String contents = HtmlStructure.createInspectPageTabContent(serverName, plugins, replaceMap); String contents = HtmlStructure.createInspectPageTabContent(serverName, plugins, replaceMap);
cacheInspectPluginsTab(uuid, contents); cacheInspectPluginsTab(uuid, contents);
} }
}
public void cacheInspectPluginsTab(UUID uuid, String contents) { public void cacheInspectPluginsTab(UUID uuid, String contents) {
pluginsTabContents.put(uuid, contents); pluginsTabContents.put(uuid, contents);
@ -104,7 +111,11 @@ public class BukkitInformationManager extends InformationManager {
@Override @Override
public boolean isCached(UUID uuid) { public boolean isCached(UUID uuid) {
if (usingBungeeWebServer) { if (usingBungeeWebServer) {
// TODO Check if cached on bungee try {
return getWebAPI().getAPI(IsCachedWebAPI.class).isInspectCached(webServerAddress, uuid);
} catch (WebAPIException e) {
Log.toLog(this.getClass().getName(), e);
}
} }
return super.isCached(uuid); return super.isCached(uuid);
} }
@ -112,11 +123,19 @@ public class BukkitInformationManager extends InformationManager {
@Override @Override
public boolean isAnalysisCached() { public boolean isAnalysisCached() {
if (usingBungeeWebServer) { if (usingBungeeWebServer) {
// TODO Check if cached on bungee try {
return getWebAPI().getAPI(IsCachedWebAPI.class).isAnalysisCached(webServerAddress);
} catch (WebAPIException e) {
Log.toLog(this.getClass().getName(), e);
}
} }
return PageCache.isCached("analysisPage"); return PageCache.isCached("analysisPage");
} }
private WebAPIManager getWebAPI() {
return plugin.getWebServer().getWebAPI();
}
@Override @Override
public String getAnalysisHtml() { public String getAnalysisHtml() {
// TODO Bungee part. // TODO Bungee part.
@ -149,7 +168,7 @@ public class BukkitInformationManager extends InformationManager {
public void cacheAnalysisdata(AnalysisData analysisData) { public void cacheAnalysisdata(AnalysisData analysisData) {
this.analysisData = analysisData; this.analysisData = analysisData;
refreshDate = MiscUtils.getTime(); refreshDate = MiscUtils.getTime();
// TODO Web Caching (Move from Analysis) PageCache.cachePage("analysisPage", () -> new AnalysisPageResponse(this));
AnalyzeCommand.sendAnalysisMessage(analysisNotification); AnalyzeCommand.sendAnalysisMessage(analysisNotification);
analysisNotification.clear(); analysisNotification.clear();
} }
@ -163,8 +182,16 @@ public class BukkitInformationManager extends InformationManager {
} }
@Override @Override
public void attemptConnection() { public boolean attemptConnection() {
usingBungeeWebServer = true; PingWebAPI api = getWebAPI().getAPI(PingWebAPI.class);
// TODO Check the connection try {
api.sendRequest(webServerAddress);
return true;
} catch (WebAPIConnectionFailException e) {
plugin.getServerInfoManager().markConnectionFail();
} catch (WebAPIException e) {
Log.toLog(this.getClass().getName(), e);
}
return false;
} }
} }

View File

@ -4,12 +4,21 @@
*/ */
package main.java.com.djrapitops.plan.systems.info; package main.java.com.djrapitops.plan.systems.info;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIConnectionFailException;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIException;
import main.java.com.djrapitops.plan.bungee.PlanBungee; import main.java.com.djrapitops.plan.bungee.PlanBungee;
import main.java.com.djrapitops.plan.systems.cache.DataCache; import main.java.com.djrapitops.plan.systems.cache.DataCache;
import main.java.com.djrapitops.plan.systems.info.server.ServerInfo;
import main.java.com.djrapitops.plan.systems.webserver.PageCache; import main.java.com.djrapitops.plan.systems.webserver.PageCache;
import main.java.com.djrapitops.plan.systems.webserver.response.InspectPageResponse; import main.java.com.djrapitops.plan.systems.webserver.response.InspectPageResponse;
import main.java.com.djrapitops.plan.systems.webserver.webapi.bukkit.AnalyzeWebAPI;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
/** /**
* //TODO Class Javadoc Comment * //TODO Class Javadoc Comment
@ -18,8 +27,17 @@ import java.util.UUID;
*/ */
public class BungeeInformationManager extends InformationManager { public class BungeeInformationManager extends InformationManager {
public BungeeInformationManager(PlanBungee plugin) { private PlanBungee plugin;
private Map<UUID, ServerInfo> bukkitServers;
public BungeeInformationManager(PlanBungee plugin) throws SQLException {
usingBungeeWebServer = true; usingBungeeWebServer = true;
this.plugin = plugin;
refreshBukkitServerMap();
}
private void refreshBukkitServerMap() throws SQLException {
bukkitServers = plugin.getDB().getServerTable().getBukkitServers().stream().collect(Collectors.toMap(ServerInfo::getUuid, Function.identity()));
} }
@Override @Override
@ -28,7 +46,27 @@ public class BungeeInformationManager extends InformationManager {
} }
public void refreshAnalysis(UUID serverUUID) { public void refreshAnalysis(UUID serverUUID) {
// TODO ServerInfo serverInfo = bukkitServers.get(serverUUID);
if (serverInfo == null) {
try {
refreshBukkitServerMap();
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
serverInfo = bukkitServers.get(serverUUID);
}
if (serverInfo == null) {
return;
}
AnalyzeWebAPI api = plugin.getWebServer().getWebAPI().getAPI(AnalyzeWebAPI.class);
try {
api.sendRequest(serverInfo.getWebAddress());
} catch (WebAPIConnectionFailException e) {
attemptConnection();
} catch (WebAPIException e) {
Log.toLog(this.getClass().getName(), e);
}
} }
@Override @Override
@ -43,8 +81,8 @@ public class BungeeInformationManager extends InformationManager {
} }
@Override @Override
public void attemptConnection() { public boolean attemptConnection() {
return false;
} }
@Override @Override

View File

@ -28,7 +28,7 @@ public abstract class InformationManager {
analysisNotification = new HashSet<>(); analysisNotification = new HashSet<>();
} }
public abstract void attemptConnection(); public abstract boolean attemptConnection();
public abstract void cachePlayer(UUID uuid); public abstract void cachePlayer(UUID uuid);
@ -73,4 +73,8 @@ public abstract class InformationManager {
} }
public abstract String getPluginsTabContent(UUID uuid); public abstract String getPluginsTabContent(UUID uuid);
public boolean isUsingBungeeWebServer() {
return usingBungeeWebServer;
}
} }

View File

@ -7,6 +7,7 @@ package main.java.com.djrapitops.plan.systems.info.server;
import com.djrapitops.plugin.config.BukkitConfig; import com.djrapitops.plugin.config.BukkitConfig;
import com.djrapitops.plugin.config.fileconfig.IFileConfig; import com.djrapitops.plugin.config.fileconfig.IFileConfig;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import java.io.IOException; import java.io.IOException;
@ -66,10 +67,14 @@ public class ServerInfoFile extends BukkitConfig {
return getConfig().getString("Bungee.WebAddress"); return getConfig().getString("Bungee.WebAddress");
} }
public void markConnectionFail() throws IOException { public void markConnectionFail() {
try {
IFileConfig config = getConfig(); IFileConfig config = getConfig();
int fails = config.getInt("Bungee.Fail"); int fails = config.getInt("Bungee.Fail");
config.set("Bungee.Fail", fails + 1); config.set("Bungee.Fail", fails + 1);
save(); save();
} catch (IOException e) {
Log.toLog(this.getClass().getName(), e);
}
} }
} }

View File

@ -99,7 +99,7 @@ public class ServerInfoManager {
int id = serverID.get(); int id = serverID.get();
serverInfo.setId(id); serverInfo.setId(id);
serverInfoFile.saveInfo(serverInfo, new ServerInfo(id, serverUUID, name, webAddress, maxPlayers)); serverInfoFile.saveInfo(serverInfo, new ServerInfo(-1, null, name, "", 0));
} }
private UUID generateNewUUID(ServerVariableHolder variableHolder) { private UUID generateNewUUID(ServerVariableHolder variableHolder) {
@ -129,6 +129,10 @@ public class ServerInfoManager {
serverInfoFile.saveInfo(serverInfo, new ServerInfo(-1, null, "Bungee", address, -1)); serverInfoFile.saveInfo(serverInfo, new ServerInfo(-1, null, "Bungee", address, -1));
} }
public void markConnectionFail() {
serverInfoFile.markConnectionFail();
}
public int getServerID() { public int getServerID() {
return serverInfo.getId(); return serverInfo.getId();
} }

View File

@ -17,7 +17,9 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -57,9 +59,9 @@ public class APIResponseHandler {
} }
Map<String, String> variables = readVariables(requestBody); Map<String, String> variables = readVariables(requestBody);
String key = variables.get("key"); String sender = variables.get("sender");
if (!checkKey(key)) { if (!checkKey(sender)) {
String error = "Server Key not given or invalid"; String error = "Server Key not given or invalid";
return PageCache.loadPage(error, () -> { return PageCache.loadPage(error, () -> {
ForbiddenResponse forbidden = new ForbiddenResponse(); ForbiddenResponse forbidden = new ForbiddenResponse();
@ -103,20 +105,26 @@ public class APIResponseHandler {
} }
} }
private boolean checkKey(String key) { private boolean checkKey(String sender) {
if (key == null) { if (sender == null) {
return false; return false;
} }
UUID uuid = MiscUtils.getIPlan().getServerInfoManager().getServerUUID(); List<UUID> uuids = null;
try {
uuids = MiscUtils.getIPlan().getDB().getServerTable().getServerUUIDs();
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
return false;
}
UUID keyUUID; UUID keyUUID;
try { try {
keyUUID = UUID.fromString(key); keyUUID = UUID.fromString(sender);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
return false; return false;
} }
return uuid.equals(keyUUID); return uuids.contains(keyUUID);
} }
private Map<String, String> readVariables(String requestBody) { private Map<String, String> readVariables(String requestBody) {

View File

@ -12,6 +12,8 @@ import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.systems.info.InformationManager; import main.java.com.djrapitops.plan.systems.info.InformationManager;
import main.java.com.djrapitops.plan.systems.webserver.webapi.WebAPIManager; import main.java.com.djrapitops.plan.systems.webserver.webapi.WebAPIManager;
import main.java.com.djrapitops.plan.systems.webserver.webapi.bukkit.*; import main.java.com.djrapitops.plan.systems.webserver.webapi.bukkit.*;
import main.java.com.djrapitops.plan.systems.webserver.webapi.bungee.IsCachedWebAPI;
import main.java.com.djrapitops.plan.systems.webserver.webapi.bungee.PostHtmlWebAPI;
import main.java.com.djrapitops.plan.systems.webserver.webapi.universal.PingWebAPI; import main.java.com.djrapitops.plan.systems.webserver.webapi.universal.PingWebAPI;
import main.java.com.djrapitops.plan.utilities.html.HtmlUtils; import main.java.com.djrapitops.plan.utilities.html.HtmlUtils;
@ -64,7 +66,11 @@ public class WebServer {
webAPI.registerNewAPI(new ConfigurationWebAPI()); webAPI.registerNewAPI(new ConfigurationWebAPI());
webAPI.registerNewAPI(new InspectWebAPI()); webAPI.registerNewAPI(new InspectWebAPI());
webAPI.registerNewAPI(new OnlinePlayersWebAPI()); webAPI.registerNewAPI(new OnlinePlayersWebAPI());
webAPI.registerNewAPI(new MaxPlayersWebAPI());
webAPI.registerNewAPI(new PingWebAPI()); webAPI.registerNewAPI(new PingWebAPI());
webAPI.registerNewAPI(new IsCachedWebAPI(plugin));
webAPI.registerNewAPI(new PostHtmlWebAPI(plugin));
} }
/** /**

View File

@ -8,16 +8,18 @@ import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.api.IPlan; import main.java.com.djrapitops.plan.api.IPlan;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIConnectionFailException; import main.java.com.djrapitops.plan.api.exceptions.WebAPIConnectionFailException;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIException; import main.java.com.djrapitops.plan.api.exceptions.WebAPIException;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIForbiddenException;
import main.java.com.djrapitops.plan.api.exceptions.WebAPINotFoundException;
import main.java.com.djrapitops.plan.systems.webserver.response.Response; import main.java.com.djrapitops.plan.systems.webserver.response.Response;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL; import java.net.URL;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID;
/** /**
* @author Rsl1122 * @author Rsl1122
@ -32,12 +34,13 @@ public abstract class WebAPI {
public abstract Response onResponse(IPlan plugin, Map<String, String> variables); public abstract Response onResponse(IPlan plugin, Map<String, String> variables);
public void sendRequest(String address, UUID receiverUUID) throws WebAPIException { public void sendRequest(String address) throws WebAPIException {
Verify.nullCheck(address, receiverUUID); Verify.nullCheck(address);
try { try {
URL url = new URL(address + "/api/" + this.getClass().getSimpleName().toLowerCase()); URL url = new URL(address + "/api/" + this.getClass().getSimpleName().toLowerCase());
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setDoOutput(true); connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false); connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
@ -47,7 +50,6 @@ public abstract class WebAPI {
StringBuilder parameters = new StringBuilder(); StringBuilder parameters = new StringBuilder();
String serverUUID = MiscUtils.getIPlan().getServerInfoManager().getServerUUID().toString(); String serverUUID = MiscUtils.getIPlan().getServerInfoManager().getServerUUID().toString();
parameters.append("sender=").append(serverUUID).append("&"); parameters.append("sender=").append(serverUUID).append("&");
parameters.append("key=").append(receiverUUID.toString());
for (Map.Entry<String, String> entry : variables.entrySet()) { for (Map.Entry<String, String> entry : variables.entrySet()) {
parameters.append("&").append(entry.getKey()).append(entry.getValue()); parameters.append("&").append(entry.getKey()).append(entry.getValue());
} }
@ -67,9 +69,15 @@ public abstract class WebAPI {
return; return;
case 400: case 400:
throw new WebAPIException("Bad Request: " + url.toString() + "|" + parameters); throw new WebAPIException("Bad Request: " + url.toString() + "|" + parameters);
case 403:
throw new WebAPIForbiddenException(url.toString());
case 404:
throw new WebAPINotFoundException();
default: default:
throw new WebAPIException(url.toString() + "| Wrong response code " + responseCode); throw new WebAPIException(url.toString() + "| Wrong response code " + responseCode);
} }
} catch (SocketTimeoutException e) {
throw new WebAPIConnectionFailException("Connection timed out after 10 seconds.", e);
} catch (IOException e) { } catch (IOException e) {
throw new WebAPIConnectionFailException("API connection failed. address: " + address, e); throw new WebAPIConnectionFailException("API connection failed. address: " + address, e);
} }

View File

@ -25,8 +25,9 @@ public class WebAPIManager {
registry.put(api.getClass().getSimpleName().toLowerCase(), api); registry.put(api.getClass().getSimpleName().toLowerCase(), api);
} }
public WebAPI getAPI(Class api) { public <T extends WebAPI> T getAPI(Class<T> api) {
return getAPI(api.getSimpleName()); WebAPI webAPI = getAPI(api.getSimpleName());
return (T) webAPI;
} }
public WebAPI getAPI(String apiName) { public WebAPI getAPI(String apiName) {

View File

@ -34,12 +34,12 @@ public class InspectWebAPI extends WebAPI {
} }
@Override @Override
public void sendRequest(String address, UUID receiverUUID) throws WebAPIException { public void sendRequest(String address) throws WebAPIException {
throw new IllegalStateException("Wrong method call for this WebAPI, call sendRequest(String, UUID, UUID) instead."); throw new IllegalStateException("Wrong method call for this WebAPI, call sendRequest(String, UUID, UUID) instead.");
} }
public void sendRequest(String address, UUID receiverUUID, UUID uuid) throws WebAPIException { public void sendRequest(String address, UUID uuid) throws WebAPIException {
addVariable("uuid", uuid.toString()); addVariable("uuid", uuid.toString());
super.sendRequest(address, receiverUUID); super.sendRequest(address);
} }
} }

View File

@ -0,0 +1,90 @@
/*
* 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.systems.webserver.webapi.bungee;
import main.java.com.djrapitops.plan.api.IPlan;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIException;
import main.java.com.djrapitops.plan.api.exceptions.WebAPINotFoundException;
import main.java.com.djrapitops.plan.systems.info.InformationManager;
import main.java.com.djrapitops.plan.systems.webserver.PageCache;
import main.java.com.djrapitops.plan.systems.webserver.response.NotFoundResponse;
import main.java.com.djrapitops.plan.systems.webserver.response.Response;
import main.java.com.djrapitops.plan.systems.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.systems.webserver.response.api.SuccessResponse;
import main.java.com.djrapitops.plan.systems.webserver.webapi.WebAPI;
import java.util.Map;
import java.util.UUID;
/**
* WebAPI for checking if a page is in webserver cache.
*
* @author Rsl1122
*/
public class IsCachedWebAPI extends WebAPI {
private final IPlan plugin;
public IsCachedWebAPI(IPlan plugin) {
this.plugin = plugin;
}
@Override
public Response onResponse(IPlan plugin, Map<String, String> variables) {
try {
String target = variables.get("target");
InformationManager infoManager = plugin.getInfoManager();
boolean cached = false;
switch (target) {
case "inspectPage":
if (infoManager.isCached(UUID.fromString(variables.get("uuid")))) {
cached = true;
}
break;
case "analysisPage":
if (infoManager.isAnalysisCached()) {
cached = true;
}
break;
default:
String error = "Faulty Target";
return PageCache.loadPage(error, () -> new BadRequestResponse(error));
}
if (cached) {
return PageCache.loadPage("success", SuccessResponse::new);
} else {
return PageCache.loadPage("fail", () -> new NotFoundResponse("Not Cached"));
}
} catch (NullPointerException e) {
return PageCache.loadPage(e.toString(), () -> new BadRequestResponse(e.toString()));
}
}
@Override
public void sendRequest(String address) throws WebAPIException {
throw new IllegalStateException("Wrong method call for this WebAPI, call sendRequest(String, UUID, UUID) instead.");
}
public boolean isInspectCached(String address, UUID uuid) throws WebAPIException {
addVariable("uuid", uuid.toString());
addVariable("target", "inspectPage");
try {
super.sendRequest(address);
return true;
} catch (WebAPINotFoundException e) {
return false;
}
}
public boolean isAnalysisCached(String address) throws WebAPIException {
addVariable("target", "analysisPage");
try {
super.sendRequest(address);
return true;
} catch (WebAPINotFoundException e) {
return false;
}
}
}

View File

@ -5,6 +5,7 @@
package main.java.com.djrapitops.plan.systems.webserver.webapi.bungee; package main.java.com.djrapitops.plan.systems.webserver.webapi.bungee;
import main.java.com.djrapitops.plan.api.IPlan; import main.java.com.djrapitops.plan.api.IPlan;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIException;
import main.java.com.djrapitops.plan.systems.info.InformationManager; import main.java.com.djrapitops.plan.systems.info.InformationManager;
import main.java.com.djrapitops.plan.systems.webserver.PageCache; import main.java.com.djrapitops.plan.systems.webserver.PageCache;
import main.java.com.djrapitops.plan.systems.webserver.response.AnalysisPageResponse; import main.java.com.djrapitops.plan.systems.webserver.response.AnalysisPageResponse;
@ -18,7 +19,7 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
/** /**
* WebAPI for posting Html pages such as Inspect, players or server pages. * WebAPI for posting Html pages such as Inspect or server pages.
* *
* @author Rsl1122 * @author Rsl1122
*/ */
@ -52,4 +53,22 @@ public class PostHtmlWebAPI extends WebAPI {
return PageCache.loadPage(e.toString(), () -> new BadRequestResponse(e.toString())); return PageCache.loadPage(e.toString(), () -> new BadRequestResponse(e.toString()));
} }
} }
@Override
public void sendRequest(String address) throws WebAPIException {
throw new IllegalStateException("Wrong method call for this WebAPI, call sendRequest(String, UUID, UUID) instead.");
}
public void sendInspectHtml(String address, UUID uuid, String html) throws WebAPIException {
addVariable("uuid", uuid.toString());
addVariable("html", html);
addVariable("target", "inspectPage");
super.sendRequest(address);
}
public void sendAnalysisHtml(String address, String html) throws WebAPIException {
addVariable("html", html);
addVariable("target", "analysisPage");
super.sendRequest(address);
}
} }

View File

@ -17,9 +17,6 @@ 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.systems.info.BukkitInformationManager; import main.java.com.djrapitops.plan.systems.info.BukkitInformationManager;
import main.java.com.djrapitops.plan.systems.info.InformationManager; import main.java.com.djrapitops.plan.systems.info.InformationManager;
import main.java.com.djrapitops.plan.systems.webserver.PageCache;
import main.java.com.djrapitops.plan.systems.webserver.response.AnalysisPageResponse;
import main.java.com.djrapitops.plan.systems.webserver.response.PlayersPageResponse;
import main.java.com.djrapitops.plan.utilities.Benchmark; import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.comparators.UserInfoLastPlayedComparator; import main.java.com.djrapitops.plan.utilities.comparators.UserInfoLastPlayedComparator;
@ -127,10 +124,6 @@ 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()));
PageCache.removeIf(identifier -> identifier.startsWith("inspectPage: ") || identifier.startsWith("inspectionJson: "));
PageCache.cachePage("analysisPage", () -> new AnalysisPageResponse(plugin.getInfoManager()));
PageCache.cachePage("players", PlayersPageResponse::new);
// TODO Export // TODO Export
// ExportUtility.export(analysisData, rawData); // ExportUtility.export(analysisData, rawData);
} catch (Exception e) { } catch (Exception e) {

View File

@ -1,39 +0,0 @@
/*
* 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.systems.webserver;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.api.exceptions.WebAPIException;
import main.java.com.djrapitops.plan.systems.webserver.webapi.WebAPI;
import main.java.com.djrapitops.plan.systems.webserver.webapi.universal.PingWebAPI;
import org.junit.Before;
import org.junit.Test;
import test.java.utils.TestInit;
import static org.junit.Assert.assertTrue;
/**
* //TODO Class Javadoc Comment
*
* @author Rsl1122
*/
public class WebAPITest {
private WebServer webServer;
@Before
public void setUp() throws Exception {
TestInit.initEmptyLocale();
webServer = new WebServer(null);
webServer.initServer();
assertTrue(webServer.isEnabled());
}
@Test
public void testPingWebAPI() throws WebAPIException {
WebAPI api = webServer.getWebAPI().getAPI(PingWebAPI.class);
api.sendRequest(webServer.getAccessAddress(), Plan.getServerUUID());
}
}