Refactored /players page to use ResolverService

Deprecated a lot of the old response factory methods
This commit is contained in:
Rsl1122 2020-02-13 23:28:13 +02:00 committed by Risto Lahtela
parent 2736ba042a
commit 2914966650
12 changed files with 194 additions and 126 deletions

View File

@ -57,6 +57,6 @@ public class PlayerJSONExporter extends FileExporter {
}
private void exportJSON(Path to, UUID playerUUID) throws IOException {
export(to, responseFactory.rawPlayerPageResponse(playerUUID).getContent());
export(to, responseFactory.rawPlayerPageResponse_old(playerUUID).getContent());
}
}

View File

@ -0,0 +1,59 @@
/*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan.delivery.rendering.pages;
import com.djrapitops.plan.delivery.formatting.PlaceholderReplacer;
import com.djrapitops.plan.delivery.rendering.html.Contributors;
import com.djrapitops.plan.delivery.rendering.html.icon.Icon;
import com.djrapitops.plan.version.VersionCheckSystem;
/**
* Page to display error stacktrace.
*
* @author Rsl1122
*/
public class ErrorMessagePage implements Page {
private final String template;
private final String errorTitle;
private final String errorMsg;
private final VersionCheckSystem versionCheckSystem;
public ErrorMessagePage(
String template, String errorTitle, String errorMsg,
VersionCheckSystem versionCheckSystem
) {
this.template = template;
this.errorTitle = errorTitle;
this.errorMsg = errorMsg;
this.versionCheckSystem = versionCheckSystem;
}
@Override
public String toHtml() {
PlaceholderReplacer placeholders = new PlaceholderReplacer();
placeholders.put("title", Icon.called("exclamation-circle") + " " + errorTitle);
placeholders.put("titleText", errorTitle);
placeholders.put("paragraph", errorMsg);
placeholders.put("version", versionCheckSystem.getUpdateButton().orElse(versionCheckSystem.getCurrentVersionButton()));
placeholders.put("updateModal", versionCheckSystem.getUpdateModal());
placeholders.put("contributors", Contributors.generateContributorHtml());
return placeholders.apply(template);
}
}

View File

@ -174,6 +174,16 @@ public class PageFactory {
}
}
public Page errorPage(String title, String error) {
try {
return new ErrorMessagePage(
getResource("web/error.html"), title, error,
versionCheckSystem.get());
} catch (IOException noParse) {
return internalErrorPage("Failed to create error message page for error: '" + error + "'", noParse);
}
}
public String getResource(String name) throws IOException {
return files.get().getCustomizableResourceOrDefault(name).asString();
}

View File

@ -167,7 +167,7 @@ public class RequestHandler implements HttpHandler {
}
private Optional<Response_old> createForbiddenResponse() {
return Optional.of(responseFactory.forbidden403("You have too many failed login attempts. Please wait 2 minutes until attempting again."));
return Optional.of(responseFactory.forbidden403_old("You have too many failed login attempts. Please wait 2 minutes until attempting again."));
}
private Authentication getAuthorization(Headers requestHeaders) {

View File

@ -92,7 +92,7 @@ public class ResponseResolver extends CompositePageResolver {
public void registerPages() {
resolverService.registerResolver("Plan", "/debug", debugPageResolver);
registerPage("players", playersPageResolver);
resolverService.registerResolver("Plan", "/players", playersPageResolver);
registerPage("player", playerPageResolver);
registerPage("network", serverPageResolver);
@ -108,16 +108,16 @@ public class ResponseResolver extends CompositePageResolver {
try {
return tryToGetResponse(request);
} catch (NotFoundException e) {
return responseFactory.notFound404(e.getMessage());
return responseFactory.notFound404_old(e.getMessage());
} catch (WebUserAuthException e) {
return responseFactory.basicAuthFail(e);
return responseFactory.basicAuthFail_old(e);
} catch (ForbiddenException e) {
return responseFactory.forbidden403(e.getMessage());
return responseFactory.forbidden403_old(e.getMessage());
} catch (BadRequestException e) {
return responseFactory.badRequest(e.getMessage(), request.getTargetString());
return responseFactory.badRequest_old(e.getMessage(), request.getTargetString());
} catch (Exception e) {
errorHandler.log(L.ERROR, this.getClass(), e);
return responseFactory.internalErrorResponse(e, request.getTargetString());
return responseFactory.internalErrorResponse_old(e, request.getTargetString());
}
}
@ -141,19 +141,19 @@ public class ResponseResolver extends CompositePageResolver {
boolean isAuthRequired = webServer.get().isAuthRequired();
if (isAuthRequired && !authentication.isPresent()) {
if (webServer.get().isUsingHTTPS()) {
return responseFactory.basicAuth();
return responseFactory.basicAuth_old();
} else {
return responseFactory.forbidden403();
return responseFactory.forbidden403_old();
}
}
if (!isAuthRequired || resolver.canAccess(authentication.get().getWebUser().toNewWebUser(), target, query)) {
return resolver.resolve(target, query).map(Response_old::from).orElseGet(responseFactory::pageNotFound404);
return resolver.resolve(target, query).map(Response_old::from).orElseGet(responseFactory::pageNotFound404_old);
} else {
return responseFactory.forbidden403();
return responseFactory.forbidden403_old();
}
} else {
return resolver.resolve(target, query).map(Response_old::from).orElseGet(responseFactory::pageNotFound404);
return resolver.resolve(target, query).map(Response_old::from).orElseGet(responseFactory::pageNotFound404_old);
}
}
@ -163,36 +163,36 @@ public class ResponseResolver extends CompositePageResolver {
String resource = target.getResourceString();
// TODO Turn into resolvers
if (target.endsWith(".css")) {
return responseFactory.cssResponse(resource);
return responseFactory.cssResponse_old(resource);
}
if (target.endsWith(".js")) {
return responseFactory.javaScriptResponse(resource);
return responseFactory.javaScriptResponse_old(resource);
}
if (target.endsWith(".png")) {
return responseFactory.imageResponse(resource);
return responseFactory.imageResponse_old(resource);
}
if (target.endsWith("favicon.ico")) {
return responseFactory.faviconResponse();
return responseFactory.faviconResponse_old();
}
if (target.endsWithAny(".woff", ".woff2", ".eot", ".ttf")) {
return responseFactory.fontResponse(resource);
return responseFactory.fontResponse_old(resource);
}
boolean isAuthRequired = webServer.get().isAuthRequired();
if (isAuthRequired && !authentication.isPresent()) {
if (webServer.get().isUsingHTTPS()) {
return responseFactory.basicAuth();
return responseFactory.basicAuth_old();
} else {
return responseFactory.forbidden403();
return responseFactory.forbidden403_old();
}
}
PageResolver pageResolver = getPageResolver(target);
if (pageResolver == null) {
return responseFactory.pageNotFound404();
return responseFactory.pageNotFound404_old();
} else {
if (!isAuthRequired || pageResolver.isAuthorized(authentication.get(), target)) {
return pageResolver.resolve(request, target);
}
return responseFactory.forbidden403();
return responseFactory.forbidden403_old();
}
}
}

View File

@ -90,7 +90,7 @@ public abstract class CompositePageResolver implements PageResolver {
PageResolver pageResolver = getPageResolver(target);
return pageResolver != null
? pageResolver.resolve(request, target)
: responseFactory.pageNotFound404();
: responseFactory.pageNotFound404_old();
}
@Deprecated

View File

@ -16,14 +16,8 @@
*/
package com.djrapitops.plan.delivery.webserver.pages;
import com.djrapitops.plan.delivery.domain.WebUser_old;
import com.djrapitops.plan.delivery.web.resolver.*;
import com.djrapitops.plan.delivery.webserver.Request;
import com.djrapitops.plan.delivery.webserver.RequestTarget;
import com.djrapitops.plan.delivery.webserver.auth.Authentication;
import com.djrapitops.plan.delivery.webserver.response.ResponseFactory;
import com.djrapitops.plan.delivery.webserver.response.Response_old;
import com.djrapitops.plan.exceptions.WebUserAuthException;
import javax.inject.Inject;
import javax.inject.Singleton;
@ -35,7 +29,7 @@ import java.util.Optional;
* @author Rsl1122
*/
@Singleton
public class DebugPageResolver implements PageResolver, Resolver {
public class DebugPageResolver implements Resolver {
private final ResponseFactory responseFactory;
@ -53,15 +47,4 @@ public class DebugPageResolver implements PageResolver, Resolver {
public Optional<Response> resolve(URIPath target, URIQuery query) {
return Optional.of(responseFactory.debugPageResponse());
}
@Override
public Response_old resolve(Request request, RequestTarget target) {
return responseFactory.debugPageResponse_old();
}
@Override
public boolean isAuthorized(Authentication auth, RequestTarget target) throws WebUserAuthException {
WebUser_old webUser = auth.getWebUser();
return webUser.getPermLevel() <= 0;
}
}

View File

@ -59,7 +59,7 @@ public class PlayerPageResolver implements PageResolver {
@Override
public Response_old resolve(Request request, RequestTarget target) throws WebException {
if (target.isEmpty()) {
return responseFactory.pageNotFound404();
return responseFactory.pageNotFound404_old();
}
String playerName = target.get(0);
@ -68,16 +68,16 @@ public class PlayerPageResolver implements PageResolver {
boolean raw = target.size() >= 2 && target.get(1).equalsIgnoreCase("raw");
if (playerUUID == null) {
return responseFactory.uuidNotFound404();
return responseFactory.uuidNotFound404_old();
}
Database.State dbState = dbSystem.getDatabase().getState();
if (dbState != Database.State.OPEN) {
throw new ForbiddenException("Database is " + dbState.name() + " - Please try again later. You can check database status with /plan info");
}
if (raw) {
return responseFactory.rawPlayerPageResponse(playerUUID);
return responseFactory.rawPlayerPageResponse_old(playerUUID);
}
return responseFactory.playerPageResponse(playerUUID);
return responseFactory.playerPageResponse_old(playerUUID);
}
@Override

View File

@ -16,19 +16,12 @@
*/
package com.djrapitops.plan.delivery.webserver.pages;
import com.djrapitops.plan.delivery.webserver.Request;
import com.djrapitops.plan.delivery.webserver.RequestTarget;
import com.djrapitops.plan.delivery.webserver.auth.Authentication;
import com.djrapitops.plan.delivery.web.resolver.*;
import com.djrapitops.plan.delivery.webserver.response.ResponseFactory;
import com.djrapitops.plan.delivery.webserver.response.Response_old;
import com.djrapitops.plan.exceptions.WebUserAuthException;
import com.djrapitops.plan.exceptions.connection.ForbiddenException;
import com.djrapitops.plan.exceptions.connection.WebException;
import com.djrapitops.plan.storage.database.DBSystem;
import com.djrapitops.plan.storage.database.Database;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Optional;
/**
* Resolves /players URL.
@ -36,31 +29,24 @@ import javax.inject.Singleton;
* @author Rsl1122
*/
@Singleton
public class PlayersPageResolver implements PageResolver {
public class PlayersPageResolver implements Resolver {
private final DBSystem dbSystem;
private final ResponseFactory responseFactory;
@Inject
public PlayersPageResolver(
DBSystem dbSystem,
ResponseFactory responseFactory
) {
this.dbSystem = dbSystem;
this.responseFactory = responseFactory;
}
@Override
public Response_old resolve(Request request, RequestTarget target) throws WebException {
Database.State dbState = dbSystem.getDatabase().getState();
if (dbState != Database.State.OPEN) {
throw new ForbiddenException("Database is " + dbState.name() + " - Please try again later. You can check database status with /plan info");
}
return responseFactory.playersPageResponse();
public boolean canAccess(WebUser permissions, URIPath target, URIQuery query) {
return permissions.hasPermission("page.players");
}
@Override
public boolean isAuthorized(Authentication auth, RequestTarget target) throws WebUserAuthException {
return auth.getWebUser().getPermLevel() <= 1;
public Optional<Response> resolve(URIPath target, URIQuery query) {
return Optional.of(responseFactory.playersPageResponse());
}
}

View File

@ -51,12 +51,12 @@ public class RootPageResolver implements PageResolver {
public Response_old resolve(Request request, RequestTarget target) throws WebException {
Server server = serverInfo.getServer();
if (!webServer.isAuthRequired()) {
return responseFactory.redirectResponse(server.isProxy() ? "network" : "server/" + Html.encodeToURL(server.getIdentifiableName()));
return responseFactory.redirectResponse_old(server.isProxy() ? "network" : "server/" + Html.encodeToURL(server.getIdentifiableName()));
}
Optional<Authentication> auth = request.getAuth();
if (!auth.isPresent()) {
return responseFactory.basicAuth();
return responseFactory.basicAuth_old();
}
WebUser_old webUser = auth.get().getWebUser();
@ -64,13 +64,13 @@ public class RootPageResolver implements PageResolver {
int permLevel = webUser.getPermLevel();
switch (permLevel) {
case 0:
return responseFactory.redirectResponse(server.isProxy() ? "network" : "server/" + Html.encodeToURL(server.getIdentifiableName()));
return responseFactory.redirectResponse_old(server.isProxy() ? "network" : "server/" + Html.encodeToURL(server.getIdentifiableName()));
case 1:
return responseFactory.redirectResponse("players");
return responseFactory.redirectResponse_old("players");
case 2:
return responseFactory.redirectResponse("player/" + Html.encodeToURL(webUser.getName()));
return responseFactory.redirectResponse_old("player/" + Html.encodeToURL(webUser.getName()));
default:
return responseFactory.forbidden403();
return responseFactory.forbidden403_old();
}
}

View File

@ -71,13 +71,13 @@ public class ServerPageResolver implements PageResolver {
if (serverUUID.isPresent()) {
checkDBState();
if (proxy && serverInfo.getServerUUID().equals(serverUUID.get())) {
return responseFactory.networkPageResponse();
return responseFactory.networkPageResponse_old();
}
return responseFactory.serverPageResponse(serverUUID.get());
return responseFactory.serverPageResponse_old(serverUUID.get());
} else {
// Redirect to base server page.
String directTo = proxy ? "/network" : "/server/" + Html.encodeToURL(serverInfo.getServer().getIdentifiableName());
return responseFactory.redirectResponse(webServer.get().getAccessAddress() + directTo);
return responseFactory.redirectResponse_old(webServer.get().getAccessAddress() + directTo);
}
}

View File

@ -21,12 +21,15 @@ import com.djrapitops.plan.delivery.rendering.pages.PageFactory;
import com.djrapitops.plan.delivery.web.resolver.MimeType;
import com.djrapitops.plan.delivery.web.resolver.Response;
import com.djrapitops.plan.delivery.webserver.response.errors.*;
import com.djrapitops.plan.delivery.webserver.response.pages.*;
import com.djrapitops.plan.delivery.webserver.response.pages.PageResponse;
import com.djrapitops.plan.delivery.webserver.response.pages.RawDataResponse;
import com.djrapitops.plan.delivery.webserver.response.pages.RawPlayerDataResponse;
import com.djrapitops.plan.exceptions.WebUserAuthException;
import com.djrapitops.plan.exceptions.connection.NotFoundException;
import com.djrapitops.plan.settings.locale.Locale;
import com.djrapitops.plan.settings.locale.lang.ErrorPageLang;
import com.djrapitops.plan.storage.database.DBSystem;
import com.djrapitops.plan.storage.database.Database;
import com.djrapitops.plan.storage.database.queries.containers.ContainerFetchQueries;
import com.djrapitops.plan.storage.file.PlanFiles;
import com.djrapitops.plan.version.VersionCheckSystem;
@ -34,6 +37,7 @@ import com.djrapitops.plan.version.VersionCheckSystem;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;
/**
@ -86,24 +90,31 @@ public class ResponseFactory {
.build();
}
public Response playersPageResponse() {
try {
Optional<Response> error = checkIfDBIsOpen();
if (error.isPresent()) return error.get();
return forPage(pageFactory.playersPage());
} catch (IOException e) {
return forInternalError("Failed to generate players page", e);
}
}
private Optional<Response> checkIfDBIsOpen() {
Database.State dbState = dbSystem.getDatabase().getState();
if (dbState != Database.State.OPEN) {
return Optional.of(Response.builder().setContent(pageFactory.errorPage(
"503 Resources Unavailable",
"Database is " + dbState.name() + " - Please try again later. You can check database status with /plan info"
).toHtml()).setMimeType(MimeType.HTML)
.setStatus(503)
.build());
}
return Optional.empty();
}
@Deprecated
public Response_old debugPageResponse_old() {
try {
return new DebugPageResponse(pageFactory.debugPage(), versionCheckSystem, files);
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate debug page");
}
}
public Response_old playersPageResponse() {
try {
return new PlayersPageResponse(pageFactory.playersPage());
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate players page");
}
}
public ErrorResponse internalErrorResponse(Throwable e, String s) {
public ErrorResponse internalErrorResponse_old(Throwable e, String s) {
try {
return new InternalErrorResponse(s, e, versionCheckSystem, files);
} catch (IOException improperRestartException) {
@ -115,47 +126,54 @@ public class ResponseFactory {
}
}
public Response_old networkPageResponse() {
@Deprecated
public Response_old networkPageResponse_old() {
try {
return new PageResponse(pageFactory.networkPage());
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate network page");
return internalErrorResponse_old(e, "Failed to generate network page");
}
}
public Response_old serverPageResponse(UUID serverUUID) throws NotFoundException {
@Deprecated
public Response_old serverPageResponse_old(UUID serverUUID) throws NotFoundException {
try {
return new PageResponse(pageFactory.serverPage(serverUUID));
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate server page");
return internalErrorResponse_old(e, "Failed to generate server page");
}
}
public RawDataResponse rawPlayerPageResponse(UUID uuid) {
@Deprecated
public RawDataResponse rawPlayerPageResponse_old(UUID uuid) {
return new RawPlayerDataResponse(dbSystem.getDatabase().query(ContainerFetchQueries.fetchPlayerContainer(uuid)));
}
public Response_old javaScriptResponse(String fileName) {
@Deprecated
public Response_old javaScriptResponse_old(String fileName) {
try {
return new JavaScriptResponse(fileName, files, locale);
} catch (IOException e) {
return notFound404("JS File not found from jar: " + fileName + ", " + e.toString());
return notFound404_old("JS File not found from jar: " + fileName + ", " + e.toString());
}
}
public Response_old cssResponse(String fileName) {
@Deprecated
public Response_old cssResponse_old(String fileName) {
try {
return new CSSResponse(fileName, files);
} catch (IOException e) {
return notFound404("CSS File not found from jar: " + fileName + ", " + e.toString());
return notFound404_old("CSS File not found from jar: " + fileName + ", " + e.toString());
}
}
public Response_old imageResponse(String fileName) {
@Deprecated
public Response_old imageResponse_old(String fileName) {
return new ByteResponse(ResponseType.IMAGE, FileResponse.format(fileName), files);
}
public Response_old fontResponse(String fileName) {
@Deprecated
public Response_old fontResponse_old(String fileName) {
ResponseType type = ResponseType.FONT_BYTESTREAM;
if (fileName.endsWith(".woff")) {
type = ResponseType.FONT_WOFF;
@ -175,74 +193,86 @@ public class ResponseFactory {
* @param location Starts with '/'
* @return Redirection response.
*/
public Response_old redirectResponse(String location) {
@Deprecated
public Response_old redirectResponse_old(String location) {
return new RedirectResponse(location);
}
public Response_old faviconResponse() {
@Deprecated
public Response_old faviconResponse_old() {
return new ByteResponse(ResponseType.X_ICON, "web/favicon.ico", files);
}
public ErrorResponse pageNotFound404() {
return notFound404(locale.getString(ErrorPageLang.UNKNOWN_PAGE_404));
@Deprecated
public ErrorResponse pageNotFound404_old() {
return notFound404_old(locale.getString(ErrorPageLang.UNKNOWN_PAGE_404));
}
public ErrorResponse uuidNotFound404() {
return notFound404(locale.getString(ErrorPageLang.UUID_404));
@Deprecated
public ErrorResponse uuidNotFound404_old() {
return notFound404_old(locale.getString(ErrorPageLang.UUID_404));
}
public ErrorResponse playerNotFound404() {
return notFound404(locale.getString(ErrorPageLang.NOT_PLAYED_404));
@Deprecated
public ErrorResponse playerNotFound404_old() {
return notFound404_old(locale.getString(ErrorPageLang.NOT_PLAYED_404));
}
public ErrorResponse notFound404(String message) {
@Deprecated
public ErrorResponse notFound404_old(String message) {
try {
return new NotFoundResponse(message, versionCheckSystem, files);
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate 404 page");
return internalErrorResponse_old(e, "Failed to generate 404 page");
}
}
public ErrorResponse basicAuthFail(WebUserAuthException e) {
@Deprecated
public ErrorResponse basicAuthFail_old(WebUserAuthException e) {
try {
return PromptAuthorizationResponse.getBasicAuthResponse(e, versionCheckSystem, files);
} catch (IOException jarReadFailed) {
return internalErrorResponse(e, "Failed to generate PromptAuthorizationResponse");
return internalErrorResponse_old(e, "Failed to generate PromptAuthorizationResponse");
}
}
public ErrorResponse forbidden403() {
return forbidden403("Your user is not authorized to view this page.<br>"
@Deprecated
public ErrorResponse forbidden403_old() {
return forbidden403_old("Your user is not authorized to view this page.<br>"
+ "If you believe this is an error contact staff to change your access level.");
}
public ErrorResponse forbidden403(String message) {
@Deprecated
public ErrorResponse forbidden403_old(String message) {
try {
return new ForbiddenResponse(message, versionCheckSystem, files);
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate ForbiddenResponse");
return internalErrorResponse_old(e, "Failed to generate ForbiddenResponse");
}
}
public ErrorResponse basicAuth() {
@Deprecated
public ErrorResponse basicAuth_old() {
try {
return PromptAuthorizationResponse.getBasicAuthResponse(versionCheckSystem, files);
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate PromptAuthorizationResponse");
return internalErrorResponse_old(e, "Failed to generate PromptAuthorizationResponse");
}
}
public BadRequestResponse badRequest(String errorMessage, String target) {
@Deprecated
public BadRequestResponse badRequest_old(String errorMessage, String target) {
return new BadRequestResponse(errorMessage + " (when requesting '" + target + "')");
}
public Response_old playerPageResponse(UUID playerUUID) {
@Deprecated
public Response_old playerPageResponse_old(UUID playerUUID) {
try {
return new PageResponse(pageFactory.playerPage(playerUUID));
} catch (IllegalStateException e) {
return playerNotFound404();
return playerNotFound404_old();
} catch (IOException e) {
return internalErrorResponse(e, "Failed to generate player page");
return internalErrorResponse_old(e, "Failed to generate player page");
}
}
}