diff --git a/build.gradle b/build.gradle index 29bf8a6e..257458df 100644 --- a/build.gradle +++ b/build.gradle @@ -1,184 +1,28 @@ plugins { - id "java" - id "com.qixalite.spongestart2" version "4.0.0" - id "ninja.miserable.blossom" version "1.0.1" - id "com.github.johnrengelman.shadow" version "2.0.1" + id "idea" + id "com.github.johnrengelman.shadow" version "2.0.1" apply false } -group = "valandur.webapi" -version = "${project.version}-S${project.spongeVersion}" - -blossom { - def locMain = "src/main/java/valandur/webapi/util/Constants.java" - replaceToken "@version@", project.version, locMain -} - -spongestart { - minecraft project.minecraftVersion - //spongeForgeVersion "1.12.2-2705-8.0.0-BETA-3398" - //spongeVanillaVersion "1.12.2-8.0.0-BETA-444" -} - -configurations.all { - // Exclude because included by Sponge/Minecraft - exclude group: "org.apache.commons" - exclude group: "com.google.common" - - resolutionStrategy { - force "com.google.guava:guava:23.0" - force "org.reflections:reflections:0.9.10" // Fixes some logging issues in 0.9.11 - } -} - -repositories { - mavenCentral() - maven { - url "https://repo.spongepowered.org/maven/" - } - maven { - url "http://repo.bstats.org/content/repositories/releases/" - } - maven { - url = "http://repo.aikar.co/nexus/content/groups/aikar/" - } - flatDir { - dirs "lib" +allprojects { + repositories { + mavenLocal() + mavenCentral() } } -dependencies { - compile project(":webapi-lib") - - compile group: "co.aikar", name: "minecraft-timings", version: "1.0.4" - - compile group: "com.fasterxml.jackson.core", name: "jackson-core", version: project.jacksonVersion - compile group: "com.fasterxml.jackson.core", name: "jackson-databind", version: project.jacksonVersion - compile group: "com.fasterxml.jackson.core", name: "jackson-annotations", version: project.jacksonVersion - compile group: "com.fasterxml.jackson.dataformat", name: "jackson-dataformat-xml", version: project.jacksonVersion - compile group: "com.fasterxml.jackson.jaxrs", name: "jackson-jaxrs-json-provider", version: project.jacksonVersion - // compile group: "io.swagger.core.v3", name: "swagger-jaxrs2", version: "2.0.0-rc3" // This if for Swagger 3.0 - - compile group: "org.codehaus.woodstox", name: "woodstox-core-asl", version: "4.4.1" - - compile group: "org.eclipse.jetty", name: "jetty-server", version: project.jettyVersion - compile group: "org.eclipse.jetty", name: "jetty-servlet", version: project.jettyVersion - compile group: "org.eclipse.jetty", name: "jetty-rewrite", version: project.jettyVersion - compile group: "org.eclipse.jetty.websocket", name: "websocket-server", version: project.jettyVersion - compile group: "org.eclipse.jetty.websocket", name: "websocket-servlet", version: project.jettyVersion - compile group: "org.eclipse.jetty.websocket", name: "websocket-client", version: project.jettyVersion - - compile group: "io.swagger", name: "swagger-jersey2-jaxrs", version: "1.5.18" - compile group: "io.sentry", name: "sentry", version: "1.6.4" - - compile group: "org.mindrot", name: "jbcrypt", version: "0.4" - compile group: "org.glassfish.jersey.containers", name: "jersey-container-servlet", version: "2.26" - compile group: "org.glassfish.jersey.inject", name: "jersey-hk2", version: "2.26" - compile group: "org.bstats", name: "bstats-sponge", version: "1.4" - - compileOnly group: "org.spongepowered", name: "spongeapi", version: "${project.spongeVersion}-SNAPSHOT" - - compile group: 'redis.clients', name: 'jedis', version: '2.9.0' - compile group: 'com.rabbitmq', name: 'amqp-client', version: '5.3.0' - - // Integrations - compileOnly name: "ActiveTime-s7.1-v1.4.3" - compileOnly name: "CmdScheduler-s7.1-v1.1.1" - compileOnly name: "GWMLibrary 1.3.4" - compileOnly name: "GWMCrates 3.1.13" - compileOnly name: "MMCRestrict-1.7.1-API-7" - compileOnly name: "MMCTickets-2.0.7-API-7" - compileOnly name: "Nucleus-1.12.1-S7.1-api" - compileOnly name: "RedProtect-7.5.5-b130-Universal" - compileOnly name: "UniversalMarket-1.12.2-v1.3" - compileOnly name: "VillagerShops-2.0.1" - compileOnly name: "WebBooks" -} - -shadowJar { - configurations = [project.configurations.compile] +subprojects { + apply plugin: "java" + apply plugin: "com.github.johnrengelman.shadow" - mergeServiceFiles() + group = "valandur.webapi" + version = "${project.version}-S${project.spongeVersion}" - duplicatesStrategy = DuplicatesStrategy.EXCLUDE + sourceCompatibility = 1.8 + targetCompatibility = 1.8 - relocate "co.aikar.timings.lib", "valandur.webapi.shadow.co.aikar.timings.lib" - - relocate "com.ctc", "valandur.webapi.shadow.com.ctc" - relocate "com.fasterxml", "valandur.webapi.shadow.com.fasterxml" - - relocate "com.google.errorprone", "valandur.webapi.shadow.com.google.errorprone" - relocate "com.google.j2objc", "valandur.webapi.shadow.com.google.j2objc" - relocate "com.google.thirdparty", "valandur.webapi.shadow.com.google.thirdparty" - - relocate "com.sun.research", "valandur.webapi.shadow.com.sun.research" - - relocate "edu.umd.cs.findbugs.annotations", "valandur.webapi.shadow.edu.umd.cs.findbugs.annotations" - - relocate "io.sentry", "valandur.webapi.shadow.io.sentry" - relocate "io.swagger", "valandur.webapi.shadow.io.swagger" - - relocate "javassist", "valandur.webapi.shadow.javassist" - - relocate "javax.annotation", "valandur.webapi.shadow.javax.annotation" - relocate "javax.inject", "valandur.webapi.shadow.javax.inject" - relocate "javax.servlet", "valandur.webapi.shadow.javax.servlet" - relocate "javax.validation", "valandur.webapi.shadow.javax.validation" - relocate "javax.ws", "valandur.webapi.shadow.javax.ws" - relocate "javax.xml.stream", "valandur.webapi.shadow.javax.xml.stream" - - relocate "jersey.repackaged", "valandur.webapi.shadow.jersey.repackaged" - - relocate "net.jcip.annotations", "valandur.webapi.shadow.net.jcip.annotations" - - relocate "org.aopalliance", "valandur.webapi.shadow.org.aopalliance" - relocate "org.codehaus", "valandur.webapi.shadow.org.codehaus" - relocate "org.threeten", "valandur.webapi.shadow.org.threeten" - - relocate "org.eclipse.jetty.http", "valandur.webapi.shadow.org.eclipse.jetty.http" - relocate "org.eclipse.jetty.io", "valandur.webapi.shadow.org.eclipse.jetty.io" - relocate "org.eclipse.jetty.rewrite", "valandur.webapi.shadow.org.eclipse.jetty.rewrite" - relocate "org.eclipse.jetty.security", "valandur.webapi.shadow.org.eclipse.jetty.security" - relocate "org.eclipse.jetty.server", "valandur.webapi.shadow.org.eclipse.jetty.server" - relocate "org.eclipse.jetty.servlet", "valandur.webapi.shadow.org.eclipse.jetty.servlet" - relocate "org.eclipse.jetty.util", "valandur.webapi.shadow.org.eclipse.jetty.util" - relocate "org.eclipse.jetty.version", "valandur.webapi.shadow.org.eclipse.jetty.version" - - relocate "org.glassfish", "valandur.webapi.shadow.org.glassfish" - relocate "org.intellij", "valandur.webapi.shadow.org.intellij" - relocate "org.jetbrains", "valandur.webapi.shadow.org.jetbrains" - relocate "org.jvnet", "valandur.webapi.shadow.org.jvnet" - relocate "org.mindrot", "valandur.webapi.shadow.org.mindrot" - relocate "org.reflections", "valandur.webapi.shadow.org.reflections" - - relocate "org.slf4j.event", "valandur.webapi.shadow.org.slf4j.event" - relocate "org.slf4j.helpers", "valandur.webapi.shadow.org.slf4j.helpers" - relocate "org.slf4j.spi", "valandur.webapi.shadow.org.slf4j.spi" - - relocate "org.yaml", "valandur.webapi.shadow.org.yaml" - - // Provided by Sponge/Minecraft - dependencies { - exclude(dependency("org.apache.commons.*:")) - exclude(dependency("com.google.guava.*:")) - exclude(dependency("org.slf4j.*:")) + repositories { + maven { + url "https://repo.spongepowered.org/maven/" + } } - - exclude "/about.html" - exclude "/jetty-dir.css" - exclude "/org/eclipse/jetty/favicon.ico" - - archiveName = "webapi-${version}.jar" -} - -task copyJars(type: Copy) { - from([shadowJar]) - into project.file("artifacts") -} -copyJars.dependsOn(shadowJar) - -artifacts { - archives shadowJar -} - -build.dependsOn(shadowJar) -build.dependsOn(copyJars) +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 8a22e754..16ba2bf6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,7 @@ -version=5.4.1 +version=5.4.2 + minecraftVersion=1.12.2 spongeVersion=7.1.0 + jacksonVersion=2.9.4 jettyVersion=9.4.8.v20171121 diff --git a/settings.gradle b/settings.gradle index 506dff31..a0679c58 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,3 +1,5 @@ -include 'webapi-server' -include 'webapi-lib' +rootProject.name = "webapi" +include "webapi-server" +include "webapi-lib" +include "webapi-sponge" diff --git a/webapi-lib/build.gradle b/webapi-lib/build.gradle index c9c99de1..58e43003 100644 --- a/webapi-lib/build.gradle +++ b/webapi-lib/build.gradle @@ -1,19 +1,3 @@ -plugins { - id 'java' -} - -group 'valandur.webapi' -version = "${project.version}-S${project.spongeVersion}" - -sourceCompatibility = 1.8 - -repositories { - mavenCentral() - maven { - url "https://repo.spongepowered.org/maven/" - } -} - dependencies { compileOnly group: "com.fasterxml.jackson.core", name: "jackson-annotations", version: project.jacksonVersion diff --git a/webapi-server/build.gradle b/webapi-server/build.gradle index 3bf8e9f3..9a3570da 100644 --- a/webapi-server/build.gradle +++ b/webapi-server/build.gradle @@ -1,20 +1,3 @@ -plugins { - id 'java' - id "com.github.johnrengelman.shadow" -} - -group = "valandur.webapi" -version = "${project.version}-S${project.spongeVersion}" - -sourceCompatibility = 1.8 - -repositories { - mavenCentral() - maven { - url "https://repo.spongepowered.org/maven/" - } -} - dependencies { compile project(":webapi-lib") diff --git a/webapi-sponge/build.gradle b/webapi-sponge/build.gradle new file mode 100644 index 00000000..630a01f2 --- /dev/null +++ b/webapi-sponge/build.gradle @@ -0,0 +1,154 @@ +plugins { + id "com.qixalite.spongestart2" version "4.0.0" + id "ninja.miserable.blossom" version "1.0.1" +} + +blossom { + def locMain = "src/main/java/valandur/webapi/util/Constants.java" + replaceToken "@version@", project.version, locMain +} + +spongestart { + minecraft project.minecraftVersion + //spongeForgeVersion "1.12.2-2705-8.0.0-BETA-3398" + //spongeVanillaVersion "1.12.2-8.0.0-BETA-444" +} + +configurations.all { + // Exclude because included by Sponge/Minecraft + exclude group: "org.apache.commons" + exclude group: "com.google.common" + + resolutionStrategy { + force "com.google.guava:guava:23.0" + force "org.reflections:reflections:0.9.10" // Fixes some logging issues in 0.9.11 + } +} + +repositories { + maven { + url "http://repo.bstats.org/content/repositories/releases/" + } + maven { + url = "http://repo.aikar.co/nexus/content/groups/aikar/" + } + flatDir { + dirs "lib" + } +} + +dependencies { + compile project(":webapi-lib") + + compile group: "co.aikar", name: "minecraft-timings", version: "1.0.4" + + compile group: "com.fasterxml.jackson.core", name: "jackson-core", version: project.jacksonVersion + compile group: "com.fasterxml.jackson.core", name: "jackson-databind", version: project.jacksonVersion + compile group: "com.fasterxml.jackson.core", name: "jackson-annotations", version: project.jacksonVersion + compile group: "com.fasterxml.jackson.dataformat", name: "jackson-dataformat-xml", version: project.jacksonVersion + compile group: "com.fasterxml.jackson.jaxrs", name: "jackson-jaxrs-json-provider", version: project.jacksonVersion + // compile group: "io.swagger.core.v3", name: "swagger-jaxrs2", version: "2.0.0-rc3" // This if for Swagger 3.0 + + compile group: "org.codehaus.woodstox", name: "woodstox-core-asl", version: "4.4.1" + + compile group: "org.eclipse.jetty", name: "jetty-server", version: project.jettyVersion + compile group: "org.eclipse.jetty", name: "jetty-servlet", version: project.jettyVersion + compile group: "org.eclipse.jetty", name: "jetty-rewrite", version: project.jettyVersion + compile group: "org.eclipse.jetty.websocket", name: "websocket-server", version: project.jettyVersion + compile group: "org.eclipse.jetty.websocket", name: "websocket-servlet", version: project.jettyVersion + compile group: "org.eclipse.jetty.websocket", name: "websocket-client", version: project.jettyVersion + + compile group: "io.swagger", name: "swagger-jersey2-jaxrs", version: "1.5.18" + // compile group: "io.sentry", name: "sentry", version: "1.6.4" + + compile group: "org.mindrot", name: "jbcrypt", version: "0.4" + compile group: "org.glassfish.jersey.containers", name: "jersey-container-servlet", version: "2.26" + compile group: "org.glassfish.jersey.inject", name: "jersey-hk2", version: "2.26" + compile group: "org.bstats", name: "bstats-sponge", version: "1.4" + + compileOnly group: "org.spongepowered", name: "spongeapi", version: "${project.spongeVersion}-SNAPSHOT" + + compile group: 'redis.clients', name: 'jedis', version: '2.9.0' + compile group: 'com.rabbitmq', name: 'amqp-client', version: '5.3.0' + + // Integrations + compileOnly name: "ActiveTime-s7.1-v1.4.3" + compileOnly name: "CmdScheduler-s7.1-v1.1.1" + compileOnly name: "GWMLibrary 1.3.4" + compileOnly name: "GWMCrates 3.1.13" + compileOnly name: "MMCRestrict-1.7.1-API-7" + compileOnly name: "MMCTickets-2.0.7-API-7" + compileOnly name: "Nucleus-1.12.1-S7.1-api" + compileOnly name: "RedProtect-7.5.5-b130-Universal" + compileOnly name: "UniversalMarket-1.12.2-v1.3" + compileOnly name: "VillagerShops-2.0.1" + compileOnly name: "WebBooks" +} + +shadowJar { + configurations = [project.configurations.compile] + + mergeServiceFiles() + + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + + relocate ("com", "valandur.webapi.shadow.com") { + include "com.ctc.*" + include "com.fasterxml.*" + include "com.google.errorprone.*" + include "com.google.j2objc.*" + include "com.google.thirdparty.*" + include "com.sun.research.*" + include "com.rabbitmq.*" + } + relocate ("co", "valandur.webapi.shadow.co") { + include "co.aikar.timings.lib.*" + } + relocate "edu", "valandur.webapi.shadow.edu" + relocate "io", "valandur.webapi.shadow.io" + relocate "net", "valandur.webapi.shadow.net" + relocate "javassist", "valandur.webapi.shadow.javassist" + relocate ("javax", "valandur.webapi.shadow.javax") { + include "javax.annotation.*" + include "javax.inject.*" + include "javax.servlet.*" + include "javax.validation.*" + include "javax.ws.*" + include "javax.xml.stream.*" + } + relocate "jersey", "valandur.webapi.shadow.jersey" + relocate ("org", "valandur.webapi.shadow.org") { + exclude "org.spongepowered.*" + exclude "org.slf4j.*" + exclude "org.w3c.*" + exclude "org.apache.commons.*" + exclude "org.xml.sax.*" + } + relocate "redis", "valandur.webapi.shadow.redis" + + // Provided by Sponge/Minecraft + dependencies { + exclude(dependency("org.apache.commons.*:")) + exclude(dependency("com.google.guava.*:")) + exclude(dependency("org.slf4j.*:")) + } + + exclude "/about.html" + exclude "/jetty-dir.css" + exclude "/org/eclipse/jetty/favicon.ico" + + archiveName = "webapi-${version}.jar" +} + +task copyJars(type: Copy) { + from([shadowJar]) + into project.file("${rootDir}/artifacts") +} +copyJars.dependsOn(shadowJar) + +artifacts { + archives shadowJar +} + +build.dependsOn(shadowJar) +build.dependsOn(copyJars) diff --git a/lib/ActiveTime-s7.1-v1.4.3.jar b/webapi-sponge/lib/ActiveTime-s7.1-v1.4.3.jar similarity index 100% rename from lib/ActiveTime-s7.1-v1.4.3.jar rename to webapi-sponge/lib/ActiveTime-s7.1-v1.4.3.jar diff --git a/lib/CmdScheduler-s7.1-v1.1.1.jar b/webapi-sponge/lib/CmdScheduler-s7.1-v1.1.1.jar similarity index 100% rename from lib/CmdScheduler-s7.1-v1.1.1.jar rename to webapi-sponge/lib/CmdScheduler-s7.1-v1.1.1.jar diff --git a/lib/GWMCrates 3.1.13.jar b/webapi-sponge/lib/GWMCrates 3.1.13.jar similarity index 100% rename from lib/GWMCrates 3.1.13.jar rename to webapi-sponge/lib/GWMCrates 3.1.13.jar diff --git a/lib/GWMLibrary 1.3.4.jar b/webapi-sponge/lib/GWMLibrary 1.3.4.jar similarity index 100% rename from lib/GWMLibrary 1.3.4.jar rename to webapi-sponge/lib/GWMLibrary 1.3.4.jar diff --git a/lib/MMCRestrict-1.7.1-API-7.jar b/webapi-sponge/lib/MMCRestrict-1.7.1-API-7.jar similarity index 100% rename from lib/MMCRestrict-1.7.1-API-7.jar rename to webapi-sponge/lib/MMCRestrict-1.7.1-API-7.jar diff --git a/lib/MMCTickets-2.0.7-API-7.jar b/webapi-sponge/lib/MMCTickets-2.0.7-API-7.jar similarity index 100% rename from lib/MMCTickets-2.0.7-API-7.jar rename to webapi-sponge/lib/MMCTickets-2.0.7-API-7.jar diff --git a/lib/Nucleus-1.12.1-S7.1-api.jar b/webapi-sponge/lib/Nucleus-1.12.1-S7.1-api.jar similarity index 100% rename from lib/Nucleus-1.12.1-S7.1-api.jar rename to webapi-sponge/lib/Nucleus-1.12.1-S7.1-api.jar diff --git a/lib/RedProtect-7.5.5-b130-Universal.jar b/webapi-sponge/lib/RedProtect-7.5.5-b130-Universal.jar similarity index 100% rename from lib/RedProtect-7.5.5-b130-Universal.jar rename to webapi-sponge/lib/RedProtect-7.5.5-b130-Universal.jar diff --git a/lib/UniversalMarket-1.12.2-v1.3.jar b/webapi-sponge/lib/UniversalMarket-1.12.2-v1.3.jar similarity index 100% rename from lib/UniversalMarket-1.12.2-v1.3.jar rename to webapi-sponge/lib/UniversalMarket-1.12.2-v1.3.jar diff --git a/lib/VillagerShops-1.9.1.jar b/webapi-sponge/lib/VillagerShops-1.9.1.jar similarity index 100% rename from lib/VillagerShops-1.9.1.jar rename to webapi-sponge/lib/VillagerShops-1.9.1.jar diff --git a/lib/VillagerShops-2.0.1.jar b/webapi-sponge/lib/VillagerShops-2.0.1.jar similarity index 100% rename from lib/VillagerShops-2.0.1.jar rename to webapi-sponge/lib/VillagerShops-2.0.1.jar diff --git a/lib/WebBooks.jar b/webapi-sponge/lib/WebBooks.jar similarity index 100% rename from lib/WebBooks.jar rename to webapi-sponge/lib/WebBooks.jar diff --git a/src/main/java/valandur/webapi/WebAPI.java b/webapi-sponge/src/main/java/valandur/webapi/WebAPI.java similarity index 96% rename from src/main/java/valandur/webapi/WebAPI.java rename to webapi-sponge/src/main/java/valandur/webapi/WebAPI.java index 2a60c802..b4fe1857 100644 --- a/src/main/java/valandur/webapi/WebAPI.java +++ b/webapi-sponge/src/main/java/valandur/webapi/WebAPI.java @@ -1,622 +1,623 @@ -package valandur.webapi; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.reflect.TypeToken; -import com.google.inject.Inject; -import io.sentry.Sentry; -import io.sentry.context.Context; -import io.swagger.converter.ModelConverters; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; -import org.bstats.sponge.Metrics2; -import org.eclipse.jetty.util.log.Log; -import org.slf4j.Logger; -import org.spongepowered.api.Platform; -import org.spongepowered.api.Platform.Component; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.CommandManager; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.config.ConfigDir; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.EventManager; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.Order; -import org.spongepowered.api.event.game.GameReloadEvent; -import org.spongepowered.api.event.game.state.*; -import org.spongepowered.api.plugin.Plugin; -import org.spongepowered.api.plugin.PluginContainer; -import org.spongepowered.api.scheduler.SpongeExecutorService; -import org.spongepowered.api.service.ServiceManager; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; -import valandur.webapi.block.BlockOperation; -import valandur.webapi.block.BlockOperationStatusChangeEvent; -import valandur.webapi.block.BlockService; -import valandur.webapi.cache.CacheService; -import valandur.webapi.command.CommandRegistry; -import valandur.webapi.command.CommandSource; -import valandur.webapi.config.BaseConfig; -import valandur.webapi.config.MainConfig; -import valandur.webapi.hook.WebHook; -import valandur.webapi.hook.WebHookSerializer; -import valandur.webapi.hook.WebHookService; -import valandur.webapi.link.LinkService; -import valandur.webapi.link.internal.InternalHttpRequest; -import valandur.webapi.link.internal.InternalHttpResponse; -import valandur.webapi.link.message.RequestMessage; -import valandur.webapi.link.message.ResponseMessage; -import valandur.webapi.message.InteractiveMessageService; -import valandur.webapi.security.PermissionStruct; -import valandur.webapi.security.PermissionStructSerializer; -import valandur.webapi.security.SecurityService; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.server.ServerService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.ServletService; -import valandur.webapi.swagger.SwaggerModelConverter; -import valandur.webapi.user.UserPermissionStruct; -import valandur.webapi.user.UserPermissionStructSerializer; -import valandur.webapi.user.UserService; -import valandur.webapi.util.Constants; -import valandur.webapi.util.JettyLogger; -import valandur.webapi.util.Timings; - -import javax.net.ssl.HttpsURLConnection; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.WebApplicationException; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -@Plugin( - id = Constants.ID, - version = Constants.VERSION, - name = Constants.NAME, - url = Constants.URL, - description = Constants.DESCRIPTION, - authors = { - "Valandur" - } -) -public class WebAPI { - - static { - System.out.println("Static initialized"); - } - - private static WebAPI instance; - public static WebAPI getInstance() { - return WebAPI.instance; - } - - private static SpongeExecutorService syncExecutor; - private static SpongeExecutorService asyncExecutor; - - private boolean devMode = false; - public static boolean isDevMode() { - return WebAPI.getInstance().devMode; - } - - private boolean adminPanelEnabled = true; - public static boolean isAdminPanelEnabled() { - return WebAPI.getInstance().adminPanelEnabled; - } - - private static String spongeApi; - private static String spongeGame; - private static String spongeImpl; - private static String pluginList; - - private static WebServer server; - - @Inject - private Metrics2 metrics; - - @Inject - private Logger logger; - public static Logger getLogger() { - return WebAPI.getInstance().logger; - } - - @Inject - @ConfigDir(sharedRoot = false) - private Path configPath; - public static Path getConfigPath() { - return WebAPI.getInstance().configPath; - } - - @Inject - private PluginContainer container; - public static PluginContainer getContainer() { - return WebAPI.getInstance().container; - } - - private boolean reportErrors; - public static boolean reportErrors() { - return WebAPI.getInstance() == null || WebAPI.getInstance().reportErrors; - } - - // Services - private BlockService blockService; - public static BlockService getBlockService() { - return WebAPI.getInstance().blockService; - } - - private CacheService cacheService; - public static CacheService getCacheService() { - return WebAPI.getInstance().cacheService; - } - - private SerializeService serializeService; - public static SerializeService getSerializeService() { - return WebAPI.getInstance().serializeService; - } - - private InteractiveMessageService messageService; - public static InteractiveMessageService getMessageService() { - return WebAPI.getInstance().messageService; - } - - private LinkService linkService; - public static LinkService getLinkService() { - return WebAPI.getInstance().linkService; - } - - private SecurityService securityService; - public static SecurityService getSecurityService() { - return WebAPI.getInstance().securityService; - } - - private ServerService serverService; - public static ServerService getServerService() { - return WebAPI.getInstance().serverService; - } - - private ServletService servletService; - public static ServletService getServletService() { - return WebAPI.getInstance().servletService; - } - - private UserService userService; - public static UserService getUserService() { - return WebAPI.getInstance().userService; - } - - private WebHookService webHookService; - public static WebHookService getWebHookService() { - return WebAPI.getInstance().webHookService; - } - - - - public WebAPI() { - System.setProperty("sentry.dsn", "https://fb64795d2a5c4ff18f3c3e4117d7c245:53cf4ea85ae44608ab5b189f0c07b3f1@sentry.io/203545"); - System.setProperty("sentry.release", Constants.VERSION.split("-")[0]); - System.setProperty("sentry.maxmessagelength", "2000"); - System.setProperty("sentry.stacktrace.app.packages", WebAPI.class.getPackage().getName()); - } - - @Listener - public void onPreInitialization(GamePreInitializationEvent event) { - WebAPI.instance = this; - - Timings.STARTUP.startTiming(); - - Platform platform = Sponge.getPlatform(); - spongeApi = platform.getContainer(Component.API).getVersion().orElse(null); - spongeGame = platform.getContainer(Component.GAME).getVersion().orElse(null); - spongeImpl = platform.getContainer(Component.IMPLEMENTATION).getVersion().orElse(null); - pluginList = Sponge.getPluginManager().getPlugins().stream() - .map(p -> p.getId() + ": " + p.getVersion().orElse(null)) - .collect(Collectors.joining("; \n")); - - // Create our config directory if it doesn't exist - if (!Files.exists(configPath)) { - try { - Files.createDirectories(configPath); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // Reusable sync executor to run code on main server thread - syncExecutor = Sponge.getScheduler().createSyncExecutor(this); - asyncExecutor = Sponge.getScheduler().createAsyncExecutor(this); - - // Register custom serializers - TypeSerializers.getDefaultSerializers().registerType( - TypeToken.of(WebHook.class), new WebHookSerializer()); - TypeSerializers.getDefaultSerializers().registerType( - TypeToken.of(UserPermissionStruct.class), new UserPermissionStructSerializer()); - TypeSerializers.getDefaultSerializers().registerType( - TypeToken.of(PermissionStruct.class), new PermissionStructSerializer()); - - // Setup services - this.blockService = new BlockService(); - this.cacheService = new CacheService(); - this.linkService = new LinkService(); - this.messageService = new InteractiveMessageService(); - this.securityService = new SecurityService(); - this.serializeService = new SerializeService(); - this.serverService = new ServerService(); - this.servletService = new ServletService(); - this.webHookService = new WebHookService(); - this.userService = new UserService(); - - // Register services - ServiceManager serviceMan = Sponge.getServiceManager(); - serviceMan.setProvider(this, BlockService.class, blockService); - serviceMan.setProvider(this, CacheService.class, cacheService); - serviceMan.setProvider(this, LinkService.class, linkService); - serviceMan.setProvider(this, InteractiveMessageService.class, messageService); - serviceMan.setProvider(this, SecurityService.class, securityService); - serviceMan.setProvider(this, SerializeService.class, serializeService); - serviceMan.setProvider(this, ServerService.class, serverService); - serviceMan.setProvider(this, ServletService.class, servletService); - serviceMan.setProvider(this, WebHookService.class, webHookService); - serviceMan.setProvider(this, UserService.class, userService); - - // Register events of services - EventManager evenMan = Sponge.getEventManager(); - evenMan.registerListeners(this, cacheService); - evenMan.registerListeners(this, linkService); - evenMan.registerListeners(this, webHookService); - - // Swagger setup stuff - ModelConverters.getInstance().addConverter(new SwaggerModelConverter()); - - Timings.STARTUP.stopTiming(); - } - @Listener - public void onInitialization(GameInitializationEvent event) { - Timings.STARTUP.startTiming(); - - logger.info(Constants.NAME + " v" + Constants.VERSION + " is starting..."); - - logger.info("Setting up jetty logger..."); - Log.setLog(new JettyLogger()); - - // Main init function, that is also called when reloading the plugin - init(null); - - logger.info(Constants.NAME + " ready"); - - Timings.STARTUP.stopTiming(); - } - @Listener(order = Order.POST) - public void onPostInitialization(GamePostInitializationEvent event) { - Timings.STARTUP.startTiming(); - - // Load base data - cacheService.updateWorlds(); - cacheService.updatePlugins(); - cacheService.updateCommands(); - - Timings.STARTUP.stopTiming(); - } - - // Reusable setup function, for starting and reloading - private void init(Player triggeringPlayer) { - Timings.STARTUP.startTiming(); - - logger.info("Loading configuration..."); - - Path configPath = WebAPI.getConfigPath().resolve("config.conf").normalize(); - MainConfig mainConfig = BaseConfig.load(configPath, new MainConfig()); - - // Save important config values to variables - devMode = mainConfig.devMode; - reportErrors = mainConfig.reportErrors; - adminPanelEnabled = mainConfig.adminPanel; - - // Create our WebServer - server = new WebServer(logger, mainConfig); - - if (devMode) { - logger.warn("Web-API IS RUNNING IN DEV MODE. ERROR REPORTING IS OFF!"); - reportErrors = false; - } - - // Use the container instead of VERSION so the compiler doesn't remove it because it's constant - if (this.container.getVersion().orElse("").equalsIgnoreCase("@version@")) { - logger.warn("Web-API VERSION SIGNALS DEV MODE. ERROR REPORTING IS OFF!"); - reportErrors = false; - } - - if (reportErrors) { - Sentry.init(); - } - - blockService.init(); - - cacheService.init(); - - linkService.init(); - - securityService.init(); - - serializeService.init(); - - serverService.init(); - - servletService.init(); - - userService.init(); - - webHookService.init(); - - CommandRegistry.init(); - - if (triggeringPlayer != null) { - triggeringPlayer.sendMessage(Text.builder().color(TextColors.AQUA) - .append(Text.of("[" + Constants.NAME + "] " + Constants.NAME + " has been reloaded!")) - .build()); - } - - Timings.STARTUP.stopTiming(); - } - - private void checkForUpdates() { - if (devMode) { - logger.warn("SKIPPING UPDATE CHECK IN DEV MODE"); - return; - } - - asyncExecutor.execute(() -> { - HttpsURLConnection connection = null; - try { - java.net.URL url = new URL(Constants.UPDATE_URL); - connection = (HttpsURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - connection.setRequestProperty("User-Agent", "Web-API"); - connection.setRequestProperty("accept", "application/json"); - connection.setRequestProperty("charset", "utf-8"); - connection.setUseCaches(false); - - //Get Response - int code = connection.getResponseCode(); - if (code != 200) { - logger.warn("Could not check for updates: " + code); - return; - } - - InputStream is = connection.getInputStream(); - BufferedReader rd = new BufferedReader(new InputStreamReader(is)); - StringBuilder response = new StringBuilder(); - String line; - while ((line = rd.readLine()) != null) { - response.append(line); - response.append('\r'); - } - rd.close(); - - String respString = response.toString().trim(); - if (respString.isEmpty() || respString.equalsIgnoreCase("OK")) { - logger.warn("Empty response received when checking for updates"); - return; - } - - ObjectMapper map = new ObjectMapper(); - JsonNode resp = map.readTree(respString); - - String version = container.getVersion().orElse("").split("-")[0]; - String newVersion = resp.get("tag_name").asText().substring(1).split("-")[0]; - - if (newVersion.equalsIgnoreCase(version)) { - return; - } - - String[] changes = resp.get("body").asText().split("\n"); - - logger.warn("------- Web-API Update -------"); - logger.warn("Latest: " + newVersion); - logger.warn("Current: " + version); - logger.warn("---------- Changes -----------"); - for (String change : changes) - logger.warn(change); - logger.warn("------------------------------"); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (connection != null) { - connection.disconnect(); - } - } - }); - } - - // Event listeners - @Listener - public void onServerStart(GameStartedServerEvent event) { - server.start(null); - - checkForUpdates(); - - // Add custom bstats metrics - metrics.addCustomChart(new Metrics2.DrilldownPie("plugin_version", () -> { - String[] vers = Constants.VERSION.split("-"); - - Map entry = new HashMap<>(); - entry.put(vers[1], 1); - - Map> map = new HashMap<>(); - map.put(vers[0], entry); - - return map; - })); - metrics.addCustomChart(new Metrics2.SimplePie("report_errors", () -> reportErrors ? "Yes" : "No")); - metrics.addCustomChart(new Metrics2.SimplePie("admin_panel", () -> adminPanelEnabled ? "Yes" : "No")); - metrics.addCustomChart(new Metrics2.SimpleBarChart("servlets", () -> { - Map map = new HashMap<>(); - Collection> servlets = servletService.getRegisteredServlets().values(); - for (Class servlet : servlets) { - map.put(servlet.getName(), 1); - } - return map; - })); - } - @Listener - public void onServerStop(GameStoppedServerEvent event) { - server.stop(); - } - @Listener - public void onReload(GameReloadEvent event) { - Optional p = event.getCause().first(Player.class); - - logger.info("Reloading " + Constants.NAME + " v" + Constants.VERSION + "..."); - - cacheService.updatePlugins(); - cacheService.updateCommands(); - - server.stop(); - - init(p.orElse(null)); - - server.start(p.orElse(null)); - - checkForUpdates(); - - logger.info("Reloaded " + Constants.NAME); - } - - @Listener(order = Order.POST) - public void onBlockUpdateStatusChange(BlockOperationStatusChangeEvent event) { - BlockOperation on = event.getBlockOperation(); - switch (on.getStatus()) { - case DONE: - logger.info("Block op " + on.getUUID() + " is done"); - break; - - case ERRORED: - logger.warn("Block op " + on.getUUID() + " failed: " + on.getError()); - break; - - case CANCELED: - logger.info("Block op " + on.getUUID() + " was canceled"); - break; - - case PAUSED: - logger.info("Block op " + on.getUUID() + " paused"); - break; - - case RUNNING: - logger.info("Block op " + on.getUUID() + " started"); - break; - } - } - - // Execute a command - public static CommandResult executeCommand(String command, CommandSource source) { - CommandManager cmdManager = Sponge.getGame().getCommandManager(); - return cmdManager.process(source, command); - } - - // Run functions on the main server thread - public static void runOnMain(Runnable runnable) throws WebApplicationException { - if (Sponge.getServer().isMainThread()) { - runnable.run(); - } else { - CompletableFuture future = CompletableFuture.runAsync(runnable, WebAPI.syncExecutor); - try { - future.get(); - } catch (InterruptedException ignored) { - } catch (ExecutionException e) { - // Rethrow any web application exceptions we get, because they're handled by the servlets - if (e.getCause() instanceof WebApplicationException) - throw (WebApplicationException)e.getCause(); - - e.printStackTrace(); - WebAPI.sentryCapture(e); - throw new InternalServerErrorException(e.getMessage()); - } - } - } - public static T runOnMain(Supplier supplier) throws WebApplicationException { - if (Sponge.getServer().isMainThread()) { - Timings.RUN_ON_MAIN.startTiming(); - T obj = supplier.get(); - Timings.RUN_ON_MAIN.stopTiming(); - return obj; - } else { - CompletableFuture future = CompletableFuture.supplyAsync(supplier, WebAPI.syncExecutor); - try { - return future.get(); - } catch (InterruptedException e) { - throw new InternalServerErrorException(e.getMessage()); - } catch (ExecutionException e) { - // Rethrow any web application exceptions we get, because they're handled by the servlets - if (e.getCause() instanceof WebApplicationException) - throw (WebApplicationException)e.getCause(); - - e.printStackTrace(); - WebAPI.sentryCapture(e); - throw new InternalServerErrorException(e.getMessage()); - } - } - } - - // Emulate HTTP requests from sockets - public static ResponseMessage emulateRequest(RequestMessage message) { - try { - InternalHttpRequest req = new InternalHttpRequest(message); - InternalHttpResponse res = new InternalHttpResponse(); - server.handle(message.getPath(), req, req, res); - return new ResponseMessage(message.getId(), res.getStatus(), res.getHeaders(), res.getOuput()); - } catch (Exception e) { - e.printStackTrace(); - return new ResponseMessage(message.getId(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - new HashMap<>(), e.getMessage()); - } - } - - // Sentry logging - private static void addDefaultContext() { - Context context = Sentry.getContext(); - context.addTag("full_release", Constants.VERSION); - - context.addTag("java_version", System.getProperty("java.version")); - context.addTag("os_name", System.getProperty("os.name")); - context.addTag("os_arch", System.getProperty("os.arch")); - context.addTag("os_version", System.getProperty("os.version")); - - context.addExtra("processors", Runtime.getRuntime().availableProcessors()); - context.addExtra("memory_max", Runtime.getRuntime().maxMemory()); - context.addExtra("memory_total", Runtime.getRuntime().totalMemory()); - context.addExtra("memory_free", Runtime.getRuntime().freeMemory()); - - context.addExtra("server_host", server.getHost()); - context.addExtra("server_port_http", server.getHttpPort()); - context.addExtra("server_port_https", server.getHttpsPort()); - - context.addExtra("sponge_api", spongeApi); - context.addExtra("sponge_game", spongeGame); - context.addExtra("sponge_impl", spongeImpl); - - context.addExtra("plugins", pluginList); - } - public static void sentryCapture(Exception e) { - if (!reportErrors()) - return; - addDefaultContext(); - Sentry.capture(e); - } - public static void sentryCapture(Throwable t) { - if (!reportErrors()) - return; - addDefaultContext(); - Sentry.capture(t); - } -} +package valandur.webapi; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.reflect.TypeToken; +import com.google.inject.Inject; +import io.swagger.converter.ModelConverters; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; +import org.bstats.sponge.Metrics2; +import org.eclipse.jetty.util.log.Log; +import org.slf4j.Logger; +import org.spongepowered.api.Platform; +import org.spongepowered.api.Platform.Component; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.command.CommandManager; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.config.ConfigDir; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.event.EventManager; +import org.spongepowered.api.event.Listener; +import org.spongepowered.api.event.Order; +import org.spongepowered.api.event.game.GameReloadEvent; +import org.spongepowered.api.event.game.state.*; +import org.spongepowered.api.plugin.Plugin; +import org.spongepowered.api.plugin.PluginContainer; +import org.spongepowered.api.scheduler.SpongeExecutorService; +import org.spongepowered.api.service.ServiceManager; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.format.TextColors; +import valandur.webapi.block.BlockOperation; +import valandur.webapi.block.BlockOperationStatusChangeEvent; +import valandur.webapi.block.BlockService; +import valandur.webapi.cache.CacheService; +import valandur.webapi.command.CommandRegistry; +import valandur.webapi.command.CommandSource; +import valandur.webapi.config.BaseConfig; +import valandur.webapi.config.MainConfig; +import valandur.webapi.hook.WebHook; +import valandur.webapi.hook.WebHookSerializer; +import valandur.webapi.hook.WebHookService; +import valandur.webapi.link.LinkService; +import valandur.webapi.link.internal.InternalHttpRequest; +import valandur.webapi.link.internal.InternalHttpResponse; +import valandur.webapi.link.message.RequestMessage; +import valandur.webapi.link.message.ResponseMessage; +import valandur.webapi.message.InteractiveMessageService; +import valandur.webapi.security.PermissionStruct; +import valandur.webapi.security.PermissionStructSerializer; +import valandur.webapi.security.SecurityService; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.server.ServerService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.ServletService; +import valandur.webapi.swagger.SwaggerModelConverter; +import valandur.webapi.user.UserPermissionStruct; +import valandur.webapi.user.UserPermissionStructSerializer; +import valandur.webapi.user.UserService; +import valandur.webapi.util.Constants; +import valandur.webapi.util.JettyLogger; +import valandur.webapi.util.Timings; + +import javax.net.ssl.HttpsURLConnection; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.WebApplicationException; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +@Plugin( + id = Constants.ID, + version = Constants.VERSION, + name = Constants.NAME, + url = Constants.URL, + description = Constants.DESCRIPTION, + authors = { + "Valandur" + } +) +public class WebAPI { + + static { + System.out.println("Static initialized"); + } + + private static WebAPI instance; + public static WebAPI getInstance() { + return WebAPI.instance; + } + + private static SpongeExecutorService syncExecutor; + private static SpongeExecutorService asyncExecutor; + public static SpongeExecutorService getAsyncExecutor() { + return WebAPI.asyncExecutor; + } + + private boolean devMode = false; + public static boolean isDevMode() { + return WebAPI.getInstance().devMode; + } + + private boolean adminPanelEnabled = true; + public static boolean isAdminPanelEnabled() { + return WebAPI.getInstance().adminPanelEnabled; + } + + private static String spongeApi; + private static String spongeGame; + private static String spongeImpl; + private static String pluginList; + + private static WebServer server; + + @Inject + private Metrics2 metrics; + + @Inject + private Logger logger; + public static Logger getLogger() { + return WebAPI.getInstance().logger; + } + + @Inject + @ConfigDir(sharedRoot = false) + private Path configPath; + public static Path getConfigPath() { + return WebAPI.getInstance().configPath; + } + + @Inject + private PluginContainer container; + public static PluginContainer getContainer() { + return WebAPI.getInstance().container; + } + + private boolean reportErrors; + public static boolean reportErrors() { + return WebAPI.getInstance() == null || WebAPI.getInstance().reportErrors; + } + + // Services + private BlockService blockService; + public static BlockService getBlockService() { + return WebAPI.getInstance().blockService; + } + + private CacheService cacheService; + public static CacheService getCacheService() { + return WebAPI.getInstance().cacheService; + } + + private SerializeService serializeService; + public static SerializeService getSerializeService() { + return WebAPI.getInstance().serializeService; + } + + private InteractiveMessageService messageService; + public static InteractiveMessageService getMessageService() { + return WebAPI.getInstance().messageService; + } + + private LinkService linkService; + public static LinkService getLinkService() { + return WebAPI.getInstance().linkService; + } + + private SecurityService securityService; + public static SecurityService getSecurityService() { + return WebAPI.getInstance().securityService; + } + + private ServerService serverService; + public static ServerService getServerService() { + return WebAPI.getInstance().serverService; + } + + private ServletService servletService; + public static ServletService getServletService() { + return WebAPI.getInstance().servletService; + } + + private UserService userService; + public static UserService getUserService() { + return WebAPI.getInstance().userService; + } + + private WebHookService webHookService; + public static WebHookService getWebHookService() { + return WebAPI.getInstance().webHookService; + } + + + + public WebAPI() { + System.setProperty("sentry.dsn", "https://fb64795d2a5c4ff18f3c3e4117d7c245:53cf4ea85ae44608ab5b189f0c07b3f1@sentry.io/203545"); + System.setProperty("sentry.release", Constants.VERSION.split("-")[0]); + System.setProperty("sentry.maxmessagelength", "2000"); + System.setProperty("sentry.stacktrace.app.packages", WebAPI.class.getPackage().getName()); + } + + @Listener + public void onPreInitialization(GamePreInitializationEvent event) { + WebAPI.instance = this; + + Timings.STARTUP.startTiming(); + + Platform platform = Sponge.getPlatform(); + spongeApi = platform.getContainer(Component.API).getVersion().orElse(null); + spongeGame = platform.getContainer(Component.GAME).getVersion().orElse(null); + spongeImpl = platform.getContainer(Component.IMPLEMENTATION).getVersion().orElse(null); + pluginList = Sponge.getPluginManager().getPlugins().stream() + .map(p -> p.getId() + ": " + p.getVersion().orElse(null)) + .collect(Collectors.joining("; \n")); + + // Create our config directory if it doesn't exist + if (!Files.exists(configPath)) { + try { + Files.createDirectories(configPath); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // Reusable sync executor to run code on main server thread + syncExecutor = Sponge.getScheduler().createSyncExecutor(this); + asyncExecutor = Sponge.getScheduler().createAsyncExecutor(this); + + // Register custom serializers + TypeSerializers.getDefaultSerializers().registerType( + TypeToken.of(WebHook.class), new WebHookSerializer()); + TypeSerializers.getDefaultSerializers().registerType( + TypeToken.of(UserPermissionStruct.class), new UserPermissionStructSerializer()); + TypeSerializers.getDefaultSerializers().registerType( + TypeToken.of(PermissionStruct.class), new PermissionStructSerializer()); + + // Setup services + this.blockService = new BlockService(); + this.cacheService = new CacheService(); + this.linkService = new LinkService(); + this.messageService = new InteractiveMessageService(); + this.securityService = new SecurityService(); + this.serializeService = new SerializeService(); + this.serverService = new ServerService(); + this.servletService = new ServletService(); + this.webHookService = new WebHookService(); + this.userService = new UserService(); + + // Register services + ServiceManager serviceMan = Sponge.getServiceManager(); + serviceMan.setProvider(this, BlockService.class, blockService); + serviceMan.setProvider(this, CacheService.class, cacheService); + serviceMan.setProvider(this, LinkService.class, linkService); + serviceMan.setProvider(this, InteractiveMessageService.class, messageService); + serviceMan.setProvider(this, SecurityService.class, securityService); + serviceMan.setProvider(this, SerializeService.class, serializeService); + serviceMan.setProvider(this, ServerService.class, serverService); + serviceMan.setProvider(this, ServletService.class, servletService); + serviceMan.setProvider(this, WebHookService.class, webHookService); + serviceMan.setProvider(this, UserService.class, userService); + + // Register events of services + EventManager evenMan = Sponge.getEventManager(); + evenMan.registerListeners(this, cacheService); + evenMan.registerListeners(this, linkService); + evenMan.registerListeners(this, webHookService); + + // Swagger setup stuff + ModelConverters.getInstance().addConverter(new SwaggerModelConverter()); + + Timings.STARTUP.stopTiming(); + } + @Listener + public void onInitialization(GameInitializationEvent event) { + Timings.STARTUP.startTiming(); + + logger.info(Constants.NAME + " v" + Constants.VERSION + " is starting..."); + + logger.info("Setting up jetty logger..."); + Log.setLog(new JettyLogger()); + + // Main init function, that is also called when reloading the plugin + init(null); + + logger.info(Constants.NAME + " ready"); + + Timings.STARTUP.stopTiming(); + } + @Listener(order = Order.POST) + public void onPostInitialization(GamePostInitializationEvent event) { + Timings.STARTUP.startTiming(); + + // Load base data + cacheService.updateWorlds(); + cacheService.updatePlugins(); + cacheService.updateCommands(); + + Timings.STARTUP.stopTiming(); + } + + // Reusable setup function, for starting and reloading + private void init(Player triggeringPlayer) { + Timings.STARTUP.startTiming(); + + logger.info("Loading configuration..."); + + Path configPath = WebAPI.getConfigPath().resolve("config.conf").normalize(); + MainConfig mainConfig = BaseConfig.load(configPath, new MainConfig()); + + // Save important config values to variables + devMode = mainConfig.devMode; + reportErrors = mainConfig.reportErrors; + adminPanelEnabled = mainConfig.adminPanel; + + // Create our WebServer + server = new WebServer(logger, mainConfig); + + if (devMode) { + logger.warn("Web-API IS RUNNING IN DEV MODE. ERROR REPORTING IS OFF!"); + reportErrors = false; + } + + // Use the container instead of VERSION so the compiler doesn't remove it because it's constant + if (this.container.getVersion().orElse("").equalsIgnoreCase("@version@")) { + logger.warn("Web-API VERSION SIGNALS DEV MODE. ERROR REPORTING IS OFF!"); + reportErrors = false; + } + + /*if (reportErrors) { + Sentry.init(); + }*/ + + blockService.init(); + + cacheService.init(); + + linkService.init(); + + securityService.init(); + + serializeService.init(); + + serverService.init(); + + servletService.init(); + + userService.init(); + + webHookService.init(); + + CommandRegistry.init(); + + if (triggeringPlayer != null) { + triggeringPlayer.sendMessage(Text.builder().color(TextColors.AQUA) + .append(Text.of("[" + Constants.NAME + "] " + Constants.NAME + " has been reloaded!")) + .build()); + } + + Timings.STARTUP.stopTiming(); + } + + private void checkForUpdates() { + if (devMode) { + logger.warn("SKIPPING UPDATE CHECK IN DEV MODE"); + return; + } + + asyncExecutor.execute(() -> { + HttpsURLConnection connection = null; + try { + java.net.URL url = new URL(Constants.UPDATE_URL); + connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setRequestProperty("User-Agent", "Web-API"); + connection.setRequestProperty("accept", "application/json"); + connection.setRequestProperty("charset", "utf-8"); + connection.setUseCaches(false); + + //Get Response + int code = connection.getResponseCode(); + if (code != 200) { + logger.warn("Could not check for updates: " + code); + return; + } + + InputStream is = connection.getInputStream(); + BufferedReader rd = new BufferedReader(new InputStreamReader(is)); + StringBuilder response = new StringBuilder(); + String line; + while ((line = rd.readLine()) != null) { + response.append(line); + response.append('\r'); + } + rd.close(); + + String respString = response.toString().trim(); + if (respString.isEmpty() || respString.equalsIgnoreCase("OK")) { + logger.warn("Empty response received when checking for updates"); + return; + } + + ObjectMapper map = new ObjectMapper(); + JsonNode resp = map.readTree(respString); + + String version = container.getVersion().orElse("").split("-")[0]; + String newVersion = resp.get("tag_name").asText().substring(1).split("-")[0]; + + if (newVersion.equalsIgnoreCase(version)) { + return; + } + + String[] changes = resp.get("body").asText().split("\n"); + + logger.warn("------- Web-API Update -------"); + logger.warn("Latest: " + newVersion); + logger.warn("Current: " + version); + logger.warn("---------- Changes -----------"); + for (String change : changes) + logger.warn(change); + logger.warn("------------------------------"); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (connection != null) { + connection.disconnect(); + } + } + }); + } + + // Event listeners + @Listener + public void onServerStart(GameStartedServerEvent event) { + server.start(null); + + checkForUpdates(); + + // Add custom bstats metrics + metrics.addCustomChart(new Metrics2.DrilldownPie("plugin_version", () -> { + String[] vers = Constants.VERSION.split("-"); + + Map entry = new HashMap<>(); + entry.put(vers[1], 1); + + Map> map = new HashMap<>(); + map.put(vers[0], entry); + + return map; + })); + metrics.addCustomChart(new Metrics2.SimplePie("report_errors", () -> reportErrors ? "Yes" : "No")); + metrics.addCustomChart(new Metrics2.SimplePie("admin_panel", () -> adminPanelEnabled ? "Yes" : "No")); + metrics.addCustomChart(new Metrics2.SimpleBarChart("servlets", () -> { + Map map = new HashMap<>(); + Collection> servlets = servletService.getRegisteredServlets().values(); + for (Class servlet : servlets) { + map.put(servlet.getName(), 1); + } + return map; + })); + } + @Listener + public void onServerStop(GameStoppedServerEvent event) { + server.stop(); + } + @Listener + public void onReload(GameReloadEvent event) { + Optional p = event.getCause().first(Player.class); + + logger.info("Reloading " + Constants.NAME + " v" + Constants.VERSION + "..."); + + cacheService.updatePlugins(); + cacheService.updateCommands(); + + server.stop(); + + init(p.orElse(null)); + + server.start(p.orElse(null)); + + checkForUpdates(); + + logger.info("Reloaded " + Constants.NAME); + } + + @Listener(order = Order.POST) + public void onBlockUpdateStatusChange(BlockOperationStatusChangeEvent event) { + BlockOperation on = event.getBlockOperation(); + switch (on.getStatus()) { + case DONE: + logger.info("Block op " + on.getUUID() + " is done"); + break; + + case ERRORED: + logger.warn("Block op " + on.getUUID() + " failed: " + on.getError()); + break; + + case CANCELED: + logger.info("Block op " + on.getUUID() + " was canceled"); + break; + + case PAUSED: + logger.info("Block op " + on.getUUID() + " paused"); + break; + + case RUNNING: + logger.info("Block op " + on.getUUID() + " started"); + break; + } + } + + // Execute a command + public static CommandResult executeCommand(String command, CommandSource source) { + CommandManager cmdManager = Sponge.getGame().getCommandManager(); + return cmdManager.process(source, command); + } + + // Run functions on the main server thread + public static void runOnMain(Runnable runnable) throws WebApplicationException { + if (Sponge.getServer().isMainThread()) { + runnable.run(); + } else { + CompletableFuture future = CompletableFuture.runAsync(runnable, WebAPI.syncExecutor); + try { + future.get(); + } catch (InterruptedException ignored) { + } catch (ExecutionException e) { + // Rethrow any web application exceptions we get, because they're handled by the servlets + if (e.getCause() instanceof WebApplicationException) + throw (WebApplicationException)e.getCause(); + + e.printStackTrace(); + WebAPI.sentryCapture(e); + throw new InternalServerErrorException(e.getMessage()); + } + } + } + public static T runOnMain(Supplier supplier) throws WebApplicationException { + if (Sponge.getServer().isMainThread()) { + Timings.RUN_ON_MAIN.startTiming(); + T obj = supplier.get(); + Timings.RUN_ON_MAIN.stopTiming(); + return obj; + } else { + CompletableFuture future = CompletableFuture.supplyAsync(supplier, WebAPI.syncExecutor); + try { + return future.get(); + } catch (InterruptedException e) { + throw new InternalServerErrorException(e.getMessage()); + } catch (ExecutionException e) { + // Rethrow any web application exceptions we get, because they're handled by the servlets + if (e.getCause() instanceof WebApplicationException) + throw (WebApplicationException)e.getCause(); + + e.printStackTrace(); + WebAPI.sentryCapture(e); + throw new InternalServerErrorException(e.getMessage()); + } + } + } + + // Emulate HTTP requests from sockets + public static ResponseMessage emulateRequest(RequestMessage message) { + try { + InternalHttpRequest req = new InternalHttpRequest(message); + InternalHttpResponse res = new InternalHttpResponse(); + server.handle(message.getPath(), req, req, res); + return new ResponseMessage(message.getId(), res.getStatus(), res.getHeaders(), res.getOuput()); + } catch (Exception e) { + e.printStackTrace(); + return new ResponseMessage(message.getId(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + new HashMap<>(), e.getMessage()); + } + } + + // Sentry logging + private static void addDefaultContext() { + /*ontext context = Sentry.getContext(); + context.addTag("full_release", Constants.VERSION); + + context.addTag("java_version", System.getProperty("java.version")); + context.addTag("os_name", System.getProperty("os.name")); + context.addTag("os_arch", System.getProperty("os.arch")); + context.addTag("os_version", System.getProperty("os.version")); + + context.addExtra("processors", Runtime.getRuntime().availableProcessors()); + context.addExtra("memory_max", Runtime.getRuntime().maxMemory()); + context.addExtra("memory_total", Runtime.getRuntime().totalMemory()); + context.addExtra("memory_free", Runtime.getRuntime().freeMemory()); + + context.addExtra("server_host", server.getHost()); + context.addExtra("server_port_http", server.getHttpPort()); + context.addExtra("server_port_https", server.getHttpsPort()); + + context.addExtra("sponge_api", spongeApi); + context.addExtra("sponge_game", spongeGame); + context.addExtra("sponge_impl", spongeImpl); + + context.addExtra("plugins", pluginList);*/ + } + public static void sentryCapture(Exception e) { + if (!reportErrors()) + return; + addDefaultContext(); + //Sentry.capture(e); + } + public static void sentryCapture(Throwable t) { + if (!reportErrors()) + return; + addDefaultContext(); + //Sentry.capture(t); + } +} diff --git a/src/main/java/valandur/webapi/WebServer.java b/webapi-sponge/src/main/java/valandur/webapi/WebServer.java similarity index 97% rename from src/main/java/valandur/webapi/WebServer.java rename to webapi-sponge/src/main/java/valandur/webapi/WebServer.java index 3c93e0dd..4b3a24b3 100644 --- a/src/main/java/valandur/webapi/WebServer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/WebServer.java @@ -1,323 +1,323 @@ -package valandur.webapi; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.swagger.jaxrs.config.BeanConfig; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.rewrite.handler.RedirectPatternRule; -import org.eclipse.jetty.rewrite.handler.RewriteHandler; -import org.eclipse.jetty.server.*; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.util.MultiException; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.glassfish.jersey.server.ResourceConfig; -import org.glassfish.jersey.servlet.ServletContainer; -import org.slf4j.Logger; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; -import valandur.webapi.config.MainConfig; -import valandur.webapi.handler.AssetHandler; -import valandur.webapi.handler.ErrorHandler; -import valandur.webapi.serialize.SerializationFeature; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.util.Constants; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.SocketException; -import java.nio.charset.Charset; -import java.util.HashSet; -import java.util.Set; - -public class WebServer { - - private Logger logger; - - private Server server; - - private MainConfig config; - - private byte[] apConfig; - - public String getHost() { - return config.host; - } - public int getHttpPort() { - return config.http; - } - public int getHttpsPort() { - return config.https; - } - - - WebServer(Logger logger, MainConfig config) { - this.logger = logger; - this.config = config; - - // Process the config.js file to include data from the Web-API config files - try { - MainConfig.APConfig cfg = config.adminPanelConfig; - if (cfg != null) { - ObjectMapper om = new ObjectMapper(); - String configStr = "window.config = " + om.writeValueAsString(cfg); - apConfig = configStr.getBytes(Charset.forName("utf-8")); - } - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - } - - public void start(Player player) { - // Start web server - logger.info("Starting Web Server..."); - - try { - server = new Server(); - - // HTTP config - HttpConfiguration httpConfig = new HttpConfiguration(); - httpConfig.setOutputBufferSize(32768); - - String baseUri = null; - - // HTTP - if (config.http >= 0) { - if (config.http < 1024) { - logger.warn("You are using an HTTP port < 1024 which is not recommended! \n" + - "This might cause errors when not running the server as root/admin. \n" + - "Running the server as root/admin is not recommended. " + - "Please use a port above 1024 for HTTP." - ); - } - ServerConnector httpConn = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); - httpConn.setHost(config.host); - httpConn.setPort(config.http); - httpConn.setIdleTimeout(30000); - server.addConnector(httpConn); - - baseUri = "http://" + config.host + ":" + config.http; - } - - // HTTPS - if (config.https >= 0) { - if (config.https < 1024) { - logger.warn("You are using an HTTPS port < 1024 which is not recommended! \n" + - "This might cause errors when not running the server as root/admin. \n" + - "Running the server as root/admin is not recommended. " + - "Please use a port above 1024 for HTTPS." - ); - } - - // Update http config - httpConfig.setSecureScheme("https"); - httpConfig.setSecurePort(config.https); - - String loc = config.customKeyStore; - String pw = config.customKeyStorePassword; - String mgrPw = config.customKeyStoreManagerPassword; - - if (loc == null || loc.isEmpty()) { - loc = Sponge.getAssetManager().getAsset(WebAPI.getInstance(), "keystore.jks") - .map(a -> a.getUrl().toString()) - .orElse("../../src/main/resources/assets/webapi/keystore.jks"); - pw = "mX4z%&uJ2E6VN#5f"; - mgrPw = "mX4z%&uJ2E6VN#5f"; - } - - // SSL Factory - SslContextFactory sslFactory = new SslContextFactory(); - sslFactory.setKeyStorePath(loc); - sslFactory.setKeyStorePassword(pw); - sslFactory.setKeyManagerPassword(mgrPw); - - // HTTPS config - HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); - SecureRequestCustomizer src = new SecureRequestCustomizer(); - src.setStsMaxAge(2000); - src.setStsIncludeSubDomains(true); - httpsConfig.addCustomizer(src); - - - ServerConnector httpsConn = new ServerConnector(server, - new SslConnectionFactory(sslFactory, HttpVersion.HTTP_1_1.asString()), - new HttpConnectionFactory(httpsConfig) - ); - httpsConn.setHost(config.host); - httpsConn.setPort(config.https); - httpsConn.setIdleTimeout(30000); - server.addConnector(httpsConn); - - baseUri = "https://" + config.host + ":" + config.https; - } - - if (baseUri == null) { - logger.error("You have disabled both HTTP and HTTPS - The Web-API will be unreachable!"); - baseUri = ""; // for swagger - } - - // Collection of all handlers - ContextHandlerCollection mainContext = new ContextHandlerCollection(); - - // Asset handlers - mainContext.addHandler(newContext("/docs", new AssetHandler("pages/redoc.html"))); - - String panelPath = null; - if (config.adminPanel) { - // Rewrite handler - RewriteHandler rewrite = new RewriteHandler(); - rewrite.setRewriteRequestURI(true); - rewrite.setRewritePathInfo(true); - - panelPath = config.adminPanelConfig.basePath; - if (!panelPath.startsWith("/")) { - panelPath = "/" + config.adminPanelConfig.basePath; - } - RedirectPatternRule redirect = new RedirectPatternRule(); - redirect.setPattern("/*"); - redirect.setLocation(panelPath); - rewrite.addRule(redirect); - mainContext.addHandler(newContext("/", rewrite)); - - final String pPath = panelPath; - mainContext.addHandler(newContext(panelPath, new AssetHandler("admin", path -> { - if (path.endsWith("config.js") && this.apConfig != null) { - return input -> apConfig; - } - if (path.endsWith("index.html")) { - return input -> new String(input).replace("", - "").getBytes(); - } - - return input -> input; - }))); - } - - // Main servlet context - ServletContextHandler servletsContext = new ServletContextHandler(); - servletsContext.setContextPath(Constants.BASE_PATH); - - // Resource config for jersey servlet - ResourceConfig conf = new ResourceConfig(); - conf.packages( - "io.swagger.jaxrs.listing", - "valandur.webapi.shadow.io.swagger.jaxrs.listing", - "valandur.webapi.handler", - "valandur.webapi.security", - "valandur.webapi.serialize", - "valandur.webapi.user" - //"io.swagger.v3.jaxrs2.integration.resources" // This if for Swagger 3.0 - ); - conf.property("jersey.config.server.wadl.disableWadl", true); - - // Add error handler to jetty (will also be picked up by jersey - ErrorHandler errHandler = new ErrorHandler(); - server.setErrorHandler(errHandler); - server.addBean(errHandler); - - // Register all servlets. We use this instead of package scanning because we don't want the - // integrated servlets to load unless their plugin is present. Also this gives us more control/info - // over which servlets/endpoints are loaded. - Set servlets = new HashSet<>(); - for (Class servletClass : - WebAPI.getServletService().getRegisteredServlets().values()) { - conf.register(servletClass); - String pkg = servletClass.getPackage().getName(); - servlets.add(pkg); - } - - // Register serializer - conf.register(SerializationFeature.class); - - // Jersey servlet - ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(conf)); - jerseyServlet.setInitOrder(1); - // This if for Swagger 3.0 - // jerseyServlet.setInitParameter("openApi.configuration.location", assets/webapi/swagger/config.json"); // This is for Swagger 3.0 - servletsContext.addServlet(jerseyServlet, "/*"); - - // Register swagger as bean - // TODO: We can't set scheme and host yet because Swagger 2.0 doesn't support multiple different ones - BeanConfig beanConfig = new BeanConfig(); - beanConfig.setBasePath(Constants.BASE_PATH); - beanConfig.setResourcePackage("valandur.webapi.swagger," + String.join(",", servlets)); - beanConfig.setScan(true); - if (config.devMode) { - beanConfig.setPrettyPrint(true); - } - servletsContext.addBean(beanConfig); - - // Attach error handler to servlets context - servletsContext.setErrorHandler(errHandler); - servletsContext.addBean(errHandler); - - // Add servlets to main context - mainContext.addHandler(servletsContext); - - // Add main context to server - server.setHandler(mainContext); - - - server.start(); - - if (config.adminPanel) { - logger.info("AdminPanel: " + baseUri + panelPath); - } - logger.info("API Docs: " + baseUri + "/docs"); - } catch (SocketException e) { - logger.error("Web-API webserver could not start, probably because one of the ports needed for HTTP " + - "and/or HTTPS are in use or not accessible (ports below 1024 are protected)"); - } catch (MultiException e) { - e.getThrowables().forEach(t -> { - if (t instanceof SocketException) { - logger.error("Web-API webserver could not start, probably because one of the ports needed for HTTP " + - "and/or HTTPS are in use or not accessible (ports below 1024 are protected)"); - } else { - t.printStackTrace(); - WebAPI.sentryCapture(t); - } - }); - } catch (Exception e) { - e.printStackTrace(); - WebAPI.sentryCapture(e); - } - - if (player != null) { - player.sendMessage(Text.builder() - .color(TextColors.AQUA) - .append(Text.of("[" + Constants.NAME + "] The web server has been restarted!")) - .toText() - ); - } - } - - public void stop() { - if (server != null) { - try { - server.stop(); - server = null; - } catch (Exception e) { - e.printStackTrace(); - WebAPI.sentryCapture(e); - } - } - } - - public void handle(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse res) - throws IOException, ServletException { - server.handle(target, baseRequest, req, res); - } - - private ContextHandler newContext(String path, Handler handler) { - ContextHandler context = new ContextHandler(); - context.setContextPath(path); - context.setHandler(handler); - return context; - } -} +package valandur.webapi; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.jaxrs.config.BeanConfig; +import org.eclipse.jetty.http.HttpVersion; +import org.eclipse.jetty.rewrite.handler.RedirectPatternRule; +import org.eclipse.jetty.rewrite.handler.RewriteHandler; +import org.eclipse.jetty.server.*; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.util.MultiException; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.servlet.ServletContainer; +import org.slf4j.Logger; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.format.TextColors; +import valandur.webapi.config.MainConfig; +import valandur.webapi.handler.AssetHandler; +import valandur.webapi.handler.ErrorHandler; +import valandur.webapi.serialize.SerializationFeature; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.util.Constants; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.SocketException; +import java.nio.charset.Charset; +import java.util.HashSet; +import java.util.Set; + +public class WebServer { + + private Logger logger; + + private Server server; + + private MainConfig config; + + private byte[] apConfig; + + public String getHost() { + return config.host; + } + public int getHttpPort() { + return config.http; + } + public int getHttpsPort() { + return config.https; + } + + + WebServer(Logger logger, MainConfig config) { + this.logger = logger; + this.config = config; + + // Process the config.js file to include data from the Web-API config files + try { + MainConfig.APConfig cfg = config.adminPanelConfig; + if (cfg != null) { + ObjectMapper om = new ObjectMapper(); + String configStr = "window.config = " + om.writeValueAsString(cfg); + apConfig = configStr.getBytes(Charset.forName("utf-8")); + } + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } + + public void start(Player player) { + // Start web server + logger.info("Starting Web Server..."); + + try { + server = new Server(); + + // HTTP config + HttpConfiguration httpConfig = new HttpConfiguration(); + httpConfig.setOutputBufferSize(32768); + + String baseUri = null; + + // HTTP + if (config.http >= 0) { + if (config.http < 1024) { + logger.warn("You are using an HTTP port < 1024 which is not recommended! \n" + + "This might cause errors when not running the server as root/admin. \n" + + "Running the server as root/admin is not recommended. " + + "Please use a port above 1024 for HTTP." + ); + } + ServerConnector httpConn = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); + httpConn.setHost(config.host); + httpConn.setPort(config.http); + httpConn.setIdleTimeout(30000); + server.addConnector(httpConn); + + baseUri = "http://" + config.host + ":" + config.http; + } + + // HTTPS + if (config.https >= 0) { + if (config.https < 1024) { + logger.warn("You are using an HTTPS port < 1024 which is not recommended! \n" + + "This might cause errors when not running the server as root/admin. \n" + + "Running the server as root/admin is not recommended. " + + "Please use a port above 1024 for HTTPS." + ); + } + + // Update http config + httpConfig.setSecureScheme("https"); + httpConfig.setSecurePort(config.https); + + String loc = config.customKeyStore; + String pw = config.customKeyStorePassword; + String mgrPw = config.customKeyStoreManagerPassword; + + if (loc == null || loc.isEmpty()) { + loc = Sponge.getAssetManager().getAsset(WebAPI.getInstance(), "keystore.jks") + .map(a -> a.getUrl().toString()) + .orElse("../../src/main/resources/assets/webapi/keystore.jks"); + pw = "mX4z%&uJ2E6VN#5f"; + mgrPw = "mX4z%&uJ2E6VN#5f"; + } + + // SSL Factory + SslContextFactory sslFactory = new SslContextFactory(); + sslFactory.setKeyStorePath(loc); + sslFactory.setKeyStorePassword(pw); + sslFactory.setKeyManagerPassword(mgrPw); + + // HTTPS config + HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); + SecureRequestCustomizer src = new SecureRequestCustomizer(); + src.setStsMaxAge(2000); + src.setStsIncludeSubDomains(true); + httpsConfig.addCustomizer(src); + + + ServerConnector httpsConn = new ServerConnector(server, + new SslConnectionFactory(sslFactory, HttpVersion.HTTP_1_1.asString()), + new HttpConnectionFactory(httpsConfig) + ); + httpsConn.setHost(config.host); + httpsConn.setPort(config.https); + httpsConn.setIdleTimeout(30000); + server.addConnector(httpsConn); + + baseUri = "https://" + config.host + ":" + config.https; + } + + if (baseUri == null) { + logger.error("You have disabled both HTTP and HTTPS - The Web-API will be unreachable!"); + baseUri = ""; // for swagger + } + + // Collection of all handlers + ContextHandlerCollection mainContext = new ContextHandlerCollection(); + + // Asset handlers + mainContext.addHandler(newContext("/docs", new AssetHandler("pages/redoc.html"))); + + String panelPath = null; + if (config.adminPanel) { + // Rewrite handler + RewriteHandler rewrite = new RewriteHandler(); + rewrite.setRewriteRequestURI(true); + rewrite.setRewritePathInfo(true); + + panelPath = config.adminPanelConfig.basePath; + if (!panelPath.startsWith("/")) { + panelPath = "/" + config.adminPanelConfig.basePath; + } + RedirectPatternRule redirect = new RedirectPatternRule(); + redirect.setPattern("/*"); + redirect.setLocation(panelPath); + rewrite.addRule(redirect); + mainContext.addHandler(newContext("/", rewrite)); + + final String pPath = panelPath; + mainContext.addHandler(newContext(panelPath, new AssetHandler("admin", path -> { + if (path.endsWith("config.js") && this.apConfig != null) { + return input -> apConfig; + } + if (path.endsWith("index.html")) { + return input -> new String(input).replace("", + "").getBytes(); + } + + return input -> input; + }))); + } + + // Main servlet context + ServletContextHandler servletsContext = new ServletContextHandler(); + servletsContext.setContextPath(Constants.BASE_PATH); + + // Resource config for jersey servlet + ResourceConfig conf = new ResourceConfig(); + conf.packages( + "io.swagger.jaxrs.listing", + "valandur.webapi.shadow.io.swagger.jaxrs.listing", + "valandur.webapi.handler", + "valandur.webapi.security", + "valandur.webapi.serialize", + "valandur.webapi.user" + //"io.swagger.v3.jaxrs2.integration.resources" // This if for Swagger 3.0 + ); + conf.property("jersey.config.server.wadl.disableWadl", true); + + // Add error handler to jetty (will also be picked up by jersey + ErrorHandler errHandler = new ErrorHandler(); + server.setErrorHandler(errHandler); + server.addBean(errHandler); + + // Register all servlets. We use this instead of package scanning because we don't want the + // integrated servlets to load unless their plugin is present. Also this gives us more control/info + // over which servlets/endpoints are loaded. + Set servlets = new HashSet<>(); + for (Class servletClass : + WebAPI.getServletService().getRegisteredServlets().values()) { + conf.register(servletClass); + String pkg = servletClass.getPackage().getName(); + servlets.add(pkg); + } + + // Register serializer + conf.register(SerializationFeature.class); + + // Jersey servlet + ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(conf)); + jerseyServlet.setInitOrder(1); + // This if for Swagger 3.0 + // jerseyServlet.setInitParameter("openApi.configuration.location", assets/webapi/swagger/config.json"); // This is for Swagger 3.0 + servletsContext.addServlet(jerseyServlet, "/*"); + + // Register swagger as bean + // TODO: We can't set scheme and host yet because Swagger 2.0 doesn't support multiple different ones + BeanConfig beanConfig = new BeanConfig(); + beanConfig.setBasePath(Constants.BASE_PATH); + beanConfig.setResourcePackage("valandur.webapi.swagger," + String.join(",", servlets)); + beanConfig.setScan(true); + if (config.devMode) { + beanConfig.setPrettyPrint(true); + } + servletsContext.addBean(beanConfig); + + // Attach error handler to servlets context + servletsContext.setErrorHandler(errHandler); + servletsContext.addBean(errHandler); + + // Add servlets to main context + mainContext.addHandler(servletsContext); + + // Add main context to server + server.setHandler(mainContext); + + + server.start(); + + if (config.adminPanel) { + logger.info("AdminPanel: " + baseUri + panelPath); + } + logger.info("API Docs: " + baseUri + "/docs"); + } catch (SocketException e) { + logger.error("Web-API webserver could not start, probably because one of the ports needed for HTTP " + + "and/or HTTPS are in use or not accessible (ports below 1024 are protected)"); + } catch (MultiException e) { + e.getThrowables().forEach(t -> { + if (t instanceof SocketException) { + logger.error("Web-API webserver could not start, probably because one of the ports needed for HTTP " + + "and/or HTTPS are in use or not accessible (ports below 1024 are protected)"); + } else { + t.printStackTrace(); + WebAPI.sentryCapture(t); + } + }); + } catch (Exception e) { + e.printStackTrace(); + WebAPI.sentryCapture(e); + } + + if (player != null) { + player.sendMessage(Text.builder() + .color(TextColors.AQUA) + .append(Text.of("[" + Constants.NAME + "] The web server has been restarted!")) + .toText() + ); + } + } + + public void stop() { + if (server != null) { + try { + server.stop(); + server = null; + } catch (Exception e) { + e.printStackTrace(); + WebAPI.sentryCapture(e); + } + } + } + + public void handle(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse res) + throws IOException, ServletException { + server.handle(target, baseRequest, req, res); + } + + private ContextHandler newContext(String path, Handler handler) { + ContextHandler context = new ContextHandler(); + context.setContextPath(path); + context.setHandler(handler); + return context; + } +} diff --git a/src/main/java/valandur/webapi/block/BlockChangeOperation.java b/webapi-sponge/src/main/java/valandur/webapi/block/BlockChangeOperation.java similarity index 96% rename from src/main/java/valandur/webapi/block/BlockChangeOperation.java rename to webapi-sponge/src/main/java/valandur/webapi/block/BlockChangeOperation.java index 7492e303..31834010 100644 --- a/src/main/java/valandur/webapi/block/BlockChangeOperation.java +++ b/webapi-sponge/src/main/java/valandur/webapi/block/BlockChangeOperation.java @@ -1,37 +1,37 @@ -package valandur.webapi.block; - -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.ApiModel; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.world.BlockChangeFlags; -import org.spongepowered.api.world.World; -import valandur.webapi.cache.world.CachedWorld; - -import java.util.Map; - -@ApiModel(parent = BlockOperation.class) -public class BlockChangeOperation extends BlockOperation { - - Map newStates; - - @Override - public BlockOperationType getType() { - return BlockOperationType.CHANGE; - } - - public BlockChangeOperation(CachedWorld world, Vector3i min, Vector3i max, Map blocks) { - super(world, min, max); - - this.newStates = blocks; - } - - @Override - protected void processBlock(World world, Vector3i pos) { - BlockState state = newStates.get(pos); - - if (state == null) - return; - - world.setBlock(pos, state, BlockChangeFlags.NONE); - } -} +package valandur.webapi.block; + +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.ApiModel; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.world.BlockChangeFlags; +import org.spongepowered.api.world.World; +import valandur.webapi.cache.world.CachedWorld; + +import java.util.Map; + +@ApiModel(parent = BlockOperation.class) +public class BlockChangeOperation extends BlockOperation { + + Map newStates; + + @Override + public BlockOperationType getType() { + return BlockOperationType.CHANGE; + } + + public BlockChangeOperation(CachedWorld world, Vector3i min, Vector3i max, Map blocks) { + super(world, min, max); + + this.newStates = blocks; + } + + @Override + protected void processBlock(World world, Vector3i pos) { + BlockState state = newStates.get(pos); + + if (state == null) + return; + + world.setBlock(pos, state, BlockChangeFlags.NONE); + } +} diff --git a/src/main/java/valandur/webapi/block/BlockGetOperation.java b/webapi-sponge/src/main/java/valandur/webapi/block/BlockGetOperation.java similarity index 96% rename from src/main/java/valandur/webapi/block/BlockGetOperation.java rename to webapi-sponge/src/main/java/valandur/webapi/block/BlockGetOperation.java index ee53f7ee..18f66db8 100644 --- a/src/main/java/valandur/webapi/block/BlockGetOperation.java +++ b/webapi-sponge/src/main/java/valandur/webapi/block/BlockGetOperation.java @@ -1,38 +1,38 @@ -package valandur.webapi.block; - -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.ApiModel; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.world.World; -import valandur.webapi.cache.world.CachedWorld; -import valandur.webapi.serialize.JsonDetails; - -@ApiModel(parent = BlockOperation.class) -public class BlockGetOperation extends BlockOperation { - - private BlockState[][][] blockStates; - - @Override - public BlockOperationType getType() { - return BlockOperationType.GET; - } - - @JsonDetails - public BlockState[][][] getBlocks() { - return blockStates; - } - - - public BlockGetOperation(CachedWorld world, Vector3i min, Vector3i max) { - super(world, min, max); - blockStates = new BlockState[size.getX()][size.getY()][size.getZ()]; - } - - @Override - protected void processBlock(World world, Vector3i pos) { - int x = pos.getX() - min.getX(); - int y = pos.getY() - min.getY(); - int z = pos.getZ() - min.getZ(); - blockStates[x][y][z] = world.getBlock(pos).copy(); - } -} +package valandur.webapi.block; + +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.ApiModel; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.world.World; +import valandur.webapi.cache.world.CachedWorld; +import valandur.webapi.serialize.JsonDetails; + +@ApiModel(parent = BlockOperation.class) +public class BlockGetOperation extends BlockOperation { + + private BlockState[][][] blockStates; + + @Override + public BlockOperationType getType() { + return BlockOperationType.GET; + } + + @JsonDetails + public BlockState[][][] getBlocks() { + return blockStates; + } + + + public BlockGetOperation(CachedWorld world, Vector3i min, Vector3i max) { + super(world, min, max); + blockStates = new BlockState[size.getX()][size.getY()][size.getZ()]; + } + + @Override + protected void processBlock(World world, Vector3i pos) { + int x = pos.getX() - min.getX(); + int y = pos.getY() - min.getY(); + int z = pos.getZ() - min.getZ(); + blockStates[x][y][z] = world.getBlock(pos).copy(); + } +} diff --git a/src/main/java/valandur/webapi/block/BlockOperation.java b/webapi-sponge/src/main/java/valandur/webapi/block/BlockOperation.java similarity index 100% rename from src/main/java/valandur/webapi/block/BlockOperation.java rename to webapi-sponge/src/main/java/valandur/webapi/block/BlockOperation.java diff --git a/src/main/java/valandur/webapi/block/BlockOperationEvent.java b/webapi-sponge/src/main/java/valandur/webapi/block/BlockOperationEvent.java similarity index 100% rename from src/main/java/valandur/webapi/block/BlockOperationEvent.java rename to webapi-sponge/src/main/java/valandur/webapi/block/BlockOperationEvent.java diff --git a/src/main/java/valandur/webapi/block/BlockOperationProgressEvent.java b/webapi-sponge/src/main/java/valandur/webapi/block/BlockOperationProgressEvent.java similarity index 100% rename from src/main/java/valandur/webapi/block/BlockOperationProgressEvent.java rename to webapi-sponge/src/main/java/valandur/webapi/block/BlockOperationProgressEvent.java diff --git a/src/main/java/valandur/webapi/block/BlockOperationStatusChangeEvent.java b/webapi-sponge/src/main/java/valandur/webapi/block/BlockOperationStatusChangeEvent.java similarity index 100% rename from src/main/java/valandur/webapi/block/BlockOperationStatusChangeEvent.java rename to webapi-sponge/src/main/java/valandur/webapi/block/BlockOperationStatusChangeEvent.java diff --git a/src/main/java/valandur/webapi/block/BlockService.java b/webapi-sponge/src/main/java/valandur/webapi/block/BlockService.java similarity index 100% rename from src/main/java/valandur/webapi/block/BlockService.java rename to webapi-sponge/src/main/java/valandur/webapi/block/BlockService.java diff --git a/src/main/java/valandur/webapi/cache/CacheService.java b/webapi-sponge/src/main/java/valandur/webapi/cache/CacheService.java similarity index 100% rename from src/main/java/valandur/webapi/cache/CacheService.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/CacheService.java diff --git a/src/main/java/valandur/webapi/cache/CachedObject.java b/webapi-sponge/src/main/java/valandur/webapi/cache/CachedObject.java similarity index 97% rename from src/main/java/valandur/webapi/cache/CachedObject.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/CachedObject.java index af5813d7..da44004b 100644 --- a/src/main/java/valandur/webapi/cache/CachedObject.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/CachedObject.java @@ -1,117 +1,117 @@ -package valandur.webapi.cache; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.DataHolder; -import org.spongepowered.api.data.Property; -import org.spongepowered.api.data.manipulator.DataManipulator; -import org.spongepowered.api.data.property.PropertyHolder; -import valandur.webapi.WebAPI; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.serialize.SerializeService; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * The base class for all cached objects. - */ -@ApiModel("CachedObject") -public abstract class CachedObject { - protected long cachedAt; - protected long cacheDuration = 0; - - protected CacheService cacheService; - protected SerializeService serializeService; - protected Class clazz; - - protected Map data = new HashMap<>(); - /** - * Gets any data associated with the object if the original object was a {@link DataHolder}. - * @return Data stored on the object. - */ - @ApiModelProperty(hidden = true) - @JsonDetails - @JsonAnyGetter - public Map getData() { - return data; - } - - - public CachedObject(T value) { - this(value, true); - } - public CachedObject(T value, boolean serializeData) { - this.cachedAt = System.nanoTime(); - this.cacheService = WebAPI.getCacheService(); - this.serializeService = WebAPI.getSerializeService(); - - this.cacheDuration = cacheService.getCacheDurationFor(this.getClass()); - - if (value != null) this.clazz = (Class) value.getClass(); - - if (serializeData) { - if (value instanceof DataHolder) { - DataHolder holder = (DataHolder)value; - - Map>> supData = serializeService.getSupportedData(); - for (Map.Entry>> entry : supData.entrySet()) { - try { - if (!holder.supports(entry.getValue())) - continue; - - Optional m = holder.get(entry.getValue()); - - if (!m.isPresent()) - continue; - - data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); - } catch (IllegalArgumentException | IllegalStateException ignored) { - } - } - } - if (value instanceof PropertyHolder) { - PropertyHolder holder = (PropertyHolder)value; - - Map>, String> props = serializeService.getSupportedProperties(); - for (Property property : holder.getApplicableProperties()) { - String key = props.get(property.getClass()); - if (data.containsKey(key)) { - key = key + "Property"; - } - data.put(key, property.getValue()); - } - } - } - } - - /** - * Gets a relative link representing a Web-API endpoint where details for the object can be retrieved. - * @return The link to the details of the object, or null if not applicable. - */ - @ApiModelProperty(value = "The API link that can be used to obtain more information about this object", required = true, readOnly = true) - public abstract String getLink(); - - /** - * Tries to get the live version this object is representing. - * @return An optional containing the live version of this object if available, empty otherwise. - */ - @ApiModelProperty(hidden = true) - @JsonIgnore - public Optional getLive() { - return Optional.empty(); - } - - /** - * Checks if this cached object has expired. - * @return True if this cached object is considered expired, false otherwise. - */ - @ApiModelProperty(hidden = true) - @JsonIgnore - public final boolean isExpired() { - return (System.nanoTime() - cachedAt) / 1000000000 > cacheDuration; - } -} +package valandur.webapi.cache; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.DataHolder; +import org.spongepowered.api.data.Property; +import org.spongepowered.api.data.manipulator.DataManipulator; +import org.spongepowered.api.data.property.PropertyHolder; +import valandur.webapi.WebAPI; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.serialize.SerializeService; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * The base class for all cached objects. + */ +@ApiModel("CachedObject") +public abstract class CachedObject { + protected long cachedAt; + protected long cacheDuration = 0; + + protected CacheService cacheService; + protected SerializeService serializeService; + protected Class clazz; + + protected Map data = new HashMap<>(); + /** + * Gets any data associated with the object if the original object was a {@link DataHolder}. + * @return Data stored on the object. + */ + @ApiModelProperty(hidden = true) + @JsonDetails + @JsonAnyGetter + public Map getData() { + return data; + } + + + public CachedObject(T value) { + this(value, true); + } + public CachedObject(T value, boolean serializeData) { + this.cachedAt = System.nanoTime(); + this.cacheService = WebAPI.getCacheService(); + this.serializeService = WebAPI.getSerializeService(); + + this.cacheDuration = cacheService.getCacheDurationFor(this.getClass()); + + if (value != null) this.clazz = (Class) value.getClass(); + + if (serializeData) { + if (value instanceof DataHolder) { + DataHolder holder = (DataHolder)value; + + Map>> supData = serializeService.getSupportedData(); + for (Map.Entry>> entry : supData.entrySet()) { + try { + if (!holder.supports(entry.getValue())) + continue; + + Optional m = holder.get(entry.getValue()); + + if (!m.isPresent()) + continue; + + data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); + } catch (IllegalArgumentException | IllegalStateException ignored) { + } + } + } + if (value instanceof PropertyHolder) { + PropertyHolder holder = (PropertyHolder)value; + + Map>, String> props = serializeService.getSupportedProperties(); + for (Property property : holder.getApplicableProperties()) { + String key = props.get(property.getClass()); + if (data.containsKey(key)) { + key = key + "Property"; + } + data.put(key, property.getValue()); + } + } + } + } + + /** + * Gets a relative link representing a Web-API endpoint where details for the object can be retrieved. + * @return The link to the details of the object, or null if not applicable. + */ + @ApiModelProperty(value = "The API link that can be used to obtain more information about this object", required = true, readOnly = true) + public abstract String getLink(); + + /** + * Tries to get the live version this object is representing. + * @return An optional containing the live version of this object if available, empty otherwise. + */ + @ApiModelProperty(hidden = true) + @JsonIgnore + public Optional getLive() { + return Optional.empty(); + } + + /** + * Checks if this cached object has expired. + * @return True if this cached object is considered expired, false otherwise. + */ + @ApiModelProperty(hidden = true) + @JsonIgnore + public final boolean isExpired() { + return (System.nanoTime() - cachedAt) / 1000000000 > cacheDuration; + } +} diff --git a/src/main/java/valandur/webapi/cache/command/CachedCommand.java b/webapi-sponge/src/main/java/valandur/webapi/cache/command/CachedCommand.java similarity index 100% rename from src/main/java/valandur/webapi/cache/command/CachedCommand.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/command/CachedCommand.java diff --git a/src/main/java/valandur/webapi/cache/command/CachedCommandCall.java b/webapi-sponge/src/main/java/valandur/webapi/cache/command/CachedCommandCall.java similarity index 100% rename from src/main/java/valandur/webapi/cache/command/CachedCommandCall.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/command/CachedCommandCall.java diff --git a/src/main/java/valandur/webapi/cache/command/CachedCommandResult.java b/webapi-sponge/src/main/java/valandur/webapi/cache/command/CachedCommandResult.java similarity index 100% rename from src/main/java/valandur/webapi/cache/command/CachedCommandResult.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/command/CachedCommandResult.java diff --git a/src/main/java/valandur/webapi/cache/entity/CachedEntity.java b/webapi-sponge/src/main/java/valandur/webapi/cache/entity/CachedEntity.java similarity index 100% rename from src/main/java/valandur/webapi/cache/entity/CachedEntity.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/entity/CachedEntity.java diff --git a/src/main/java/valandur/webapi/cache/message/CachedChatMessage.java b/webapi-sponge/src/main/java/valandur/webapi/cache/message/CachedChatMessage.java similarity index 96% rename from src/main/java/valandur/webapi/cache/message/CachedChatMessage.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/message/CachedChatMessage.java index b7858354..4bbb9a1d 100644 --- a/src/main/java/valandur/webapi/cache/message/CachedChatMessage.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/message/CachedChatMessage.java @@ -1,35 +1,35 @@ -package valandur.webapi.cache.message; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.channel.MessageReceiver; -import valandur.webapi.cache.player.CachedPlayer; - -import java.util.Collection; - -@ApiModel(value = "ChatMessage", parent = CachedMessage.class) -public class CachedChatMessage extends CachedMessage { - - private CachedPlayer sender; - @ApiModelProperty(value = "The sender of the message", required = true) - public CachedPlayer getSender() { - return sender; - } - - - public CachedChatMessage(Player sender, Collection receivers, Text content) { - super(receivers, content); - - this.sender = cacheService.getPlayer(sender); - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.cache.message; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.channel.MessageReceiver; +import valandur.webapi.cache.player.CachedPlayer; + +import java.util.Collection; + +@ApiModel(value = "ChatMessage", parent = CachedMessage.class) +public class CachedChatMessage extends CachedMessage { + + private CachedPlayer sender; + @ApiModelProperty(value = "The sender of the message", required = true) + public CachedPlayer getSender() { + return sender; + } + + + public CachedChatMessage(Player sender, Collection receivers, Text content) { + super(receivers, content); + + this.sender = cacheService.getPlayer(sender); + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/cache/message/CachedMessage.java b/webapi-sponge/src/main/java/valandur/webapi/cache/message/CachedMessage.java similarity index 96% rename from src/main/java/valandur/webapi/cache/message/CachedMessage.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/message/CachedMessage.java index 40c2a8f4..1b26f0f8 100644 --- a/src/main/java/valandur/webapi/cache/message/CachedMessage.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/message/CachedMessage.java @@ -1,55 +1,55 @@ -package valandur.webapi.cache.message; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.channel.MessageReceiver; -import valandur.webapi.cache.CachedObject; - -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.stream.Collectors; - -@ApiModel(value = "Message", subTypes = { CachedChatMessage.class }) -public class CachedMessage extends CachedObject { - - protected Long timestamp; - @ApiModelProperty(value = "The timestamp at which the chat message was sent (epoch millis)", required = true) - public Long getTimestamp() { - return timestamp; - } - - protected Collection receivers = new HashSet<>(); - @ApiModelProperty(value = "The receivers of this message", required = true) - public Collection getReceivers() { - return receivers; - } - - protected Text content; - @ApiModelProperty(value = "The content of the message", required = true) - public Text getContent() { - return content; - } - - - public CachedMessage(Collection receivers, Text content) { - super(null); - - this.timestamp = (new Date()).toInstant().toEpochMilli(); - if (receivers != null) { - this.receivers.addAll(receivers.stream() - .map(m -> cacheService.asCachedObject(m)) - .collect(Collectors.toList())); - } - this.content = content.toBuilder().build(); - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.cache.message; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.channel.MessageReceiver; +import valandur.webapi.cache.CachedObject; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.stream.Collectors; + +@ApiModel(value = "Message", subTypes = { CachedChatMessage.class }) +public class CachedMessage extends CachedObject { + + protected Long timestamp; + @ApiModelProperty(value = "The timestamp at which the chat message was sent (epoch millis)", required = true) + public Long getTimestamp() { + return timestamp; + } + + protected Collection receivers = new HashSet<>(); + @ApiModelProperty(value = "The receivers of this message", required = true) + public Collection getReceivers() { + return receivers; + } + + protected Text content; + @ApiModelProperty(value = "The content of the message", required = true) + public Text getContent() { + return content; + } + + + public CachedMessage(Collection receivers, Text content) { + super(null); + + this.timestamp = (new Date()).toInstant().toEpochMilli(); + if (receivers != null) { + this.receivers.addAll(receivers.stream() + .map(m -> cacheService.asCachedObject(m)) + .collect(Collectors.toList())); + } + this.content = content.toBuilder().build(); + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/cache/misc/CachedCatalogType.java b/webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedCatalogType.java similarity index 100% rename from src/main/java/valandur/webapi/cache/misc/CachedCatalogType.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedCatalogType.java diff --git a/src/main/java/valandur/webapi/cache/misc/CachedCause.java b/webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedCause.java similarity index 96% rename from src/main/java/valandur/webapi/cache/misc/CachedCause.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedCause.java index b3c5f5f3..afbb424d 100644 --- a/src/main/java/valandur/webapi/cache/misc/CachedCause.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedCause.java @@ -1,52 +1,52 @@ -package valandur.webapi.cache.misc; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.EventContextKey; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.util.Util; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@ApiModel("Cause") -public class CachedCause extends CachedObject { - - private Map context = new HashMap<>(); - @ApiModelProperty(value = "The context surrounding the cause", required = true) - public Map getContext() { - return context; - } - - private List causes = new ArrayList<>(); - @ApiModelProperty(value = "The direct sources of this cause", required = true) - public List getCauses() { - return causes; - } - - - public CachedCause(Cause cause) { - super(cause); - - for (Map.Entry, Object> entry : cause.getContext().asMap().entrySet()) { - String key = Util.lowerFirst(entry.getKey().getId()); - context.put(key, WebAPI.getCacheService().asCachedObject(entry.getValue())); - } - - for (Object entry : cause.all()) { - causes.add(WebAPI.getCacheService().asCachedObject(entry)); - } - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.cache.misc; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.EventContextKey; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.util.Util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@ApiModel("Cause") +public class CachedCause extends CachedObject { + + private Map context = new HashMap<>(); + @ApiModelProperty(value = "The context surrounding the cause", required = true) + public Map getContext() { + return context; + } + + private List causes = new ArrayList<>(); + @ApiModelProperty(value = "The direct sources of this cause", required = true) + public List getCauses() { + return causes; + } + + + public CachedCause(Cause cause) { + super(cause); + + for (Map.Entry, Object> entry : cause.getContext().asMap().entrySet()) { + String key = Util.lowerFirst(entry.getKey().getId()); + context.put(key, WebAPI.getCacheService().asCachedObject(entry.getValue())); + } + + for (Object entry : cause.all()) { + causes.add(WebAPI.getCacheService().asCachedObject(entry)); + } + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/cache/misc/CachedInventory.java b/webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedInventory.java similarity index 96% rename from src/main/java/valandur/webapi/cache/misc/CachedInventory.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedInventory.java index 9f1603cf..57d86d74 100644 --- a/src/main/java/valandur/webapi/cache/misc/CachedInventory.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedInventory.java @@ -1,73 +1,73 @@ -package valandur.webapi.cache.misc; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.item.inventory.Inventory; -import org.spongepowered.api.item.inventory.InventoryArchetype; -import org.spongepowered.api.item.inventory.Slot; -import valandur.webapi.cache.CachedObject; - -import java.util.ArrayList; -import java.util.List; - -@ApiModel("Inventory") -public class CachedInventory extends CachedObject { - - private String name; - @ApiModelProperty(value = "The name of the inventory", required = true) - public String getName() { - return name; - } - - private CachedCatalogType type; - @ApiModelProperty(value = "The type of the inventory", required = true) - public CachedCatalogType getType() { - return type; - } - - private int capacity; - @ApiModelProperty(value = "The maximum capacity of the inventory (maximum number of stacks)", required = true) - public int getCapacity() { - return capacity; - } - - private int totalItems; - @ApiModelProperty(value = "The total amount of items currently in the inventory", required = true) - public int getTotalItems() { - return totalItems; - } - - private List slots; - @ApiModelProperty(value = "Gets a list of slots in the inventory (with their items)", required = true) - public List getSlots() { - return slots; - } - - - public CachedInventory(Inventory inv) { - super(inv, false); - - this.name = inv.getName().get(); - this.capacity = inv.capacity(); - this.totalItems = inv.totalItems(); - this.type = new CachedCatalogType<>(inv.getArchetype()); - - try { - this.slots = new ArrayList<>(); - for (Inventory subInv : inv.slots()) { - if (subInv.totalItems() == 0) { - continue; - } - this.slots.add(new CachedSlot((Slot) subInv)); - } - } catch (AbstractMethodError ignored) {} - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.cache.misc; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.item.inventory.Inventory; +import org.spongepowered.api.item.inventory.InventoryArchetype; +import org.spongepowered.api.item.inventory.Slot; +import valandur.webapi.cache.CachedObject; + +import java.util.ArrayList; +import java.util.List; + +@ApiModel("Inventory") +public class CachedInventory extends CachedObject { + + private String name; + @ApiModelProperty(value = "The name of the inventory", required = true) + public String getName() { + return name; + } + + private CachedCatalogType type; + @ApiModelProperty(value = "The type of the inventory", required = true) + public CachedCatalogType getType() { + return type; + } + + private int capacity; + @ApiModelProperty(value = "The maximum capacity of the inventory (maximum number of stacks)", required = true) + public int getCapacity() { + return capacity; + } + + private int totalItems; + @ApiModelProperty(value = "The total amount of items currently in the inventory", required = true) + public int getTotalItems() { + return totalItems; + } + + private List slots; + @ApiModelProperty(value = "Gets a list of slots in the inventory (with their items)", required = true) + public List getSlots() { + return slots; + } + + + public CachedInventory(Inventory inv) { + super(inv, false); + + this.name = inv.getName().get(); + this.capacity = inv.capacity(); + this.totalItems = inv.totalItems(); + this.type = new CachedCatalogType<>(inv.getArchetype()); + + try { + this.slots = new ArrayList<>(); + for (Inventory subInv : inv.slots()) { + if (subInv.totalItems() == 0) { + continue; + } + this.slots.add(new CachedSlot((Slot) subInv)); + } + } catch (AbstractMethodError ignored) {} + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/cache/misc/CachedSlot.java b/webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedSlot.java similarity index 100% rename from src/main/java/valandur/webapi/cache/misc/CachedSlot.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/misc/CachedSlot.java diff --git a/src/main/java/valandur/webapi/cache/player/CachedAdvancement.java b/webapi-sponge/src/main/java/valandur/webapi/cache/player/CachedAdvancement.java similarity index 96% rename from src/main/java/valandur/webapi/cache/player/CachedAdvancement.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/player/CachedAdvancement.java index 98f49e11..3aa6d6b3 100644 --- a/src/main/java/valandur/webapi/cache/player/CachedAdvancement.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/player/CachedAdvancement.java @@ -1,95 +1,95 @@ -package valandur.webapi.cache.player; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.advancement.Advancement; -import org.spongepowered.api.advancement.AdvancementTree; -import org.spongepowered.api.advancement.DisplayInfo; -import org.spongepowered.api.text.Text; -import valandur.webapi.cache.misc.CachedCatalogType; -import valandur.webapi.serialize.JsonDetails; - -@ApiModel("Advancement") -public class CachedAdvancement extends CachedCatalogType { - - private String id; - @Override - @ApiModelProperty(value = "The unique id of the advancement", required = true) - public String getId() { - return id; - } - - private String name; - @Override - @ApiModelProperty(value = "The name of the advancement", required = true) - public String getName() { - return name; - } - - private Text title; - @ApiModelProperty(value = "The title of the advancement", required = true) - public Text getTitle() { - return title; - } - - private Text description; - @JsonDetails - @ApiModelProperty("The description of the advancement") - public Text getDescription() { - return description; - } - - private boolean announceToChat; - @JsonDetails - @ApiModelProperty("True if the achieving of this advancement is announced in chat, false otherwise") - public boolean isAnnounceToChat() { - return announceToChat; - } - - private boolean showToast; - @JsonDetails - @ApiModelProperty("True if achieving this advancement shows the player a toast message, false otherwise") - public boolean isShowToast() { - return showToast; - } - - private boolean hidden; - @JsonDetails - @ApiModelProperty("True if this is a hidden advancement") - public boolean isHidden() { - return hidden; - } - - private CachedAdvancement parent; - @JsonDetails(simple = true) - @ApiModelProperty("The parent advancement, which must be unlocked prior to this advancement") - public CachedAdvancement getParent() { - return parent; - } - - private CachedCatalogType tree; - @JsonDetails - @ApiModelProperty("The advancement tree that this advancement belongs to") - public CachedCatalogType getTree() { - return tree; - } - - - public CachedAdvancement(Advancement value) { - super(value); - - this.id = value.getId(); - this.name = value.getName(); - this.parent = value.getParent().map(CachedAdvancement::new).orElse(null); - this.tree = value.getTree().map(CachedCatalogType::new).orElse(null); - - if (value.getDisplayInfo().isPresent()) { - DisplayInfo info = value.getDisplayInfo().get(); - this.title = info.getTitle(); - this.description = info.getDescription(); - this.announceToChat = info.doesAnnounceToChat(); - this.showToast = info.doesShowToast(); - this.hidden = info.isHidden(); - } - } -} +package valandur.webapi.cache.player; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.advancement.Advancement; +import org.spongepowered.api.advancement.AdvancementTree; +import org.spongepowered.api.advancement.DisplayInfo; +import org.spongepowered.api.text.Text; +import valandur.webapi.cache.misc.CachedCatalogType; +import valandur.webapi.serialize.JsonDetails; + +@ApiModel("Advancement") +public class CachedAdvancement extends CachedCatalogType { + + private String id; + @Override + @ApiModelProperty(value = "The unique id of the advancement", required = true) + public String getId() { + return id; + } + + private String name; + @Override + @ApiModelProperty(value = "The name of the advancement", required = true) + public String getName() { + return name; + } + + private Text title; + @ApiModelProperty(value = "The title of the advancement", required = true) + public Text getTitle() { + return title; + } + + private Text description; + @JsonDetails + @ApiModelProperty("The description of the advancement") + public Text getDescription() { + return description; + } + + private boolean announceToChat; + @JsonDetails + @ApiModelProperty("True if the achieving of this advancement is announced in chat, false otherwise") + public boolean isAnnounceToChat() { + return announceToChat; + } + + private boolean showToast; + @JsonDetails + @ApiModelProperty("True if achieving this advancement shows the player a toast message, false otherwise") + public boolean isShowToast() { + return showToast; + } + + private boolean hidden; + @JsonDetails + @ApiModelProperty("True if this is a hidden advancement") + public boolean isHidden() { + return hidden; + } + + private CachedAdvancement parent; + @JsonDetails(simple = true) + @ApiModelProperty("The parent advancement, which must be unlocked prior to this advancement") + public CachedAdvancement getParent() { + return parent; + } + + private CachedCatalogType tree; + @JsonDetails + @ApiModelProperty("The advancement tree that this advancement belongs to") + public CachedCatalogType getTree() { + return tree; + } + + + public CachedAdvancement(Advancement value) { + super(value); + + this.id = value.getId(); + this.name = value.getName(); + this.parent = value.getParent().map(CachedAdvancement::new).orElse(null); + this.tree = value.getTree().map(CachedCatalogType::new).orElse(null); + + if (value.getDisplayInfo().isPresent()) { + DisplayInfo info = value.getDisplayInfo().get(); + this.title = info.getTitle(); + this.description = info.getDescription(); + this.announceToChat = info.doesAnnounceToChat(); + this.showToast = info.doesShowToast(); + this.hidden = info.isHidden(); + } + } +} diff --git a/src/main/java/valandur/webapi/cache/player/CachedPlayer.java b/webapi-sponge/src/main/java/valandur/webapi/cache/player/CachedPlayer.java similarity index 100% rename from src/main/java/valandur/webapi/cache/player/CachedPlayer.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/player/CachedPlayer.java diff --git a/src/main/java/valandur/webapi/cache/plugin/CachedPluginContainer.java b/webapi-sponge/src/main/java/valandur/webapi/cache/plugin/CachedPluginContainer.java similarity index 100% rename from src/main/java/valandur/webapi/cache/plugin/CachedPluginContainer.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/plugin/CachedPluginContainer.java diff --git a/src/main/java/valandur/webapi/cache/plugin/CachedPluginDependency.java b/webapi-sponge/src/main/java/valandur/webapi/cache/plugin/CachedPluginDependency.java similarity index 96% rename from src/main/java/valandur/webapi/cache/plugin/CachedPluginDependency.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/plugin/CachedPluginDependency.java index bc602943..0f8f6c27 100644 --- a/src/main/java/valandur/webapi/cache/plugin/CachedPluginDependency.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/plugin/CachedPluginDependency.java @@ -1,67 +1,67 @@ -package valandur.webapi.cache.plugin; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.plugin.meta.PluginDependency; -import valandur.webapi.cache.CachedObject; - -import java.util.Optional; - -import static org.spongepowered.plugin.meta.PluginDependency.LoadOrder; - -@ApiModel("PluginDependency") -public class CachedPluginDependency extends CachedObject { - - private String id; - @ApiModelProperty(value = "The id of the plugin that the original plugin depends on", required = true) - public String getId() { - return id; - } - - private LoadOrder loadOrder; - @ApiModelProperty(value = "The load order of the original plugin in relation to the dependency", required = true) - public LoadOrder getLoadOrder() { - return loadOrder; - } - - private String version; - @ApiModelProperty(value = "The version of the plugin that the original plugin depends on", required = true) - public String getVersion() { - return version; - } - - private Boolean optional; - @ApiModelProperty(value = "True if this is an optional dependency, false otherwise", required = true) - public Boolean isOptional() { - return optional; - } - - - public CachedPluginDependency(PluginDependency dependency) { - super(dependency); - - this.id = dependency.getId(); - this.version = dependency.getVersion(); - this.loadOrder = dependency.getLoadOrder(); - this.optional = dependency.isOptional(); - } - public CachedPluginDependency(String id, boolean optional) { - super(null); - - this.id = id; - this.optional = optional; - } - - @Override - public Optional getLive() { - return Optional.of(new PluginDependency(loadOrder, id, version, optional)); - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.cache.plugin; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.plugin.meta.PluginDependency; +import valandur.webapi.cache.CachedObject; + +import java.util.Optional; + +import static org.spongepowered.plugin.meta.PluginDependency.LoadOrder; + +@ApiModel("PluginDependency") +public class CachedPluginDependency extends CachedObject { + + private String id; + @ApiModelProperty(value = "The id of the plugin that the original plugin depends on", required = true) + public String getId() { + return id; + } + + private LoadOrder loadOrder; + @ApiModelProperty(value = "The load order of the original plugin in relation to the dependency", required = true) + public LoadOrder getLoadOrder() { + return loadOrder; + } + + private String version; + @ApiModelProperty(value = "The version of the plugin that the original plugin depends on", required = true) + public String getVersion() { + return version; + } + + private Boolean optional; + @ApiModelProperty(value = "True if this is an optional dependency, false otherwise", required = true) + public Boolean isOptional() { + return optional; + } + + + public CachedPluginDependency(PluginDependency dependency) { + super(dependency); + + this.id = dependency.getId(); + this.version = dependency.getVersion(); + this.loadOrder = dependency.getLoadOrder(); + this.optional = dependency.isOptional(); + } + public CachedPluginDependency(String id, boolean optional) { + super(null); + + this.id = id; + this.optional = optional; + } + + @Override + public Optional getLive() { + return Optional.of(new PluginDependency(loadOrder, id, version, optional)); + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/cache/tileentity/CachedTileEntity.java b/webapi-sponge/src/main/java/valandur/webapi/cache/tileentity/CachedTileEntity.java similarity index 100% rename from src/main/java/valandur/webapi/cache/tileentity/CachedTileEntity.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/tileentity/CachedTileEntity.java diff --git a/src/main/java/valandur/webapi/cache/world/CachedChunk.java b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedChunk.java similarity index 97% rename from src/main/java/valandur/webapi/cache/world/CachedChunk.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedChunk.java index 1e38b723..ae5f5093 100644 --- a/src/main/java/valandur/webapi/cache/world/CachedChunk.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedChunk.java @@ -1,107 +1,107 @@ -package valandur.webapi.cache.world; - -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.world.Chunk; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.util.Constants; - -import java.util.Optional; -import java.util.UUID; - -@ApiModel("Chunk") -public class CachedChunk extends CachedObject { - - private UUID uuid; - @ApiModelProperty(value = "The unique id of this chunk", required = true) - public UUID getUUID() { - return uuid; - } - - private Vector3i pos; - @ApiModelProperty(value = "The position of this chunk (in chunk coordinates)", required = true) - public Vector3i getPosition() { - return pos; - } - - private CachedWorld world; - @JsonDetails(simple = true) - @ApiModelProperty("The world the chunk is in") - public CachedWorld getWorld() { - return world; - } - - private boolean loaded; - @ApiModelProperty(value = "True if this chunk is currently loaded, false otherwise", required = true) - public boolean isLoaded() { - return loaded; - } - - private Vector3i blockMin; - @JsonDetails - @ApiModelProperty("The bock with the smallest coordinates that is still part of this chunk") - public Vector3i getBlockMin() { - return blockMin; - } - - private Vector3i blockMax; - @JsonDetails - @ApiModelProperty("The bock with the largest coordinates that is still part of this chunk") - public Vector3i getBlockMax() { - return blockMax; - } - - private int inhabitedTime; - @JsonDetails - @ApiModelProperty("The total amount of time (in server ticks) this chunk has been inhabited by players.") - public int getInhabitedTime() { - return inhabitedTime; - } - - private double regionalDifficultyFactor; - @JsonDetails - @ApiModelProperty("The increase in difficulty due to the presence of players in the chunk") - public double getRegionalDifficultyFactor() { - return regionalDifficultyFactor; - } - - private double regionalDifficultyPercentage; - @JsonDetails - @ApiModelProperty("The increase in difficulty due to the presence of players in the chunk as a percentage") - public double getRegionalDifficultyPercentage() { - return regionalDifficultyPercentage; - } - - - public CachedChunk(Chunk chunk) { - super(chunk); - - this.uuid = UUID.fromString(chunk.getUniqueId().toString()); - this.pos = chunk.getPosition().clone(); - this.world = WebAPI.getCacheService().getWorld(chunk.getWorld()); - this.blockMin = chunk.getBlockMin().clone(); - this.blockMax = chunk.getBlockMax().clone(); - this.loaded = chunk.isLoaded(); - this.inhabitedTime = chunk.getInhabitedTime(); - this.regionalDifficultyFactor = chunk.getRegionalDifficultyFactor(); - this.regionalDifficultyPercentage = chunk.getRegionalDifficultyPercentage(); - } - - @Override - public Optional getLive() { - if (world.isLoaded()) { - return Sponge.getServer().getWorld(uuid).flatMap(w -> w.getChunk(pos)); - } else { - return Optional.empty(); - } - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/chunk/" + world.getUUID() + "/" + pos.getX() + "/" + pos.getZ(); - } -} +package valandur.webapi.cache.world; + +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.world.Chunk; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.util.Constants; + +import java.util.Optional; +import java.util.UUID; + +@ApiModel("Chunk") +public class CachedChunk extends CachedObject { + + private UUID uuid; + @ApiModelProperty(value = "The unique id of this chunk", required = true) + public UUID getUUID() { + return uuid; + } + + private Vector3i pos; + @ApiModelProperty(value = "The position of this chunk (in chunk coordinates)", required = true) + public Vector3i getPosition() { + return pos; + } + + private CachedWorld world; + @JsonDetails(simple = true) + @ApiModelProperty("The world the chunk is in") + public CachedWorld getWorld() { + return world; + } + + private boolean loaded; + @ApiModelProperty(value = "True if this chunk is currently loaded, false otherwise", required = true) + public boolean isLoaded() { + return loaded; + } + + private Vector3i blockMin; + @JsonDetails + @ApiModelProperty("The bock with the smallest coordinates that is still part of this chunk") + public Vector3i getBlockMin() { + return blockMin; + } + + private Vector3i blockMax; + @JsonDetails + @ApiModelProperty("The bock with the largest coordinates that is still part of this chunk") + public Vector3i getBlockMax() { + return blockMax; + } + + private int inhabitedTime; + @JsonDetails + @ApiModelProperty("The total amount of time (in server ticks) this chunk has been inhabited by players.") + public int getInhabitedTime() { + return inhabitedTime; + } + + private double regionalDifficultyFactor; + @JsonDetails + @ApiModelProperty("The increase in difficulty due to the presence of players in the chunk") + public double getRegionalDifficultyFactor() { + return regionalDifficultyFactor; + } + + private double regionalDifficultyPercentage; + @JsonDetails + @ApiModelProperty("The increase in difficulty due to the presence of players in the chunk as a percentage") + public double getRegionalDifficultyPercentage() { + return regionalDifficultyPercentage; + } + + + public CachedChunk(Chunk chunk) { + super(chunk); + + this.uuid = UUID.fromString(chunk.getUniqueId().toString()); + this.pos = chunk.getPosition().clone(); + this.world = WebAPI.getCacheService().getWorld(chunk.getWorld()); + this.blockMin = chunk.getBlockMin().clone(); + this.blockMax = chunk.getBlockMax().clone(); + this.loaded = chunk.isLoaded(); + this.inhabitedTime = chunk.getInhabitedTime(); + this.regionalDifficultyFactor = chunk.getRegionalDifficultyFactor(); + this.regionalDifficultyPercentage = chunk.getRegionalDifficultyPercentage(); + } + + @Override + public Optional getLive() { + if (world.isLoaded()) { + return Sponge.getServer().getWorld(uuid).flatMap(w -> w.getChunk(pos)); + } else { + return Optional.empty(); + } + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/chunk/" + world.getUUID() + "/" + pos.getX() + "/" + pos.getZ(); + } +} diff --git a/src/main/java/valandur/webapi/cache/world/CachedLocation.java b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedLocation.java similarity index 96% rename from src/main/java/valandur/webapi/cache/world/CachedLocation.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedLocation.java index 5a325e85..21458641 100644 --- a/src/main/java/valandur/webapi/cache/world/CachedLocation.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedLocation.java @@ -1,62 +1,62 @@ -package valandur.webapi.cache.world; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.flowpowered.math.vector.Vector3d; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.serialize.JsonDetails; - -import java.util.Optional; - -@ApiModel("Location") -public class CachedLocation extends CachedObject { - - private CachedWorld world; - @ApiModelProperty(value = "The world this location refers to", required = true) - @JsonDetails(value = false, simple = true) - public CachedWorld getWorld() { - return world; - } - - private Vector3d position; - @ApiModelProperty(value = "The position within the world that this location refers to", required = true) - public Vector3d getPosition() { - return position; - } - - - public CachedLocation(String worldNameOrUuid, double x, double y, double z) { - super(null); - - this.world = cacheService.getWorld(worldNameOrUuid).orElse(null); - this.position = new Vector3d(x, y, z); - } - public CachedLocation(CachedWorld world, double x, double y, double z) { - super(null); - - this.world = world; - this.position = new Vector3d(x, y, z); - } - public CachedLocation(Location location) { - super(null); - - this.world = cacheService.getWorld(location.getExtent()); - this.position = location.getPosition().clone(); - } - - @Override - public Optional getLive() { - Optional optWorld = world.getLive(); - return optWorld.map(w -> new Location<>(w, position)); - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.cache.world; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.flowpowered.math.vector.Vector3d; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.world.Location; +import org.spongepowered.api.world.World; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.serialize.JsonDetails; + +import java.util.Optional; + +@ApiModel("Location") +public class CachedLocation extends CachedObject { + + private CachedWorld world; + @ApiModelProperty(value = "The world this location refers to", required = true) + @JsonDetails(value = false, simple = true) + public CachedWorld getWorld() { + return world; + } + + private Vector3d position; + @ApiModelProperty(value = "The position within the world that this location refers to", required = true) + public Vector3d getPosition() { + return position; + } + + + public CachedLocation(String worldNameOrUuid, double x, double y, double z) { + super(null); + + this.world = cacheService.getWorld(worldNameOrUuid).orElse(null); + this.position = new Vector3d(x, y, z); + } + public CachedLocation(CachedWorld world, double x, double y, double z) { + super(null); + + this.world = world; + this.position = new Vector3d(x, y, z); + } + public CachedLocation(Location location) { + super(null); + + this.world = cacheService.getWorld(location.getExtent()); + this.position = location.getPosition().clone(); + } + + @Override + public Optional getLive() { + Optional optWorld = world.getLive(); + return optWorld.map(w -> new Location<>(w, position)); + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/cache/world/CachedTransform.java b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedTransform.java similarity index 96% rename from src/main/java/valandur/webapi/cache/world/CachedTransform.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedTransform.java index 6af83c58..8b45cb00 100644 --- a/src/main/java/valandur/webapi/cache/world/CachedTransform.java +++ b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedTransform.java @@ -1,64 +1,64 @@ -package valandur.webapi.cache.world; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.flowpowered.math.vector.Vector3d; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.entity.Transform; -import org.spongepowered.api.world.World; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.serialize.JsonDetails; - -import java.util.Optional; - -@ApiModel("Transform") -public class CachedTransform extends CachedObject { - - private CachedWorld world; - @JsonDetails(value = false, simple = true) - @ApiModelProperty(value = "The world of this transform", required = true) - public CachedWorld getWorld() { - return world; - } - - private Vector3d position; - @ApiModelProperty(value = "The position within the world", required = true) - public Vector3d getPosition() { - return position; - } - - private Vector3d rotation; - @ApiModelProperty(value = "The rotation of the object", required = true) - public Vector3d getRotation() { - return rotation; - } - - private Vector3d scale; - @ApiModelProperty(value = "The scale of the object", required = true) - public Vector3d getScale() { - return scale; - } - - - public CachedTransform(Transform transform) { - super(null); - - this.world = cacheService.getWorld(transform.getExtent()); - this.position = transform.getPosition().clone(); - this.rotation = transform.getRotation().clone(); - this.scale = transform.getScale().clone(); - } - - @Override - public Optional getLive() { - Optional optWorld = world.getLive(); - return optWorld.map(w -> new Transform<>(w, position)); - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.cache.world; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.flowpowered.math.vector.Vector3d; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.entity.Transform; +import org.spongepowered.api.world.World; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.serialize.JsonDetails; + +import java.util.Optional; + +@ApiModel("Transform") +public class CachedTransform extends CachedObject { + + private CachedWorld world; + @JsonDetails(value = false, simple = true) + @ApiModelProperty(value = "The world of this transform", required = true) + public CachedWorld getWorld() { + return world; + } + + private Vector3d position; + @ApiModelProperty(value = "The position within the world", required = true) + public Vector3d getPosition() { + return position; + } + + private Vector3d rotation; + @ApiModelProperty(value = "The rotation of the object", required = true) + public Vector3d getRotation() { + return rotation; + } + + private Vector3d scale; + @ApiModelProperty(value = "The scale of the object", required = true) + public Vector3d getScale() { + return scale; + } + + + public CachedTransform(Transform transform) { + super(null); + + this.world = cacheService.getWorld(transform.getExtent()); + this.position = transform.getPosition().clone(); + this.rotation = transform.getRotation().clone(); + this.scale = transform.getScale().clone(); + } + + @Override + public Optional getLive() { + Optional optWorld = world.getLive(); + return optWorld.map(w -> new Transform<>(w, position)); + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/cache/world/CachedWorld.java b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedWorld.java similarity index 100% rename from src/main/java/valandur/webapi/cache/world/CachedWorld.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedWorld.java diff --git a/src/main/java/valandur/webapi/cache/world/CachedWorldBorder.java b/webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedWorldBorder.java similarity index 100% rename from src/main/java/valandur/webapi/cache/world/CachedWorldBorder.java rename to webapi-sponge/src/main/java/valandur/webapi/cache/world/CachedWorldBorder.java diff --git a/src/main/java/valandur/webapi/command/CommandRegistry.java b/webapi-sponge/src/main/java/valandur/webapi/command/CommandRegistry.java similarity index 100% rename from src/main/java/valandur/webapi/command/CommandRegistry.java rename to webapi-sponge/src/main/java/valandur/webapi/command/CommandRegistry.java diff --git a/src/main/java/valandur/webapi/command/CommandSource.java b/webapi-sponge/src/main/java/valandur/webapi/command/CommandSource.java similarity index 100% rename from src/main/java/valandur/webapi/command/CommandSource.java rename to webapi-sponge/src/main/java/valandur/webapi/command/CommandSource.java diff --git a/src/main/java/valandur/webapi/command/auth/CmdAuthListAdd.java b/webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListAdd.java similarity index 100% rename from src/main/java/valandur/webapi/command/auth/CmdAuthListAdd.java rename to webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListAdd.java diff --git a/src/main/java/valandur/webapi/command/auth/CmdAuthListDisable.java b/webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListDisable.java similarity index 100% rename from src/main/java/valandur/webapi/command/auth/CmdAuthListDisable.java rename to webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListDisable.java diff --git a/src/main/java/valandur/webapi/command/auth/CmdAuthListEnable.java b/webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListEnable.java similarity index 100% rename from src/main/java/valandur/webapi/command/auth/CmdAuthListEnable.java rename to webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListEnable.java diff --git a/src/main/java/valandur/webapi/command/auth/CmdAuthListRemove.java b/webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListRemove.java similarity index 100% rename from src/main/java/valandur/webapi/command/auth/CmdAuthListRemove.java rename to webapi-sponge/src/main/java/valandur/webapi/command/auth/CmdAuthListRemove.java diff --git a/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesList.java b/webapi-sponge/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesList.java similarity index 100% rename from src/main/java/valandur/webapi/command/block/CmdBlockUpdatesList.java rename to webapi-sponge/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesList.java diff --git a/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesPause.java b/webapi-sponge/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesPause.java similarity index 100% rename from src/main/java/valandur/webapi/command/block/CmdBlockUpdatesPause.java rename to webapi-sponge/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesPause.java diff --git a/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesStop.java b/webapi-sponge/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesStop.java similarity index 100% rename from src/main/java/valandur/webapi/command/block/CmdBlockUpdatesStop.java rename to webapi-sponge/src/main/java/valandur/webapi/command/block/CmdBlockUpdatesStop.java diff --git a/src/main/java/valandur/webapi/command/element/CmdIpElement.java b/webapi-sponge/src/main/java/valandur/webapi/command/element/CmdIpElement.java similarity index 100% rename from src/main/java/valandur/webapi/command/element/CmdIpElement.java rename to webapi-sponge/src/main/java/valandur/webapi/command/element/CmdIpElement.java diff --git a/src/main/java/valandur/webapi/command/hook/CmdNotifyHook.java b/webapi-sponge/src/main/java/valandur/webapi/command/hook/CmdNotifyHook.java similarity index 100% rename from src/main/java/valandur/webapi/command/hook/CmdNotifyHook.java rename to webapi-sponge/src/main/java/valandur/webapi/command/hook/CmdNotifyHook.java diff --git a/src/main/java/valandur/webapi/command/user/CmdUserAdd.java b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserAdd.java similarity index 97% rename from src/main/java/valandur/webapi/command/user/CmdUserAdd.java rename to webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserAdd.java index f548ba4a..bc887c51 100644 --- a/src/main/java/valandur/webapi/command/user/CmdUserAdd.java +++ b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserAdd.java @@ -1,51 +1,51 @@ -package valandur.webapi.command.user; - -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; -import valandur.webapi.WebAPI; -import valandur.webapi.security.SecurityService; -import valandur.webapi.user.UserPermissionStruct; -import valandur.webapi.util.Util; - -import java.util.Optional; - -public class CmdUserAdd implements CommandExecutor { - - @Override - public CommandResult execute(CommandSource src, CommandContext args) { - Optional optUsername = args.getOne("username"); - if (!optUsername.isPresent()) { - return CommandResult.empty(); - } - String username = optUsername.get(); - - Optional optPassword = args.getOne("password"); - String password = optPassword.orElse(Util.generateUniqueId().substring(0, 8)); - - Optional optUser = WebAPI.getUserService().addUser( - username, password, SecurityService.permitAllNode()); - - if (!optUser.isPresent()) { - src.sendMessage(Text.builder("A user with this name already exists").color(TextColors.RED).build()); - return CommandResult.empty(); - } - - if (!optPassword.isPresent()) { - src.sendMessage(Text.builder("Created user ") - .append(Text.builder(username).color(TextColors.GOLD).build()) - .append(Text.of(" with password ")) - .append(Text.builder(password).color(TextColors.GOLD).build()) - .build()); - } else { - src.sendMessage(Text.builder("Created user ") - .append(Text.builder(username).color(TextColors.GOLD).build()) - .build()); - } - - return CommandResult.success(); - } -} +package valandur.webapi.command.user; + +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.format.TextColors; +import valandur.webapi.WebAPI; +import valandur.webapi.security.SecurityService; +import valandur.webapi.user.UserPermissionStruct; +import valandur.webapi.util.Util; + +import java.util.Optional; + +public class CmdUserAdd implements CommandExecutor { + + @Override + public CommandResult execute(CommandSource src, CommandContext args) { + Optional optUsername = args.getOne("username"); + if (!optUsername.isPresent()) { + return CommandResult.empty(); + } + String username = optUsername.get(); + + Optional optPassword = args.getOne("password"); + String password = optPassword.orElse(Util.generateUniqueId().substring(0, 8)); + + Optional optUser = WebAPI.getUserService().addUser( + username, password, SecurityService.permitAllNode()); + + if (!optUser.isPresent()) { + src.sendMessage(Text.builder("A user with this name already exists").color(TextColors.RED).build()); + return CommandResult.empty(); + } + + if (!optPassword.isPresent()) { + src.sendMessage(Text.builder("Created user ") + .append(Text.builder(username).color(TextColors.GOLD).build()) + .append(Text.of(" with password ")) + .append(Text.builder(password).color(TextColors.GOLD).build()) + .build()); + } else { + src.sendMessage(Text.builder("Created user ") + .append(Text.builder(username).color(TextColors.GOLD).build()) + .build()); + } + + return CommandResult.success(); + } +} diff --git a/src/main/java/valandur/webapi/command/user/CmdUserChangePassword.java b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserChangePassword.java similarity index 97% rename from src/main/java/valandur/webapi/command/user/CmdUserChangePassword.java rename to webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserChangePassword.java index 0a2f418b..79fbfa46 100644 --- a/src/main/java/valandur/webapi/command/user/CmdUserChangePassword.java +++ b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserChangePassword.java @@ -1,50 +1,50 @@ -package valandur.webapi.command.user; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; -import valandur.webapi.WebAPI; -import valandur.webapi.user.UserPermissionStruct; -import valandur.webapi.user.UserService; - -import java.util.Optional; - -public class CmdUserChangePassword implements CommandExecutor { - - @Override - public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { - Optional optUsername = args.getOne("username"); - if (!optUsername.isPresent()) { - return CommandResult.empty(); - } - String username = optUsername.get(); - - Optional optPassword = args.getOne("password"); - if (!optPassword.isPresent()) { - return CommandResult.empty(); - } - String password = optPassword.get(); - - UserService srv = WebAPI.getUserService(); - - Optional optUser = srv.getUser(username); - if (!optUser.isPresent()) { - src.sendMessage(Text.builder("Could not find user '" + username + "'").color(TextColors.RED).build()); - return CommandResult.empty(); - } - - UserPermissionStruct user = optUser.get(); - - user.setPassword(srv.hashPassword(password)); - src.sendMessage(Text.builder("Changed password for ") - .append(Text.builder(username).color(TextColors.GOLD).build()) - .build()); - - srv.save(); - return CommandResult.success(); - } -} +package valandur.webapi.command.user; + +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.format.TextColors; +import valandur.webapi.WebAPI; +import valandur.webapi.user.UserPermissionStruct; +import valandur.webapi.user.UserService; + +import java.util.Optional; + +public class CmdUserChangePassword implements CommandExecutor { + + @Override + public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { + Optional optUsername = args.getOne("username"); + if (!optUsername.isPresent()) { + return CommandResult.empty(); + } + String username = optUsername.get(); + + Optional optPassword = args.getOne("password"); + if (!optPassword.isPresent()) { + return CommandResult.empty(); + } + String password = optPassword.get(); + + UserService srv = WebAPI.getUserService(); + + Optional optUser = srv.getUser(username); + if (!optUser.isPresent()) { + src.sendMessage(Text.builder("Could not find user '" + username + "'").color(TextColors.RED).build()); + return CommandResult.empty(); + } + + UserPermissionStruct user = optUser.get(); + + user.setPassword(srv.hashPassword(password)); + src.sendMessage(Text.builder("Changed password for ") + .append(Text.builder(username).color(TextColors.GOLD).build()) + .build()); + + srv.save(); + return CommandResult.success(); + } +} diff --git a/src/main/java/valandur/webapi/command/user/CmdUserList.java b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserList.java similarity index 97% rename from src/main/java/valandur/webapi/command/user/CmdUserList.java rename to webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserList.java index c0b58fca..ddf65024 100644 --- a/src/main/java/valandur/webapi/command/user/CmdUserList.java +++ b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserList.java @@ -1,41 +1,41 @@ -package valandur.webapi.command.user; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.service.pagination.PaginationList; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.action.TextActions; -import org.spongepowered.api.text.format.TextColors; -import valandur.webapi.WebAPI; -import valandur.webapi.user.UserPermissionStruct; - -import java.util.Collection; -import java.util.stream.Collectors; - -public class CmdUserList implements CommandExecutor { - - @Override - public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { - Collection users = WebAPI.getUserService().getUsers(); - PaginationList.builder() - .title(Text.of("Web-API users")) - .contents(users.stream().map(u -> { - Text editUser = Text.builder("[Change pw]") - .color(TextColors.YELLOW) - .onClick(TextActions.suggestCommand("/webapi users changepw " + u.getName() + " ")) - .build(); - - Text rmvUser = Text.builder(" [Remove]") - .color(TextColors.RED) - .onClick(TextActions.suggestCommand("/webapi users remove " + u.getName())) - .build(); - - return Text.builder(u.getName() + " ").append(editUser, rmvUser).build(); - }).collect(Collectors.toList())) - .sendTo(src); - return CommandResult.success(); - } -} +package valandur.webapi.command.user; + +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.service.pagination.PaginationList; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.action.TextActions; +import org.spongepowered.api.text.format.TextColors; +import valandur.webapi.WebAPI; +import valandur.webapi.user.UserPermissionStruct; + +import java.util.Collection; +import java.util.stream.Collectors; + +public class CmdUserList implements CommandExecutor { + + @Override + public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { + Collection users = WebAPI.getUserService().getUsers(); + PaginationList.builder() + .title(Text.of("Web-API users")) + .contents(users.stream().map(u -> { + Text editUser = Text.builder("[Change pw]") + .color(TextColors.YELLOW) + .onClick(TextActions.suggestCommand("/webapi users changepw " + u.getName() + " ")) + .build(); + + Text rmvUser = Text.builder(" [Remove]") + .color(TextColors.RED) + .onClick(TextActions.suggestCommand("/webapi users remove " + u.getName())) + .build(); + + return Text.builder(u.getName() + " ").append(editUser, rmvUser).build(); + }).collect(Collectors.toList())) + .sendTo(src); + return CommandResult.success(); + } +} diff --git a/src/main/java/valandur/webapi/command/user/CmdUserRemove.java b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserRemove.java similarity index 97% rename from src/main/java/valandur/webapi/command/user/CmdUserRemove.java rename to webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserRemove.java index 12331b92..5460eb5c 100644 --- a/src/main/java/valandur/webapi/command/user/CmdUserRemove.java +++ b/webapi-sponge/src/main/java/valandur/webapi/command/user/CmdUserRemove.java @@ -1,38 +1,38 @@ -package valandur.webapi.command.user; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; -import valandur.webapi.WebAPI; -import valandur.webapi.user.UserPermissionStruct; - -import java.util.Optional; - -public class CmdUserRemove implements CommandExecutor { - - @Override - public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { - Optional optUsername = args.getOne("username"); - if (!optUsername.isPresent()) { - return CommandResult.empty(); - } - String username = optUsername.get(); - - Optional optUser = WebAPI.getUserService().removeUser(username); - if (!optUser.isPresent()) { - src.sendMessage(Text.builder("Couldn't find user to remove " + username) - .color(TextColors.RED).build()); - return CommandResult.empty(); - } - - src.sendMessage(Text.builder("Removed user ") - .append(Text.builder(username).color(TextColors.GOLD).build()) - .build()); - - return CommandResult.success(); - } -} +package valandur.webapi.command.user; + +import org.spongepowered.api.command.CommandException; +import org.spongepowered.api.command.CommandResult; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandExecutor; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.format.TextColors; +import valandur.webapi.WebAPI; +import valandur.webapi.user.UserPermissionStruct; + +import java.util.Optional; + +public class CmdUserRemove implements CommandExecutor { + + @Override + public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { + Optional optUsername = args.getOne("username"); + if (!optUsername.isPresent()) { + return CommandResult.empty(); + } + String username = optUsername.get(); + + Optional optUser = WebAPI.getUserService().removeUser(username); + if (!optUser.isPresent()) { + src.sendMessage(Text.builder("Couldn't find user to remove " + username) + .color(TextColors.RED).build()); + return CommandResult.empty(); + } + + src.sendMessage(Text.builder("Removed user ") + .append(Text.builder(username).color(TextColors.GOLD).build()) + .build()); + + return CommandResult.success(); + } +} diff --git a/src/main/java/valandur/webapi/config/BlockConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/BlockConfig.java similarity index 100% rename from src/main/java/valandur/webapi/config/BlockConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/BlockConfig.java diff --git a/src/main/java/valandur/webapi/config/CacheConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/CacheConfig.java similarity index 97% rename from src/main/java/valandur/webapi/config/CacheConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/CacheConfig.java index 96ec4f1e..2f1c5a6f 100644 --- a/src/main/java/valandur/webapi/config/CacheConfig.java +++ b/webapi-sponge/src/main/java/valandur/webapi/config/CacheConfig.java @@ -1,28 +1,28 @@ -package valandur.webapi.config; - -import com.google.common.collect.Lists; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@ConfigSerializable -public class CacheConfig extends BaseConfig { - - @Setting(comment = "The number of entries that are saved. This defines how \"far back\" the history goes.") - public int chat_amount = 100; - - @Setting(comment = "The number of entries that are saved. This defines how \"far back\" the history goes.") - public int cmd_amount = 100; - - @Setting(comment = "The number of seconds that the different types of data is cached for") - public Map duration = new HashMap<>(); - - @Setting(comment = "These are commands that should not show up in the command log.\n" + - "For example if you have a second auth plugin, or something where\n" + - "players enter private data, put the command here, so that it's\n" + - "filtered from the logs, and also won't show up in the admin panel.") - public List censoredCommands = Lists.newArrayList("register", "reg", "login", "password", "pass"); -} +package valandur.webapi.config; + +import com.google.common.collect.Lists; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@ConfigSerializable +public class CacheConfig extends BaseConfig { + + @Setting(comment = "The number of entries that are saved. This defines how \"far back\" the history goes.") + public int chat_amount = 100; + + @Setting(comment = "The number of entries that are saved. This defines how \"far back\" the history goes.") + public int cmd_amount = 100; + + @Setting(comment = "The number of seconds that the different types of data is cached for") + public Map duration = new HashMap<>(); + + @Setting(comment = "These are commands that should not show up in the command log.\n" + + "For example if you have a second auth plugin, or something where\n" + + "players enter private data, put the command here, so that it's\n" + + "filtered from the logs, and also won't show up in the admin panel.") + public List censoredCommands = Lists.newArrayList("register", "reg", "login", "password", "pass"); +} diff --git a/src/main/java/valandur/webapi/config/HookConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/HookConfig.java similarity index 98% rename from src/main/java/valandur/webapi/config/HookConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/HookConfig.java index b8f9197a..50667490 100644 --- a/src/main/java/valandur/webapi/config/HookConfig.java +++ b/webapi-sponge/src/main/java/valandur/webapi/config/HookConfig.java @@ -1,177 +1,177 @@ -package valandur.webapi.config; - -import com.google.common.collect.Lists; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import valandur.webapi.hook.CommandWebHook; -import valandur.webapi.hook.WebHook; -import valandur.webapi.hook.WebHookHeader; -import valandur.webapi.hook.WebHookParam; -import valandur.webapi.hook.WebHookService.WebHookType; -import valandur.webapi.security.SecurityService; - -import javax.ws.rs.HttpMethod; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@ConfigSerializable -public class HookConfig extends BaseConfig { - - private static Map defaultCommandHooks() { - Map hooks = new HashMap<>(); - hooks.put("test", new CommandWebHook( - false, - Lists.newArrayList("test"), - Lists.newArrayList( - new WebHookParam("player", WebHookParam.WebHookParamType.PLAYER, false), - new WebHookParam("world", WebHookParam.WebHookParamType.WORLD, true) - ), - Lists.newArrayList( - new WebHook( - "http://localhost/test/{player}", - false, - HttpMethod.POST, - WebHook.WebHookDataType.JSON, - false, - Lists.newArrayList(new WebHookHeader("X-SUPER-SECRET", "my_secret_to_verify")), - true, - SecurityService.permitAllNode() - ) - ) - )); - return hooks; - } - - @Setting(comment = "The following are event hooks which are all called when the specified event happens. They get passed various data\n" + - "in the body (if method != GET, described below for each event). The format of the hooks is described in the \"all\"\n" + - "event hook. This format can be used for any of the hook lists.\n" + - "Please note that the hooks don't get called in any particular order, and might even be called concurrently.") - public HookEvents events = new HookEvents(); - - @Setting(comment = "These hooks can be used to bind to custom events. You have to use the fully qualified class name as the key, and then\n" + - "a hook list just like for the event hooks. These hooks work just like the event hooks, although the data\n" + - "depends on the event you subscribe to.") - public Map> custom = new HashMap<>(); - - @Setting(comment = "The endpoints here get called when executing the specified command. " + - "For example the hook \"test\" would get executed\n" + - "when running the command /webapi notify test") - public Map command = defaultCommandHooks(); - - - @ConfigSerializable - public static class HookEvents { - @Setting(comment = "This event is fired for all events. The \"X-WebAPI-Event\" header specifies the exact event.") - public List all = Lists.newArrayList(new WebHook( - "http://localhost/test", - false, - HttpMethod.POST, - WebHook.WebHookDataType.JSON, - false, - Lists.newArrayList(new WebHookHeader("X-SUPER-SECRET", "my_secret_to_verify")), - true, - SecurityService.permitAllNode() - )); - - @Setting(comment = "This event is fired when a player earns an achievement / advancement") - public List achievement = new ArrayList<>(); - - @Setting(comment = "This event is fired when a block operation changes status") - public List block_operation_status = new ArrayList<>(); - - @Setting(comment = "This event is fired when a chat message is sent on the server") - public List chat = new ArrayList<>(); - - @Setting(comment = "This event is fired when a command is executed") - public List command = new ArrayList<>(); - - @Setting(comment = "This event is fired when a player clicks one of the options of an interactive message") - public List interactive_message = new ArrayList<>(); - - @Setting(comment = "This event is fired when a chunk is generated") - public List generate_chunk = new ArrayList<>(); - - @Setting(comment = "This event is fired when an explosion occurs") - public List explosion = new ArrayList<>(); - - @Setting(comment = "This event is fired when an entity spawns") - public List entity_spawn = new ArrayList<>(); - - @Setting(comment = "This event is fired when an entity despawns") - public List entity_despawn = new ArrayList<>(); - - @Setting(comment = "This event is fired when an entity expires") - public List entity_expire = new ArrayList<>(); - - @Setting(comment = "This event is fired when a player interacts with a block") - public List interact_block = new ArrayList<>(); - - @Setting(comment = "This event is fired when an inventory is opened") - public List inventory_open = new ArrayList<>(); - - @Setting(comment = "This event is fired when an inventory is closed") - public List inventory_close = new ArrayList<>(); - - @Setting(comment = "This event is fired when a player joins the server") - public List player_join = new ArrayList<>(); - - @Setting(comment = "This event is fired when a player leaves the server") - public List player_leave = new ArrayList<>(); - - @Setting(comment = "This event is fired when a player dies") - public List player_death = new ArrayList<>(); - - @Setting(comment = "This event is fired when a player gets kicked") - public List player_kick = new ArrayList<>(); - - @Setting(comment = "This event is fired when a player gets banned") - public List player_ban = new ArrayList<>(); - - @Setting(comment = "This event is fired when the server starts") - public List server_start = new ArrayList<>(); - - @Setting(comment = "This event is fired when the server stops") - public List server_stop = new ArrayList<>(); - - @Setting(comment = "This event is fired when the world is saved") - public List world_save = new ArrayList<>(); - - @Setting(comment = "This event is fired when a world is loaded") - public List world_load = new ArrayList<>(); - - @Setting(comment = "This event is fired when a world is unloaded") - public List world_unload = new ArrayList<>(); - - - public Map> asMap() { - Map> hooks = new HashMap<>(); - hooks.put(WebHookType.ALL, this.all); - hooks.put(WebHookType.ADVANCEMENT, this.achievement); - hooks.put(WebHookType.BLOCK_OPERATION_STATUS, this.block_operation_status); - hooks.put(WebHookType.CHAT, this.chat); - hooks.put(WebHookType.COMMAND, this.command); - hooks.put(WebHookType.INTERACTIVE_MESSAGE, this.interactive_message); - hooks.put(WebHookType.GENERATE_CHUNK, this.generate_chunk); - hooks.put(WebHookType.EXPLOSION, this.explosion); - hooks.put(WebHookType.ENTITY_SPAWN, this.entity_spawn); - hooks.put(WebHookType.ENTITY_DESPAWN, this.entity_despawn); - hooks.put(WebHookType.ENTITY_EXPIRE, this.entity_expire); - hooks.put(WebHookType.INTERACT_BLOCK, this.interact_block); - hooks.put(WebHookType.INVENTORY_OPEN, this.inventory_open); - hooks.put(WebHookType.INVENTORY_CLOSE, this.inventory_close); - hooks.put(WebHookType.PLAYER_JOIN, this.player_join); - hooks.put(WebHookType.PLAYER_LEAVE, this.player_leave); - hooks.put(WebHookType.PLAYER_DEATH, this.player_death); - hooks.put(WebHookType.PLAYER_KICK, this.player_kick); - hooks.put(WebHookType.PLAYER_BAN, this.player_ban); - hooks.put(WebHookType.SERVER_START, this.server_start); - hooks.put(WebHookType.SERVER_STOP, this.server_stop); - hooks.put(WebHookType.WORLD_SAVE, this.world_save); - hooks.put(WebHookType.WORLD_LOAD, this.world_load); - hooks.put(WebHookType.WORLD_UNLOAD, this.world_unload); - return hooks; - } - } -} +package valandur.webapi.config; + +import com.google.common.collect.Lists; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import valandur.webapi.hook.CommandWebHook; +import valandur.webapi.hook.WebHook; +import valandur.webapi.hook.WebHookHeader; +import valandur.webapi.hook.WebHookParam; +import valandur.webapi.hook.WebHookService.WebHookType; +import valandur.webapi.security.SecurityService; + +import javax.ws.rs.HttpMethod; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@ConfigSerializable +public class HookConfig extends BaseConfig { + + private static Map defaultCommandHooks() { + Map hooks = new HashMap<>(); + hooks.put("test", new CommandWebHook( + false, + Lists.newArrayList("test"), + Lists.newArrayList( + new WebHookParam("player", WebHookParam.WebHookParamType.PLAYER, false), + new WebHookParam("world", WebHookParam.WebHookParamType.WORLD, true) + ), + Lists.newArrayList( + new WebHook( + "http://localhost/test/{player}", + false, + HttpMethod.POST, + WebHook.WebHookDataType.JSON, + false, + Lists.newArrayList(new WebHookHeader("X-SUPER-SECRET", "my_secret_to_verify")), + true, + SecurityService.permitAllNode() + ) + ) + )); + return hooks; + } + + @Setting(comment = "The following are event hooks which are all called when the specified event happens. They get passed various data\n" + + "in the body (if method != GET, described below for each event). The format of the hooks is described in the \"all\"\n" + + "event hook. This format can be used for any of the hook lists.\n" + + "Please note that the hooks don't get called in any particular order, and might even be called concurrently.") + public HookEvents events = new HookEvents(); + + @Setting(comment = "These hooks can be used to bind to custom events. You have to use the fully qualified class name as the key, and then\n" + + "a hook list just like for the event hooks. These hooks work just like the event hooks, although the data\n" + + "depends on the event you subscribe to.") + public Map> custom = new HashMap<>(); + + @Setting(comment = "The endpoints here get called when executing the specified command. " + + "For example the hook \"test\" would get executed\n" + + "when running the command /webapi notify test") + public Map command = defaultCommandHooks(); + + + @ConfigSerializable + public static class HookEvents { + @Setting(comment = "This event is fired for all events. The \"X-WebAPI-Event\" header specifies the exact event.") + public List all = Lists.newArrayList(new WebHook( + "http://localhost/test", + false, + HttpMethod.POST, + WebHook.WebHookDataType.JSON, + false, + Lists.newArrayList(new WebHookHeader("X-SUPER-SECRET", "my_secret_to_verify")), + true, + SecurityService.permitAllNode() + )); + + @Setting(comment = "This event is fired when a player earns an achievement / advancement") + public List achievement = new ArrayList<>(); + + @Setting(comment = "This event is fired when a block operation changes status") + public List block_operation_status = new ArrayList<>(); + + @Setting(comment = "This event is fired when a chat message is sent on the server") + public List chat = new ArrayList<>(); + + @Setting(comment = "This event is fired when a command is executed") + public List command = new ArrayList<>(); + + @Setting(comment = "This event is fired when a player clicks one of the options of an interactive message") + public List interactive_message = new ArrayList<>(); + + @Setting(comment = "This event is fired when a chunk is generated") + public List generate_chunk = new ArrayList<>(); + + @Setting(comment = "This event is fired when an explosion occurs") + public List explosion = new ArrayList<>(); + + @Setting(comment = "This event is fired when an entity spawns") + public List entity_spawn = new ArrayList<>(); + + @Setting(comment = "This event is fired when an entity despawns") + public List entity_despawn = new ArrayList<>(); + + @Setting(comment = "This event is fired when an entity expires") + public List entity_expire = new ArrayList<>(); + + @Setting(comment = "This event is fired when a player interacts with a block") + public List interact_block = new ArrayList<>(); + + @Setting(comment = "This event is fired when an inventory is opened") + public List inventory_open = new ArrayList<>(); + + @Setting(comment = "This event is fired when an inventory is closed") + public List inventory_close = new ArrayList<>(); + + @Setting(comment = "This event is fired when a player joins the server") + public List player_join = new ArrayList<>(); + + @Setting(comment = "This event is fired when a player leaves the server") + public List player_leave = new ArrayList<>(); + + @Setting(comment = "This event is fired when a player dies") + public List player_death = new ArrayList<>(); + + @Setting(comment = "This event is fired when a player gets kicked") + public List player_kick = new ArrayList<>(); + + @Setting(comment = "This event is fired when a player gets banned") + public List player_ban = new ArrayList<>(); + + @Setting(comment = "This event is fired when the server starts") + public List server_start = new ArrayList<>(); + + @Setting(comment = "This event is fired when the server stops") + public List server_stop = new ArrayList<>(); + + @Setting(comment = "This event is fired when the world is saved") + public List world_save = new ArrayList<>(); + + @Setting(comment = "This event is fired when a world is loaded") + public List world_load = new ArrayList<>(); + + @Setting(comment = "This event is fired when a world is unloaded") + public List world_unload = new ArrayList<>(); + + + public Map> asMap() { + Map> hooks = new HashMap<>(); + hooks.put(WebHookType.ALL, this.all); + hooks.put(WebHookType.ADVANCEMENT, this.achievement); + hooks.put(WebHookType.BLOCK_OPERATION_STATUS, this.block_operation_status); + hooks.put(WebHookType.CHAT, this.chat); + hooks.put(WebHookType.COMMAND, this.command); + hooks.put(WebHookType.INTERACTIVE_MESSAGE, this.interactive_message); + hooks.put(WebHookType.GENERATE_CHUNK, this.generate_chunk); + hooks.put(WebHookType.EXPLOSION, this.explosion); + hooks.put(WebHookType.ENTITY_SPAWN, this.entity_spawn); + hooks.put(WebHookType.ENTITY_DESPAWN, this.entity_despawn); + hooks.put(WebHookType.ENTITY_EXPIRE, this.entity_expire); + hooks.put(WebHookType.INTERACT_BLOCK, this.interact_block); + hooks.put(WebHookType.INVENTORY_OPEN, this.inventory_open); + hooks.put(WebHookType.INVENTORY_CLOSE, this.inventory_close); + hooks.put(WebHookType.PLAYER_JOIN, this.player_join); + hooks.put(WebHookType.PLAYER_LEAVE, this.player_leave); + hooks.put(WebHookType.PLAYER_DEATH, this.player_death); + hooks.put(WebHookType.PLAYER_KICK, this.player_kick); + hooks.put(WebHookType.PLAYER_BAN, this.player_ban); + hooks.put(WebHookType.SERVER_START, this.server_start); + hooks.put(WebHookType.SERVER_STOP, this.server_stop); + hooks.put(WebHookType.WORLD_SAVE, this.world_save); + hooks.put(WebHookType.WORLD_LOAD, this.world_load); + hooks.put(WebHookType.WORLD_UNLOAD, this.world_unload); + return hooks; + } + } +} diff --git a/src/main/java/valandur/webapi/config/LinkConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/LinkConfig.java similarity index 100% rename from src/main/java/valandur/webapi/config/LinkConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/LinkConfig.java diff --git a/src/main/java/valandur/webapi/config/MainConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/MainConfig.java similarity index 97% rename from src/main/java/valandur/webapi/config/MainConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/MainConfig.java index 096692be..14cca5ca 100644 --- a/src/main/java/valandur/webapi/config/MainConfig.java +++ b/webapi-sponge/src/main/java/valandur/webapi/config/MainConfig.java @@ -1,74 +1,74 @@ -package valandur.webapi.config; - -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; - -import java.util.ArrayList; -import java.util.List; - -@ConfigSerializable -public class MainConfig extends BaseConfig { - - @Setting(comment = "Set this to false to completely disable the admin panel") - public boolean adminPanel = true; - - @Setting(comment = "Change AdminPanel settings") - public APConfig adminPanelConfig = new APConfig(); - - @Setting(comment = "Set this to true when working on the WebAPI. \n" + - "This is NOT detailed debug info, so don't turn on if not \n" + - "running the Web-API from an IDE") - public boolean devMode = false; - - @Setting(comment = "This is the host the API will be listening on.\n" + - "Default is \"localhost\" to prevent any access from outside\n" + - "the server, but you can set this to \"0.0.0.0\" to listen\n" + - "on all addresses IF YOU HAVE CONFIGURED THE PERMISSIONS") - public String host = "localhost"; - - @Setting(comment = "This tells the API on which port to listen for HTTP requests.\n" + - "It is recommended to use a port above 1024, as those below\n" + - "are reserved for the system and might not be available.\n" + - "Set to -1 to disable the HTTP protocol.") - public int http = 8080; - @Setting(comment = "This tells the API on which port to listen for HTTPS requests.\n" + - "It is recommended to use a port above 1024, as those below\n" + - "are reserved for the system and might not be available.\n" + - "Set to -1 to disable the HTTPS protocol.") - public int https = 8081; - - @Setting(comment = "Set this path to your java key store if you don't want to\n" + - "use the default self-signed one provided by the Web-API") - public String customKeyStore = null; - @Setting - public String customKeyStorePassword = null; - @Setting - public String customKeyStoreManagerPassword = null; - - @Setting(comment = "Automatically report errors (your server IP is NOT collected,\n" + - "neither any personal information). This just helps finding bugs.") - public boolean reportErrors = true; - - - @ConfigSerializable - public static class APServer { - @Setting(comment = "The display name of the server") - public String name = "Localhost"; - @Setting(comment = "The Web-API URL for the server") - public String apiUrl = ""; - - private APServer() {} - } - @ConfigSerializable - public static class APConfig { - @Setting(comment = "The base path where the AdminPanel is served") - public String basePath = "/admin/"; - @Setting(comment = "The list of servers in this AdminPanel") - public List servers; - - private APConfig() { - servers = new ArrayList<>(); - servers.add(new APServer()); - } - } -} +package valandur.webapi.config; + +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.ArrayList; +import java.util.List; + +@ConfigSerializable +public class MainConfig extends BaseConfig { + + @Setting(comment = "Set this to false to completely disable the admin panel") + public boolean adminPanel = true; + + @Setting(comment = "Change AdminPanel settings") + public APConfig adminPanelConfig = new APConfig(); + + @Setting(comment = "Set this to true when working on the WebAPI. \n" + + "This is NOT detailed debug info, so don't turn on if not \n" + + "running the Web-API from an IDE") + public boolean devMode = false; + + @Setting(comment = "This is the host the API will be listening on.\n" + + "Default is \"localhost\" to prevent any access from outside\n" + + "the server, but you can set this to \"0.0.0.0\" to listen\n" + + "on all addresses IF YOU HAVE CONFIGURED THE PERMISSIONS") + public String host = "localhost"; + + @Setting(comment = "This tells the API on which port to listen for HTTP requests.\n" + + "It is recommended to use a port above 1024, as those below\n" + + "are reserved for the system and might not be available.\n" + + "Set to -1 to disable the HTTP protocol.") + public int http = 8080; + @Setting(comment = "This tells the API on which port to listen for HTTPS requests.\n" + + "It is recommended to use a port above 1024, as those below\n" + + "are reserved for the system and might not be available.\n" + + "Set to -1 to disable the HTTPS protocol.") + public int https = 8081; + + @Setting(comment = "Set this path to your java key store if you don't want to\n" + + "use the default self-signed one provided by the Web-API") + public String customKeyStore = null; + @Setting + public String customKeyStorePassword = null; + @Setting + public String customKeyStoreManagerPassword = null; + + @Setting(comment = "Automatically report errors (your server IP is NOT collected,\n" + + "neither any personal information). This just helps finding bugs.") + public boolean reportErrors = true; + + + @ConfigSerializable + public static class APServer { + @Setting(comment = "The display name of the server") + public String name = "Localhost"; + @Setting(comment = "The Web-API URL for the server") + public String apiUrl = ""; + + private APServer() {} + } + @ConfigSerializable + public static class APConfig { + @Setting(comment = "The base path where the AdminPanel is served") + public String basePath = "/admin/"; + @Setting(comment = "The list of servers in this AdminPanel") + public List servers; + + private APConfig() { + servers = new ArrayList<>(); + servers.add(new APServer()); + } + } +} diff --git a/src/main/java/valandur/webapi/config/MapConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/MapConfig.java similarity index 98% rename from src/main/java/valandur/webapi/config/MapConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/MapConfig.java index 1fabe4db..f663084e 100644 --- a/src/main/java/valandur/webapi/config/MapConfig.java +++ b/webapi-sponge/src/main/java/valandur/webapi/config/MapConfig.java @@ -1,61 +1,61 @@ -package valandur.webapi.config; - -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; - -import java.util.HashMap; -import java.util.Map; - -@ConfigSerializable -public class MapConfig extends BaseConfig { - - @Setting(comment = "This contains the mapping of biome ids to colors used in the map.\n" + - "Colors are specified as 6 digit hex codes (like in html/css).\n" + - "If a biome cannot be found then white (\"000000\") is used.\n" + - "If a biome contains \"_mutated\" in the id then the non-mutated version is used if a mutated version is not defined.") - public Map biomeColors = new HashMap<>(); - - // Add default map values - public MapConfig() { - biomeColors.put("minecraft:ocean", "000070"); - biomeColors.put("minecraft:plains", "8DB360"); - biomeColors.put("minecraft:desert", "FA9418"); - biomeColors.put("minecraft:extreme_hills", "606060"); - biomeColors.put("minecraft:forest", "056621"); - biomeColors.put("minecraft:taiga", "0B6659"); - biomeColors.put("minecraft:swampland", "07F9B2"); - biomeColors.put("minecraft:river", "0000FF"); - biomeColors.put("minecraft:hell", "FF0000"); - biomeColors.put("minecraft:sky", "8080FF"); - biomeColors.put("minecraft:frozen_ocean", "9090A0"); - biomeColors.put("minecraft:frozen_river", "A0A0FF"); - biomeColors.put("minecraft:ice_flats", "FFFFFF"); - biomeColors.put("minecraft:ice_mountains", "A0A0A0"); - biomeColors.put("minecraft:mushroom_island", "FF00FF"); - biomeColors.put("minecraft:mushroom_island_shore", "A000FF"); - biomeColors.put("minecraft:beaches", "FADE55"); - biomeColors.put("minecraft:desert_hills", "D25F12"); - biomeColors.put("minecraft:forest_hills", "22551C"); - biomeColors.put("minecraft:taiga_hills", "163933"); - biomeColors.put("minecraft:smaller_extreme_hills", "72789A"); - biomeColors.put("minecraft:jungle", "537B09"); - biomeColors.put("minecraft:jungle_hills", "2C4205"); - biomeColors.put("minecraft:jungle_edge", "628B17"); - biomeColors.put("minecraft:deep_ocean", "000030"); - biomeColors.put("minecraft:stone_beach", "A2A284"); - biomeColors.put("minecraft:cold_beach", "FAF0C0"); - biomeColors.put("minecraft:birch_forest", "307444"); - biomeColors.put("minecraft:birch_forest_hills", "1F5F32"); - biomeColors.put("minecraft:roofed_forest", "40511A"); - biomeColors.put("minecraft:taiga_cold", "31554A"); - biomeColors.put("minecraft:taiga_cold_hills", "243F36"); - biomeColors.put("minecraft:redwood_taiga", "596651"); - biomeColors.put("minecraft:redwood_taiga_hills", "545F3E"); - biomeColors.put("minecraft:extreme_hills_with_trees", "507050"); - biomeColors.put("minecraft:savanna", "BDB25F"); - biomeColors.put("minecraft:savanna_rock", "A79D64"); - biomeColors.put("minecraft:mesa", "D94515"); - biomeColors.put("minecraft:mesa_rock", "B09765"); - biomeColors.put("minecraft:mesa_clear_rock", "CA8C65"); - } -} +package valandur.webapi.config; + +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import java.util.HashMap; +import java.util.Map; + +@ConfigSerializable +public class MapConfig extends BaseConfig { + + @Setting(comment = "This contains the mapping of biome ids to colors used in the map.\n" + + "Colors are specified as 6 digit hex codes (like in html/css).\n" + + "If a biome cannot be found then white (\"000000\") is used.\n" + + "If a biome contains \"_mutated\" in the id then the non-mutated version is used if a mutated version is not defined.") + public Map biomeColors = new HashMap<>(); + + // Add default map values + public MapConfig() { + biomeColors.put("minecraft:ocean", "000070"); + biomeColors.put("minecraft:plains", "8DB360"); + biomeColors.put("minecraft:desert", "FA9418"); + biomeColors.put("minecraft:extreme_hills", "606060"); + biomeColors.put("minecraft:forest", "056621"); + biomeColors.put("minecraft:taiga", "0B6659"); + biomeColors.put("minecraft:swampland", "07F9B2"); + biomeColors.put("minecraft:river", "0000FF"); + biomeColors.put("minecraft:hell", "FF0000"); + biomeColors.put("minecraft:sky", "8080FF"); + biomeColors.put("minecraft:frozen_ocean", "9090A0"); + biomeColors.put("minecraft:frozen_river", "A0A0FF"); + biomeColors.put("minecraft:ice_flats", "FFFFFF"); + biomeColors.put("minecraft:ice_mountains", "A0A0A0"); + biomeColors.put("minecraft:mushroom_island", "FF00FF"); + biomeColors.put("minecraft:mushroom_island_shore", "A000FF"); + biomeColors.put("minecraft:beaches", "FADE55"); + biomeColors.put("minecraft:desert_hills", "D25F12"); + biomeColors.put("minecraft:forest_hills", "22551C"); + biomeColors.put("minecraft:taiga_hills", "163933"); + biomeColors.put("minecraft:smaller_extreme_hills", "72789A"); + biomeColors.put("minecraft:jungle", "537B09"); + biomeColors.put("minecraft:jungle_hills", "2C4205"); + biomeColors.put("minecraft:jungle_edge", "628B17"); + biomeColors.put("minecraft:deep_ocean", "000030"); + biomeColors.put("minecraft:stone_beach", "A2A284"); + biomeColors.put("minecraft:cold_beach", "FAF0C0"); + biomeColors.put("minecraft:birch_forest", "307444"); + biomeColors.put("minecraft:birch_forest_hills", "1F5F32"); + biomeColors.put("minecraft:roofed_forest", "40511A"); + biomeColors.put("minecraft:taiga_cold", "31554A"); + biomeColors.put("minecraft:taiga_cold_hills", "243F36"); + biomeColors.put("minecraft:redwood_taiga", "596651"); + biomeColors.put("minecraft:redwood_taiga_hills", "545F3E"); + biomeColors.put("minecraft:extreme_hills_with_trees", "507050"); + biomeColors.put("minecraft:savanna", "BDB25F"); + biomeColors.put("minecraft:savanna_rock", "A79D64"); + biomeColors.put("minecraft:mesa", "D94515"); + biomeColors.put("minecraft:mesa_rock", "B09765"); + biomeColors.put("minecraft:mesa_clear_rock", "CA8C65"); + } +} diff --git a/src/main/java/valandur/webapi/config/PermissionConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/PermissionConfig.java similarity index 97% rename from src/main/java/valandur/webapi/config/PermissionConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/PermissionConfig.java index 8f654c9b..9d7cab81 100644 --- a/src/main/java/valandur/webapi/config/PermissionConfig.java +++ b/webapi-sponge/src/main/java/valandur/webapi/config/PermissionConfig.java @@ -1,44 +1,44 @@ -package valandur.webapi.config; - -import com.google.common.collect.Lists; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import valandur.webapi.security.PermissionStruct; -import valandur.webapi.security.SecurityService; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@ConfigSerializable -public class PermissionConfig extends BaseConfig { - - @Setting(comment = "Set this to true to enable the whitelist, false to turn it off") - public boolean useWhitelist = true; - - @Setting(comment = "Add IP address that are allowed to connect to the Web-API to this list") - public List whitelist = Lists.newArrayList("127.0.0.1", "::1"); - - @Setting(comment = "Set this to true to enable the blacklist, false to turn it off") - public boolean useBlacklist = false; - - @Setting(comment = "Add the IP addresses that are NOT allowed to connect to the Web-API to this list") - public List blacklist = new ArrayList<>(); - - @Setting(comment = "The servers which are allowed to pass the X-Forwarded-For header indicating that they are\n" + - "forwarding a request for a client and are themselves a proxy. You can use IP addresses or\n" + - "CIDR notation IP blocks (e.g. \"192.168.0.0/18\")") - public List allowedProxies = Lists.newArrayList("127.0.0.1", "::1"); - - @Setting(comment = "The access control origin header that is sent with each request.\n" + - "This is useful if you want to prevent CORS,\n" + - "but remember that it must at least include the server where the AdminPanel is running") - public String accessControlOrigin = "*"; - - @Setting(value = "default", comment = "These are the default permissions that a client without a key receives") - public PermissionStruct def = new PermissionStruct(SecurityService.emptyNode(), 1); - - @Setting(comment = "This is a map of keys, defining which keys give access to which endpoints.") - public Map keys = new HashMap<>(); -} +package valandur.webapi.config; + +import com.google.common.collect.Lists; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import valandur.webapi.security.PermissionStruct; +import valandur.webapi.security.SecurityService; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@ConfigSerializable +public class PermissionConfig extends BaseConfig { + + @Setting(comment = "Set this to true to enable the whitelist, false to turn it off") + public boolean useWhitelist = true; + + @Setting(comment = "Add IP address that are allowed to connect to the Web-API to this list") + public List whitelist = Lists.newArrayList("127.0.0.1", "::1"); + + @Setting(comment = "Set this to true to enable the blacklist, false to turn it off") + public boolean useBlacklist = false; + + @Setting(comment = "Add the IP addresses that are NOT allowed to connect to the Web-API to this list") + public List blacklist = new ArrayList<>(); + + @Setting(comment = "The servers which are allowed to pass the X-Forwarded-For header indicating that they are\n" + + "forwarding a request for a client and are themselves a proxy. You can use IP addresses or\n" + + "CIDR notation IP blocks (e.g. \"192.168.0.0/18\")") + public List allowedProxies = Lists.newArrayList("127.0.0.1", "::1"); + + @Setting(comment = "The access control origin header that is sent with each request.\n" + + "This is useful if you want to prevent CORS,\n" + + "but remember that it must at least include the server where the AdminPanel is running") + public String accessControlOrigin = "*"; + + @Setting(value = "default", comment = "These are the default permissions that a client without a key receives") + public PermissionStruct def = new PermissionStruct(SecurityService.emptyNode(), 1); + + @Setting(comment = "This is a map of keys, defining which keys give access to which endpoints.") + public Map keys = new HashMap<>(); +} diff --git a/src/main/java/valandur/webapi/config/ServerConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/ServerConfig.java similarity index 100% rename from src/main/java/valandur/webapi/config/ServerConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/ServerConfig.java diff --git a/src/main/java/valandur/webapi/config/ServletsConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/ServletsConfig.java similarity index 100% rename from src/main/java/valandur/webapi/config/ServletsConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/ServletsConfig.java diff --git a/src/main/java/valandur/webapi/config/UserConfig.java b/webapi-sponge/src/main/java/valandur/webapi/config/UserConfig.java similarity index 96% rename from src/main/java/valandur/webapi/config/UserConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/config/UserConfig.java index d055310a..45fb674e 100644 --- a/src/main/java/valandur/webapi/config/UserConfig.java +++ b/webapi-sponge/src/main/java/valandur/webapi/config/UserConfig.java @@ -1,15 +1,15 @@ -package valandur.webapi.config; - -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import valandur.webapi.user.UserPermissionStruct; - -import java.util.HashMap; -import java.util.Map; - -@ConfigSerializable -public class UserConfig extends BaseConfig { - - @Setting - public Map users = new HashMap<>(); -} +package valandur.webapi.config; + +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import valandur.webapi.user.UserPermissionStruct; + +import java.util.HashMap; +import java.util.Map; + +@ConfigSerializable +public class UserConfig extends BaseConfig { + + @Setting + public Map users = new HashMap<>(); +} diff --git a/src/main/java/valandur/webapi/exceptions/NotImplementedException.java b/webapi-sponge/src/main/java/valandur/webapi/exceptions/NotImplementedException.java similarity index 96% rename from src/main/java/valandur/webapi/exceptions/NotImplementedException.java rename to webapi-sponge/src/main/java/valandur/webapi/exceptions/NotImplementedException.java index 3ad559c0..93620fcb 100644 --- a/src/main/java/valandur/webapi/exceptions/NotImplementedException.java +++ b/webapi-sponge/src/main/java/valandur/webapi/exceptions/NotImplementedException.java @@ -1,11 +1,11 @@ -package valandur.webapi.exceptions; - -import javax.ws.rs.ServerErrorException; -import javax.ws.rs.core.Response; - -public class NotImplementedException extends ServerErrorException { - - public NotImplementedException() { - super(Response.Status.NOT_IMPLEMENTED); - } -} +package valandur.webapi.exceptions; + +import javax.ws.rs.ServerErrorException; +import javax.ws.rs.core.Response; + +public class NotImplementedException extends ServerErrorException { + + public NotImplementedException() { + super(Response.Status.NOT_IMPLEMENTED); + } +} diff --git a/src/main/java/valandur/webapi/handler/AssetHandler.java b/webapi-sponge/src/main/java/valandur/webapi/handler/AssetHandler.java similarity index 100% rename from src/main/java/valandur/webapi/handler/AssetHandler.java rename to webapi-sponge/src/main/java/valandur/webapi/handler/AssetHandler.java diff --git a/src/main/java/valandur/webapi/handler/ErrorHandler.java b/webapi-sponge/src/main/java/valandur/webapi/handler/ErrorHandler.java similarity index 97% rename from src/main/java/valandur/webapi/handler/ErrorHandler.java rename to webapi-sponge/src/main/java/valandur/webapi/handler/ErrorHandler.java index e12c56b6..0810069e 100644 --- a/src/main/java/valandur/webapi/handler/ErrorHandler.java +++ b/webapi-sponge/src/main/java/valandur/webapi/handler/ErrorHandler.java @@ -1,74 +1,74 @@ -package valandur.webapi.handler; - -import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; -import com.google.gson.JsonObject; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.server.Request; -import valandur.webapi.WebAPI; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; -import java.io.IOException; -import java.io.Writer; - -@Provider -public class ErrorHandler extends org.eclipse.jetty.server.handler.ErrorHandler implements ExceptionMapper { - - @Override - public Response toResponse(Throwable exception) { - int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); - - if (exception instanceof WebApplicationException) { - status = ((WebApplicationException)exception).getResponse().getStatus(); - } else if (exception instanceof UnrecognizedPropertyException) { - status = Response.Status.BAD_REQUEST.getStatusCode(); - } else { - // Print the stack trace as this is an "unexpected" exception, - // and we want to make sure we can track it down - exception.printStackTrace(); - } - - return Response - .status(status) - .entity(new ErrorMessage(status, exception.getMessage())) - .build(); - } - - @Override - protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException { - if (message == null) - message = HttpStatus.getMessage(code); - - JsonObject obj = new JsonObject(); - obj.addProperty("code", code); - obj.addProperty("message", message); - writer.write(obj.toString()); - } - - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { - WebAPI.getLogger().info("ERROR: " + target); - - super.handle(target, baseRequest, request, response); - } - - @ApiModel("ErrorMessage") - public static class ErrorMessage { - @ApiModelProperty("The status code of the error. This is also returned as the HTTP status code.") - public int status; - - @ApiModelProperty("A description of the error that occured") - public String error; - - public ErrorMessage(int status, String error) { - this.status = status; - this.error = error; - } - } -} +package valandur.webapi.handler; + +import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; +import com.google.gson.JsonObject; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; +import valandur.webapi.WebAPI; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.Writer; + +@Provider +public class ErrorHandler extends org.eclipse.jetty.server.handler.ErrorHandler implements ExceptionMapper { + + @Override + public Response toResponse(Throwable exception) { + int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); + + if (exception instanceof WebApplicationException) { + status = ((WebApplicationException)exception).getResponse().getStatus(); + } else if (exception instanceof UnrecognizedPropertyException) { + status = Response.Status.BAD_REQUEST.getStatusCode(); + } else { + // Print the stack trace as this is an "unexpected" exception, + // and we want to make sure we can track it down + exception.printStackTrace(); + } + + return Response + .status(status) + .entity(new ErrorMessage(status, exception.getMessage())) + .build(); + } + + @Override + protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException { + if (message == null) + message = HttpStatus.getMessage(code); + + JsonObject obj = new JsonObject(); + obj.addProperty("code", code); + obj.addProperty("message", message); + writer.write(obj.toString()); + } + + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { + WebAPI.getLogger().info("ERROR: " + target); + + super.handle(target, baseRequest, request, response); + } + + @ApiModel("ErrorMessage") + public static class ErrorMessage { + @ApiModelProperty("The status code of the error. This is also returned as the HTTP status code.") + public int status; + + @ApiModelProperty("A description of the error that occured") + public String error; + + public ErrorMessage(int status, String error) { + this.status = status; + this.error = error; + } + } +} diff --git a/src/main/java/valandur/webapi/hook/CommandWebHook.java b/webapi-sponge/src/main/java/valandur/webapi/hook/CommandWebHook.java similarity index 100% rename from src/main/java/valandur/webapi/hook/CommandWebHook.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/CommandWebHook.java diff --git a/src/main/java/valandur/webapi/hook/WebHook.java b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHook.java similarity index 96% rename from src/main/java/valandur/webapi/hook/WebHook.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/WebHook.java index 83711bc1..0208082f 100644 --- a/src/main/java/valandur/webapi/hook/WebHook.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHook.java @@ -1,83 +1,83 @@ -package valandur.webapi.hook; - -import valandur.webapi.hook.filter.BaseWebHookFilter; -import valandur.webapi.util.TreeNode; - -import java.util.List; - -public class WebHook { - - public enum WebHookDataType { - JSON, XML - } - - private String address; - public String getAddress() { - return address; - } - - private boolean enabled; - public boolean isEnabled() { - return enabled; - } - - private boolean form; - public boolean isForm() { - return form; - } - - private String method; - public String getMethod() { return method; } - - private WebHookDataType dataType; - public WebHookDataType getDataType() { - return dataType; - } - public String getDataTypeHeader() { - if (form) - return "application/x-www-form-urlencoded"; - - switch (dataType) { - case JSON: - return "application/json"; - case XML: - return "application/xml"; - default: - return ""; - } - } - - private List headers; - public List getHeaders() { return headers; } - - private boolean details; - public boolean includeDetails() { - return details; - } - - private TreeNode permissions; - public TreeNode getPermissions() { - return permissions; - } - - private BaseWebHookFilter filter; - public BaseWebHookFilter getFilter() { - return filter; - } - public void setFilter(BaseWebHookFilter filter) { - this.filter = filter; - } - - - public WebHook(String address, boolean enabled, String method, WebHookDataType dataType, boolean form, - List headers, boolean details, TreeNode permissions) { - this.address = address; - this.enabled = enabled; - this.method = method; - this.dataType = dataType; - this.form = form; - this.headers = headers; - this.details = details; - this.permissions = permissions; - } -} +package valandur.webapi.hook; + +import valandur.webapi.hook.filter.BaseWebHookFilter; +import valandur.webapi.util.TreeNode; + +import java.util.List; + +public class WebHook { + + public enum WebHookDataType { + JSON, XML + } + + private String address; + public String getAddress() { + return address; + } + + private boolean enabled; + public boolean isEnabled() { + return enabled; + } + + private boolean form; + public boolean isForm() { + return form; + } + + private String method; + public String getMethod() { return method; } + + private WebHookDataType dataType; + public WebHookDataType getDataType() { + return dataType; + } + public String getDataTypeHeader() { + if (form) + return "application/x-www-form-urlencoded"; + + switch (dataType) { + case JSON: + return "application/json"; + case XML: + return "application/xml"; + default: + return ""; + } + } + + private List headers; + public List getHeaders() { return headers; } + + private boolean details; + public boolean includeDetails() { + return details; + } + + private TreeNode permissions; + public TreeNode getPermissions() { + return permissions; + } + + private BaseWebHookFilter filter; + public BaseWebHookFilter getFilter() { + return filter; + } + public void setFilter(BaseWebHookFilter filter) { + this.filter = filter; + } + + + public WebHook(String address, boolean enabled, String method, WebHookDataType dataType, boolean form, + List headers, boolean details, TreeNode permissions) { + this.address = address; + this.enabled = enabled; + this.method = method; + this.dataType = dataType; + this.form = form; + this.headers = headers; + this.details = details; + this.permissions = permissions; + } +} diff --git a/src/main/java/valandur/webapi/hook/WebHookEventListener.java b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookEventListener.java similarity index 100% rename from src/main/java/valandur/webapi/hook/WebHookEventListener.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/WebHookEventListener.java diff --git a/src/main/java/valandur/webapi/hook/WebHookHeader.java b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookHeader.java similarity index 95% rename from src/main/java/valandur/webapi/hook/WebHookHeader.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/WebHookHeader.java index 9ea2925b..680a8844 100644 --- a/src/main/java/valandur/webapi/hook/WebHookHeader.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookHeader.java @@ -1,27 +1,27 @@ -package valandur.webapi.hook; - -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; - -@ConfigSerializable -public class WebHookHeader { - - @Setting - private String name; - public String getName() { - return name; - } - - @Setting - private String value; - public String getValue() { - return value; - } - - - public WebHookHeader() {} - public WebHookHeader(String name, String value) { - this.name = name; - this.value = value; - } -} +package valandur.webapi.hook; + +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +@ConfigSerializable +public class WebHookHeader { + + @Setting + private String name; + public String getName() { + return name; + } + + @Setting + private String value; + public String getValue() { + return value; + } + + + public WebHookHeader() {} + public WebHookHeader(String name, String value) { + this.name = name; + this.value = value; + } +} diff --git a/src/main/java/valandur/webapi/hook/WebHookParam.java b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookParam.java similarity index 100% rename from src/main/java/valandur/webapi/hook/WebHookParam.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/WebHookParam.java diff --git a/src/main/java/valandur/webapi/hook/WebHookResponse.java b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookResponse.java similarity index 100% rename from src/main/java/valandur/webapi/hook/WebHookResponse.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/WebHookResponse.java diff --git a/src/main/java/valandur/webapi/hook/WebHookSerializer.java b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookSerializer.java similarity index 97% rename from src/main/java/valandur/webapi/hook/WebHookSerializer.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/WebHookSerializer.java index 96fdbea7..732308e1 100644 --- a/src/main/java/valandur/webapi/hook/WebHookSerializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookSerializer.java @@ -1,154 +1,154 @@ -package valandur.webapi.hook; - -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; -import org.slf4j.Logger; -import valandur.webapi.WebAPI; -import valandur.webapi.hook.filter.BaseWebHookFilter; -import valandur.webapi.security.SecurityService; -import valandur.webapi.util.TreeNode; - -import javax.ws.rs.HttpMethod; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -public class WebHookSerializer implements TypeSerializer { - - @Override - public WebHook deserialize(TypeToken type, ConfigurationNode value) throws ObjectMappingException { - Logger logger = WebAPI.getLogger(); - - String address = value.getNode("address").getString(); - - if (address == null) { - logger.error("No address specified for web hook!"); - return null; - } - - logger.info(" - " + address); - - boolean enabled = value.getNode("enabled").getBoolean(); - String method = value.getNode("method").getString(); - WebHook.WebHookDataType dataType = value.getNode("dataType").getValue(TypeToken.of(WebHook.WebHookDataType.class)); - boolean form = value.getNode("form").getBoolean(); - List headers = value.getNode("headers").getList(TypeToken.of(WebHookHeader.class)); - boolean details = value.getNode("details").getBoolean(); - - ConfigurationNode filterBase = value.getNode("filter"); - String filterName = filterBase.getNode("name").getString(); - ConfigurationNode filterConfig = filterBase.getNode("config"); - - TreeNode permissions = SecurityService.permitAllNode(); - - if (headers == null) { - headers = new ArrayList<>(); - } - - if (method == null) { - method = HttpMethod.POST; - logger.warn(" Does not specify 'method', defaulting to 'POST'"); - } - - if (dataType == null) { - dataType = WebHook.WebHookDataType.JSON; - logger.warn(" Does not specify 'dataType', defaulting to 'JSON'"); - } - - if (value.getNode("permissions").isVirtual()) { - logger.warn(" Does not specify 'permissions', defaulting to '*'"); - } else { - permissions = WebAPI.getSecurityService().permissionTreeFromConfig(value.getNode("permissions")); - } - - WebHook hook = new WebHook(address, enabled, method, dataType, form, headers, details, permissions); - - if (filterName != null) { - Optional> opt = WebAPI.getWebHookService().getFilter(filterName); - if (!opt.isPresent()) { - logger.error(" Could not find filter with name '" + filterName + "'"); - } else { - try { - Constructor ctor = opt.get().getConstructor(WebHook.class, ConfigurationNode.class); - hook.setFilter((BaseWebHookFilter) ctor.newInstance(hook, filterConfig)); - } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { - logger.error(" Could not setup filter '" + filterName + "': " + e.getMessage()); - } - } - } - - if (enabled) { - logger.info(" -> Ok"); - } else { - logger.info(" -> Disabled"); - } - - return hook; - } - - @Override - public void serialize(TypeToken type, WebHook obj, ConfigurationNode value) throws ObjectMappingException { - setValueAndComment(value.getNode("address"), obj.getAddress(), - "This is the address of the endpoint."); - - setValueAndComment(value.getNode("enabled"), obj.isEnabled(), - "Set to true or omit to enable the endpoint."); - - setValueAndComment(value.getNode("headers"), new TypeToken>() {}, obj.getHeaders(), - "This is a list of additional headers that is sent to the server. You can use this to e.g. specify a secret\n" + - "key which ensures that the server knows the requests are coming from the Web-API.\n" + - "Please note that the following headers will always be overridden by the Web-API:\n" + - "X-WebAPI-Version, X-WebAPI-Event, X-WebAPI-Source, User-Agent, Content-Type, Content-Length, accept, charset"); - - setValueAndComment(value.getNode("method"), obj.getMethod(), - "This is the http method that is used (GET, PUT, POST or DELETE)"); - - setValueAndComment(value.getNode("dataType"), TypeToken.of(WebHook.WebHookDataType.class), obj.getDataType(), - "Choose to either send the data as:\n" + - "JSON = application/json\n" + - "XML = application/xml"); - - setValueAndComment(value.getNode("form"), obj.isForm(), - "Choose to send the data wrapped as application/x-www-form-urlencoded"); - - setValueAndComment(value.getNode("details"), obj.includeDetails(), - "Set to true to send detailed json data"); - - if (obj.getFilter() != null) { - ConfigurationNode filterNode = value.getNode("filter"); - obj.getFilter().writeToConfig(filterNode); - if (filterNode instanceof CommentedConfigurationNode) { - ((CommentedConfigurationNode) filterNode).setComment( - "Filters are used to only send certain events to certain endpoints\n" + - "Use the 'name' property to select a filter and pass additional options in the 'config' property" - ); - } - } - - WebAPI.getSecurityService().permissionTreeToConfig(value.getNode("permissions"), obj.getPermissions()); - if (value.getNode("permissions") instanceof CommentedConfigurationNode) { - ((CommentedConfigurationNode) value.getNode("permissions")).setComment( - "Permissions node same as the ones in the permissions.conf file,\n" + - "use to configure which data is sent to this node"); - } - } - - private void setValueAndComment(ConfigurationNode node, Object value, String comment) { - node.setValue(value); - if (node instanceof CommentedConfigurationNode) { - ((CommentedConfigurationNode) node).setComment(comment); - } - } - private void setValueAndComment(ConfigurationNode node, TypeToken type, T value, String comment) - throws ObjectMappingException { - node.setValue(type, value); - if (node instanceof CommentedConfigurationNode) { - ((CommentedConfigurationNode) node).setComment(comment); - } - } -} +package valandur.webapi.hook; + +import com.google.common.reflect.TypeToken; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import org.slf4j.Logger; +import valandur.webapi.WebAPI; +import valandur.webapi.hook.filter.BaseWebHookFilter; +import valandur.webapi.security.SecurityService; +import valandur.webapi.util.TreeNode; + +import javax.ws.rs.HttpMethod; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class WebHookSerializer implements TypeSerializer { + + @Override + public WebHook deserialize(TypeToken type, ConfigurationNode value) throws ObjectMappingException { + Logger logger = WebAPI.getLogger(); + + String address = value.getNode("address").getString(); + + if (address == null) { + logger.error("No address specified for web hook!"); + return null; + } + + logger.info(" - " + address); + + boolean enabled = value.getNode("enabled").getBoolean(); + String method = value.getNode("method").getString(); + WebHook.WebHookDataType dataType = value.getNode("dataType").getValue(TypeToken.of(WebHook.WebHookDataType.class)); + boolean form = value.getNode("form").getBoolean(); + List headers = value.getNode("headers").getList(TypeToken.of(WebHookHeader.class)); + boolean details = value.getNode("details").getBoolean(); + + ConfigurationNode filterBase = value.getNode("filter"); + String filterName = filterBase.getNode("name").getString(); + ConfigurationNode filterConfig = filterBase.getNode("config"); + + TreeNode permissions = SecurityService.permitAllNode(); + + if (headers == null) { + headers = new ArrayList<>(); + } + + if (method == null) { + method = HttpMethod.POST; + logger.warn(" Does not specify 'method', defaulting to 'POST'"); + } + + if (dataType == null) { + dataType = WebHook.WebHookDataType.JSON; + logger.warn(" Does not specify 'dataType', defaulting to 'JSON'"); + } + + if (value.getNode("permissions").isVirtual()) { + logger.warn(" Does not specify 'permissions', defaulting to '*'"); + } else { + permissions = WebAPI.getSecurityService().permissionTreeFromConfig(value.getNode("permissions")); + } + + WebHook hook = new WebHook(address, enabled, method, dataType, form, headers, details, permissions); + + if (filterName != null) { + Optional> opt = WebAPI.getWebHookService().getFilter(filterName); + if (!opt.isPresent()) { + logger.error(" Could not find filter with name '" + filterName + "'"); + } else { + try { + Constructor ctor = opt.get().getConstructor(WebHook.class, ConfigurationNode.class); + hook.setFilter((BaseWebHookFilter) ctor.newInstance(hook, filterConfig)); + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { + logger.error(" Could not setup filter '" + filterName + "': " + e.getMessage()); + } + } + } + + if (enabled) { + logger.info(" -> Ok"); + } else { + logger.info(" -> Disabled"); + } + + return hook; + } + + @Override + public void serialize(TypeToken type, WebHook obj, ConfigurationNode value) throws ObjectMappingException { + setValueAndComment(value.getNode("address"), obj.getAddress(), + "This is the address of the endpoint."); + + setValueAndComment(value.getNode("enabled"), obj.isEnabled(), + "Set to true or omit to enable the endpoint."); + + setValueAndComment(value.getNode("headers"), new TypeToken>() {}, obj.getHeaders(), + "This is a list of additional headers that is sent to the server. You can use this to e.g. specify a secret\n" + + "key which ensures that the server knows the requests are coming from the Web-API.\n" + + "Please note that the following headers will always be overridden by the Web-API:\n" + + "X-WebAPI-Version, X-WebAPI-Event, X-WebAPI-Source, User-Agent, Content-Type, Content-Length, accept, charset"); + + setValueAndComment(value.getNode("method"), obj.getMethod(), + "This is the http method that is used (GET, PUT, POST or DELETE)"); + + setValueAndComment(value.getNode("dataType"), TypeToken.of(WebHook.WebHookDataType.class), obj.getDataType(), + "Choose to either send the data as:\n" + + "JSON = application/json\n" + + "XML = application/xml"); + + setValueAndComment(value.getNode("form"), obj.isForm(), + "Choose to send the data wrapped as application/x-www-form-urlencoded"); + + setValueAndComment(value.getNode("details"), obj.includeDetails(), + "Set to true to send detailed json data"); + + if (obj.getFilter() != null) { + ConfigurationNode filterNode = value.getNode("filter"); + obj.getFilter().writeToConfig(filterNode); + if (filterNode instanceof CommentedConfigurationNode) { + ((CommentedConfigurationNode) filterNode).setComment( + "Filters are used to only send certain events to certain endpoints\n" + + "Use the 'name' property to select a filter and pass additional options in the 'config' property" + ); + } + } + + WebAPI.getSecurityService().permissionTreeToConfig(value.getNode("permissions"), obj.getPermissions()); + if (value.getNode("permissions") instanceof CommentedConfigurationNode) { + ((CommentedConfigurationNode) value.getNode("permissions")).setComment( + "Permissions node same as the ones in the permissions.conf file,\n" + + "use to configure which data is sent to this node"); + } + } + + private void setValueAndComment(ConfigurationNode node, Object value, String comment) { + node.setValue(value); + if (node instanceof CommentedConfigurationNode) { + ((CommentedConfigurationNode) node).setComment(comment); + } + } + private void setValueAndComment(ConfigurationNode node, TypeToken type, T value, String comment) + throws ObjectMappingException { + node.setValue(type, value); + if (node instanceof CommentedConfigurationNode) { + ((CommentedConfigurationNode) node).setComment(comment); + } + } +} diff --git a/src/main/java/valandur/webapi/hook/WebHookService.java b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookService.java similarity index 99% rename from src/main/java/valandur/webapi/hook/WebHookService.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/WebHookService.java index 0c8edfb6..dc1fed73 100644 --- a/src/main/java/valandur/webapi/hook/WebHookService.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/WebHookService.java @@ -312,7 +312,7 @@ private void notifyHook(WebHook hook, WebHookType eventType, String source, Obje connection.disconnect(); } } - }); + }, WebAPI.getAsyncExecutor()); } diff --git a/src/main/java/valandur/webapi/hook/filter/BaseWebHookFilter.java b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/BaseWebHookFilter.java similarity index 96% rename from src/main/java/valandur/webapi/hook/filter/BaseWebHookFilter.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/filter/BaseWebHookFilter.java index 9ffc9851..b48822cb 100644 --- a/src/main/java/valandur/webapi/hook/filter/BaseWebHookFilter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/BaseWebHookFilter.java @@ -1,25 +1,25 @@ -package valandur.webapi.hook.filter; - -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import valandur.webapi.hook.WebHook; - -public abstract class BaseWebHookFilter { - - protected WebHook hook; - - public abstract String getName(); - - - public BaseWebHookFilter(WebHook hook, ConfigurationNode config) { - this.hook = hook; - } - - public void writeToConfig(ConfigurationNode node) throws ObjectMappingException { - node.getNode("name").setValue(this.getName()); - _writeToConfig(node); - } - protected abstract void _writeToConfig(ConfigurationNode node) throws ObjectMappingException; - - public abstract boolean process(Object data); -} +package valandur.webapi.hook.filter; + +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import valandur.webapi.hook.WebHook; + +public abstract class BaseWebHookFilter { + + protected WebHook hook; + + public abstract String getName(); + + + public BaseWebHookFilter(WebHook hook, ConfigurationNode config) { + this.hook = hook; + } + + public void writeToConfig(ConfigurationNode node) throws ObjectMappingException { + node.getNode("name").setValue(this.getName()); + _writeToConfig(node); + } + protected abstract void _writeToConfig(ConfigurationNode node) throws ObjectMappingException; + + public abstract boolean process(Object data); +} diff --git a/src/main/java/valandur/webapi/hook/filter/BlockTypeFilter.java b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/BlockTypeFilter.java similarity index 96% rename from src/main/java/valandur/webapi/hook/filter/BlockTypeFilter.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/filter/BlockTypeFilter.java index 0da38ee6..a3e0c258 100644 --- a/src/main/java/valandur/webapi/hook/filter/BlockTypeFilter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/BlockTypeFilter.java @@ -1,47 +1,47 @@ -package valandur.webapi.hook.filter; - -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.event.block.TargetBlockEvent; -import valandur.webapi.hook.WebHook; - -import java.util.List; - -public class BlockTypeFilter extends BaseWebHookFilter { - - public static String name = "WebAPI-BlockType"; - @Override - public String getName() { - return name; - } - - private List types; - - - public BlockTypeFilter(WebHook hook, ConfigurationNode config) { - super(hook, config); - - try { - types = config.getList(TypeToken.of(BlockType.class)); - } catch (ObjectMappingException e) { - e.printStackTrace(); - } - } - - @Override - protected void _writeToConfig(ConfigurationNode node) throws ObjectMappingException { - node.getNode("config").setValue(new TypeToken>() {}, this.types); - } - - @Override - public boolean process(Object data) { - if (data instanceof TargetBlockEvent) { - TargetBlockEvent event = (TargetBlockEvent)data; - return types.contains(event.getTargetBlock().getState().getType()); - } - - return false; - } -} +package valandur.webapi.hook.filter; + +import com.google.common.reflect.TypeToken; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.api.block.BlockType; +import org.spongepowered.api.event.block.TargetBlockEvent; +import valandur.webapi.hook.WebHook; + +import java.util.List; + +public class BlockTypeFilter extends BaseWebHookFilter { + + public static String name = "WebAPI-BlockType"; + @Override + public String getName() { + return name; + } + + private List types; + + + public BlockTypeFilter(WebHook hook, ConfigurationNode config) { + super(hook, config); + + try { + types = config.getList(TypeToken.of(BlockType.class)); + } catch (ObjectMappingException e) { + e.printStackTrace(); + } + } + + @Override + protected void _writeToConfig(ConfigurationNode node) throws ObjectMappingException { + node.getNode("config").setValue(new TypeToken>() {}, this.types); + } + + @Override + public boolean process(Object data) { + if (data instanceof TargetBlockEvent) { + TargetBlockEvent event = (TargetBlockEvent)data; + return types.contains(event.getTargetBlock().getState().getType()); + } + + return false; + } +} diff --git a/src/main/java/valandur/webapi/hook/filter/ItemTypeFilter.java b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/ItemTypeFilter.java similarity index 96% rename from src/main/java/valandur/webapi/hook/filter/ItemTypeFilter.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/filter/ItemTypeFilter.java index b714456e..aca82865 100644 --- a/src/main/java/valandur/webapi/hook/filter/ItemTypeFilter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/ItemTypeFilter.java @@ -1,47 +1,47 @@ -package valandur.webapi.hook.filter; - -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import org.spongepowered.api.event.entity.item.TargetItemEvent; -import org.spongepowered.api.item.ItemType; -import valandur.webapi.hook.WebHook; - -import java.util.List; - -public class ItemTypeFilter extends BaseWebHookFilter { - - public static String name = "WebAPI-Item"; - @Override - public String getName() { - return name; - } - - private List items; - - - public ItemTypeFilter(WebHook hook, ConfigurationNode config) { - super(hook, config); - - try { - items = config.getList(TypeToken.of(ItemType.class)); - } catch (ObjectMappingException e) { - e.printStackTrace(); - } - } - - @Override - protected void _writeToConfig(ConfigurationNode node) throws ObjectMappingException { - node.getNode("config").setValue(new TypeToken>() {}, this.items); - } - - @Override - public boolean process(Object data) { - if (data instanceof TargetItemEvent) { - TargetItemEvent event = (TargetItemEvent)data; - return items.contains(event.getTargetEntity().getItemType()); - } - - return false; - } -} +package valandur.webapi.hook.filter; + +import com.google.common.reflect.TypeToken; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.api.event.entity.item.TargetItemEvent; +import org.spongepowered.api.item.ItemType; +import valandur.webapi.hook.WebHook; + +import java.util.List; + +public class ItemTypeFilter extends BaseWebHookFilter { + + public static String name = "WebAPI-Item"; + @Override + public String getName() { + return name; + } + + private List items; + + + public ItemTypeFilter(WebHook hook, ConfigurationNode config) { + super(hook, config); + + try { + items = config.getList(TypeToken.of(ItemType.class)); + } catch (ObjectMappingException e) { + e.printStackTrace(); + } + } + + @Override + protected void _writeToConfig(ConfigurationNode node) throws ObjectMappingException { + node.getNode("config").setValue(new TypeToken>() {}, this.items); + } + + @Override + public boolean process(Object data) { + if (data instanceof TargetItemEvent) { + TargetItemEvent event = (TargetItemEvent)data; + return items.contains(event.getTargetEntity().getItemType()); + } + + return false; + } +} diff --git a/src/main/java/valandur/webapi/hook/filter/PlayerFilter.java b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/PlayerFilter.java similarity index 96% rename from src/main/java/valandur/webapi/hook/filter/PlayerFilter.java rename to webapi-sponge/src/main/java/valandur/webapi/hook/filter/PlayerFilter.java index 090d079d..5183e22a 100644 --- a/src/main/java/valandur/webapi/hook/filter/PlayerFilter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/hook/filter/PlayerFilter.java @@ -1,47 +1,47 @@ -package valandur.webapi.hook.filter; - -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import org.spongepowered.api.event.entity.living.humanoid.player.TargetPlayerEvent; -import valandur.webapi.hook.WebHook; - -import java.util.List; - -public class PlayerFilter extends BaseWebHookFilter { - - public static String name = "WebAPI-Player"; - @Override - public String getName() { - return name; - } - - private List players; - - - public PlayerFilter(WebHook hook, ConfigurationNode config) { - super(hook, config); - - try { - players = config.getList(TypeToken.of(String.class)); - } catch (ObjectMappingException e) { - e.printStackTrace(); - } - } - - @Override - protected void _writeToConfig(ConfigurationNode node) throws ObjectMappingException { - node.getNode("config").setValue(new TypeToken>() {}, this.players); - } - - @Override - public boolean process(Object data) { - if (data instanceof TargetPlayerEvent) { - TargetPlayerEvent event = (TargetPlayerEvent)data; - return players.contains(event.getTargetEntity().getUniqueId().toString()) || - players.contains(event.getTargetEntity().getName()); - } - - return false; - } -} +package valandur.webapi.hook.filter; + +import com.google.common.reflect.TypeToken; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.api.event.entity.living.humanoid.player.TargetPlayerEvent; +import valandur.webapi.hook.WebHook; + +import java.util.List; + +public class PlayerFilter extends BaseWebHookFilter { + + public static String name = "WebAPI-Player"; + @Override + public String getName() { + return name; + } + + private List players; + + + public PlayerFilter(WebHook hook, ConfigurationNode config) { + super(hook, config); + + try { + players = config.getList(TypeToken.of(String.class)); + } catch (ObjectMappingException e) { + e.printStackTrace(); + } + } + + @Override + protected void _writeToConfig(ConfigurationNode node) throws ObjectMappingException { + node.getNode("config").setValue(new TypeToken>() {}, this.players); + } + + @Override + public boolean process(Object data) { + if (data instanceof TargetPlayerEvent) { + TargetPlayerEvent event = (TargetPlayerEvent)data; + return players.contains(event.getTargetEntity().getUniqueId().toString()) || + players.contains(event.getTargetEntity().getName()); + } + + return false; + } +} diff --git a/src/main/java/valandur/webapi/integration/activetime/ActiveTimeServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/ActiveTimeServlet.java similarity index 97% rename from src/main/java/valandur/webapi/integration/activetime/ActiveTimeServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/activetime/ActiveTimeServlet.java index 7a6b77fe..df69bef0 100644 --- a/src/main/java/valandur/webapi/integration/activetime/ActiveTimeServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/ActiveTimeServlet.java @@ -1,68 +1,68 @@ -package valandur.webapi.integration.activetime; - -import com.mcsimonflash.sponge.activetime.api.ActiveTimeAPI; -import com.mcsimonflash.sponge.activetime.objects.ServerReport; -import com.mcsimonflash.sponge.activetime.objects.TimeHolder; -import com.mcsimonflash.sponge.activetime.objects.UserReport; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.spongepowered.api.entity.living.player.User; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.player.CachedPlayer; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import java.time.LocalDate; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -@Path("active-time") -@Api(tags = { "Active Time" }, value = "Keep track of the play time of players on your server.") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class ActiveTimeServlet extends BaseServlet { - - public static void onRegister() { - SerializeService srv = WebAPI.getSerializeService(); - srv.registerView(ServerReport.class, ServerReportView.class); - srv.registerView(TimeHolder.class, TimeHolderView.class); - srv.registerView(UserReport.class, UserReportView.class); - } - - @GET - @Permission({ "report", "server" }) - @ApiOperation( - value = "Server report", - notes = "Generates a report for the whole server from week ago until now") - public ServerReport getServerReport() { - try { - return ActiveTimeAPI.getServerReport(LocalDate.now().minusWeeks(1), LocalDate.now()).get(); - } catch (InterruptedException | ExecutionException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } - - @GET - @Path("/user/{uuid}") - @Permission({ "report", "user" }) - @ApiOperation( - value = "User report", - notes = "Generates a report for a specific user from a week ago until now") - public UserReport getUserReport(@PathParam("uuid") CachedPlayer player) { - try { - CompletableFuture report = WebAPI.runOnMain(() -> { - Optional optUser = player.getUser(); - if (!optUser.isPresent()) - throw new InternalServerErrorException("Could not get live user"); - return ActiveTimeAPI.getUserReport(optUser.get(), LocalDate.now().minusWeeks(1), LocalDate.now()); - }); - return report.get(); - } catch (InterruptedException | ExecutionException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } -} +package valandur.webapi.integration.activetime; + +import com.mcsimonflash.sponge.activetime.api.ActiveTimeAPI; +import com.mcsimonflash.sponge.activetime.objects.ServerReport; +import com.mcsimonflash.sponge.activetime.objects.TimeHolder; +import com.mcsimonflash.sponge.activetime.objects.UserReport; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.spongepowered.api.entity.living.player.User; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.player.CachedPlayer; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.time.LocalDate; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +@Path("active-time") +@Api(tags = { "Active Time" }, value = "Keep track of the play time of players on your server.") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class ActiveTimeServlet extends BaseServlet { + + public static void onRegister() { + SerializeService srv = WebAPI.getSerializeService(); + srv.registerView(ServerReport.class, ServerReportView.class); + srv.registerView(TimeHolder.class, TimeHolderView.class); + srv.registerView(UserReport.class, UserReportView.class); + } + + @GET + @Permission({ "report", "server" }) + @ApiOperation( + value = "Server report", + notes = "Generates a report for the whole server from week ago until now") + public ServerReport getServerReport() { + try { + return ActiveTimeAPI.getServerReport(LocalDate.now().minusWeeks(1), LocalDate.now()).get(); + } catch (InterruptedException | ExecutionException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } + + @GET + @Path("/user/{uuid}") + @Permission({ "report", "user" }) + @ApiOperation( + value = "User report", + notes = "Generates a report for a specific user from a week ago until now") + public UserReport getUserReport(@PathParam("uuid") CachedPlayer player) { + try { + CompletableFuture report = WebAPI.runOnMain(() -> { + Optional optUser = player.getUser(); + if (!optUser.isPresent()) + throw new InternalServerErrorException("Could not get live user"); + return ActiveTimeAPI.getUserReport(optUser.get(), LocalDate.now().minusWeeks(1), LocalDate.now()); + }); + return report.get(); + } catch (InterruptedException | ExecutionException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } +} diff --git a/src/main/java/valandur/webapi/integration/activetime/ServerReportView.java b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/ServerReportView.java similarity index 96% rename from src/main/java/valandur/webapi/integration/activetime/ServerReportView.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/activetime/ServerReportView.java index dc7af931..2c10c938 100644 --- a/src/main/java/valandur/webapi/integration/activetime/ServerReportView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/ServerReportView.java @@ -1,37 +1,37 @@ -package valandur.webapi.integration.activetime; - -import com.mcsimonflash.sponge.activetime.objects.ServerReport; -import com.mcsimonflash.sponge.activetime.objects.TimeHolder; -import io.swagger.annotations.ApiModel; -import valandur.webapi.serialize.BaseView; - -import java.time.LocalDate; - -@ApiModel("ServerReport") -public class ServerReportView extends BaseView { - - public LocalDate getFrom() { - return value.from; - } - public LocalDate getTo() { - return value.to; - } - - public TimeHolder getTotal() { - return value.total; - } - public TimeHolder getDailyAverage() { - return value.dailyAverage; - } - public TimeHolder getMonthlyAverage() { - return value.monthlyAverage; - } - public TimeHolder getWeeklyAverage() { - return value.weeklyAverage; - } - - - public ServerReportView(ServerReport value) { - super(value); - } -} +package valandur.webapi.integration.activetime; + +import com.mcsimonflash.sponge.activetime.objects.ServerReport; +import com.mcsimonflash.sponge.activetime.objects.TimeHolder; +import io.swagger.annotations.ApiModel; +import valandur.webapi.serialize.BaseView; + +import java.time.LocalDate; + +@ApiModel("ServerReport") +public class ServerReportView extends BaseView { + + public LocalDate getFrom() { + return value.from; + } + public LocalDate getTo() { + return value.to; + } + + public TimeHolder getTotal() { + return value.total; + } + public TimeHolder getDailyAverage() { + return value.dailyAverage; + } + public TimeHolder getMonthlyAverage() { + return value.monthlyAverage; + } + public TimeHolder getWeeklyAverage() { + return value.weeklyAverage; + } + + + public ServerReportView(ServerReport value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/integration/activetime/TimeHolderView.java b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/TimeHolderView.java similarity index 96% rename from src/main/java/valandur/webapi/integration/activetime/TimeHolderView.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/activetime/TimeHolderView.java index 25ae240a..c4ddaa19 100644 --- a/src/main/java/valandur/webapi/integration/activetime/TimeHolderView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/TimeHolderView.java @@ -1,25 +1,25 @@ -package valandur.webapi.integration.activetime; - -import com.mcsimonflash.sponge.activetime.objects.TimeHolder; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.serialize.BaseView; - -@ApiModel("TimeHolder") -public class TimeHolderView extends BaseView { - - @ApiModelProperty("The amount of active time spent") - public int getActiveTime() { - return value.getActiveTime(); - } - - @ApiModelProperty("The amount of time spent afk (only works if Nucleus is present)") - public int getAfkTime() { - return value.getAfkTime(); - } - - - public TimeHolderView(TimeHolder value) { - super(value); - } -} +package valandur.webapi.integration.activetime; + +import com.mcsimonflash.sponge.activetime.objects.TimeHolder; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.serialize.BaseView; + +@ApiModel("TimeHolder") +public class TimeHolderView extends BaseView { + + @ApiModelProperty("The amount of active time spent") + public int getActiveTime() { + return value.getActiveTime(); + } + + @ApiModelProperty("The amount of time spent afk (only works if Nucleus is present)") + public int getAfkTime() { + return value.getAfkTime(); + } + + + public TimeHolderView(TimeHolder value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/integration/activetime/UserReportView.java b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/UserReportView.java similarity index 95% rename from src/main/java/valandur/webapi/integration/activetime/UserReportView.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/activetime/UserReportView.java index 5c1aa6d7..b3ff953d 100644 --- a/src/main/java/valandur/webapi/integration/activetime/UserReportView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/activetime/UserReportView.java @@ -1,45 +1,45 @@ -package valandur.webapi.integration.activetime; - -import com.mcsimonflash.sponge.activetime.objects.TimeHolder; -import com.mcsimonflash.sponge.activetime.objects.UserReport; -import io.swagger.annotations.ApiModel; -import valandur.webapi.serialize.BaseView; - -import java.time.LocalDate; -import java.util.UUID; - -@ApiModel("UserReport") -public class UserReportView extends BaseView { - - public UUID getUUID() { - return value.uuid; - } - public String getName() { - return value.name; - } - - public LocalDate getFrom() { - return value.from; - } - public LocalDate getTo() { - return value.to; - } - - public TimeHolder getTotal() { - return value.total; - } - public TimeHolder getDailyAverage() { - return value.dailyAverage; - } - public TimeHolder getMonthlyAverage() { - return value.monthlyAverage; - } - public TimeHolder getWeeklyAverage() { - return value.weeklyAverage; - } - - - public UserReportView(UserReport value) { - super(value); - } -} +package valandur.webapi.integration.activetime; + +import com.mcsimonflash.sponge.activetime.objects.TimeHolder; +import com.mcsimonflash.sponge.activetime.objects.UserReport; +import io.swagger.annotations.ApiModel; +import valandur.webapi.serialize.BaseView; + +import java.time.LocalDate; +import java.util.UUID; + +@ApiModel("UserReport") +public class UserReportView extends BaseView { + + public UUID getUUID() { + return value.uuid; + } + public String getName() { + return value.name; + } + + public LocalDate getFrom() { + return value.from; + } + public LocalDate getTo() { + return value.to; + } + + public TimeHolder getTotal() { + return value.total; + } + public TimeHolder getDailyAverage() { + return value.dailyAverage; + } + public TimeHolder getMonthlyAverage() { + return value.monthlyAverage; + } + public TimeHolder getWeeklyAverage() { + return value.weeklyAverage; + } + + + public UserReportView(UserReport value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/integration/cmdscheduler/CalendarScheduleView.java b/webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CalendarScheduleView.java similarity index 100% rename from src/main/java/valandur/webapi/integration/cmdscheduler/CalendarScheduleView.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CalendarScheduleView.java diff --git a/src/main/java/valandur/webapi/integration/cmdscheduler/ClassicScheduleView.java b/webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/ClassicScheduleView.java similarity index 100% rename from src/main/java/valandur/webapi/integration/cmdscheduler/ClassicScheduleView.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/ClassicScheduleView.java diff --git a/src/main/java/valandur/webapi/integration/cmdscheduler/CmdSchedulerServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CmdSchedulerServlet.java similarity index 100% rename from src/main/java/valandur/webapi/integration/cmdscheduler/CmdSchedulerServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CmdSchedulerServlet.java diff --git a/src/main/java/valandur/webapi/integration/cmdscheduler/CommandTaskView.java b/webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CommandTaskView.java similarity index 100% rename from src/main/java/valandur/webapi/integration/cmdscheduler/CommandTaskView.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CommandTaskView.java diff --git a/src/main/java/valandur/webapi/integration/cmdscheduler/CronScheduleView.java b/webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CronScheduleView.java similarity index 100% rename from src/main/java/valandur/webapi/integration/cmdscheduler/CronScheduleView.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/cmdscheduler/CronScheduleView.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/CachedCase.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedCase.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/CachedCase.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedCase.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/CachedDrop.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedDrop.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/CachedDrop.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedDrop.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/CachedExecCommand.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedExecCommand.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/CachedExecCommand.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedExecCommand.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/CachedKey.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedKey.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/CachedKey.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedKey.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/CachedManager.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedManager.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/CachedManager.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedManager.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/CachedOpenManager.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedOpenManager.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/CachedOpenManager.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedOpenManager.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/CachedPreview.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedPreview.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/CachedPreview.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/CachedPreview.java diff --git a/src/main/java/valandur/webapi/integration/gwmcrates/GWMCratesServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/GWMCratesServlet.java similarity index 100% rename from src/main/java/valandur/webapi/integration/gwmcrates/GWMCratesServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/gwmcrates/GWMCratesServlet.java diff --git a/src/main/java/valandur/webapi/integration/huskycrates/CachedCrateReward.java b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CachedCrateReward.java similarity index 97% rename from src/main/java/valandur/webapi/integration/huskycrates/CachedCrateReward.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CachedCrateReward.java index bd06cb35..c061636a 100644 --- a/src/main/java/valandur/webapi/integration/huskycrates/CachedCrateReward.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CachedCrateReward.java @@ -1,92 +1,92 @@ -/*package valandur.webapi.integration.huskycrates; - -import com.codehusky.huskycrates.crate.config.CrateReward; -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonSetter; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import org.spongepowered.api.item.inventory.ItemStack; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.serialize.JsonDetails; - -import java.util.List; -import java.util.stream.Collectors; - -@ConfigSerializable -@ApiModel("HuskyCratesCrateReward") -public class CachedCrateReward extends CachedObject { - - @Setting - private String name; - @ApiModelProperty(value = "The name of this reward", required = true) - public String getName() { - return name; - } - - @Setting - private double chance; - @ApiModelProperty(value = "The chance to aquire this reward. This is relative to the chances of the other rewards in this crate", required = true) - public double getChance() { - return chance; - } - - @Setting - @JsonDetails(value = false, simple = true) - private ItemStack displayItem; - @ApiModelProperty(value = "The ItemStack that is shown in the UI", required = true) - public ItemStack getDisplayItem() { - return displayItem; - } - - @Setting - private boolean announce; - @ApiModelProperty(value = "True if this reward is announced in chat, false otherwise", required = true) - public boolean isAnnounce() { - return announce; - } - - @JsonIgnore - private List objects; - @JsonGetter - @ApiModelProperty(value = "The objects that are rewarded as part of this reward (can be commands and/or items)", required = true) - public List getObjects() { - return objects; - } - @JsonSetter - public void setObjects(List objects) { - this.objects = objects; - } - - - public CachedCrateReward() { - super(null); - } - public CachedCrateReward(CrateReward reward) { - super(reward); - - this.name = reward.getRewardName(); - this.chance = reward.getChance(); - this.displayItem = reward.getDisplayItem().copy(); - this.announce = reward.shouldAnnounce(); - this.objects = reward.getRewards().stream().map(this::getRewardObject).collect(Collectors.toList()); - } - - private CrateRewardObject getRewardObject(Object obj) { - if (obj instanceof ItemStack) - return new ItemCrateReward(((ItemStack)obj).copy()); - if (obj instanceof String) - return new CommandCrateReward(obj.toString()); - return null; - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +/*package valandur.webapi.integration.huskycrates; + +import com.codehusky.huskycrates.crate.config.CrateReward; +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonSetter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.api.item.inventory.ItemStack; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.serialize.JsonDetails; + +import java.util.List; +import java.util.stream.Collectors; + +@ConfigSerializable +@ApiModel("HuskyCratesCrateReward") +public class CachedCrateReward extends CachedObject { + + @Setting + private String name; + @ApiModelProperty(value = "The name of this reward", required = true) + public String getName() { + return name; + } + + @Setting + private double chance; + @ApiModelProperty(value = "The chance to aquire this reward. This is relative to the chances of the other rewards in this crate", required = true) + public double getChance() { + return chance; + } + + @Setting + @JsonDetails(value = false, simple = true) + private ItemStack displayItem; + @ApiModelProperty(value = "The ItemStack that is shown in the UI", required = true) + public ItemStack getDisplayItem() { + return displayItem; + } + + @Setting + private boolean announce; + @ApiModelProperty(value = "True if this reward is announced in chat, false otherwise", required = true) + public boolean isAnnounce() { + return announce; + } + + @JsonIgnore + private List objects; + @JsonGetter + @ApiModelProperty(value = "The objects that are rewarded as part of this reward (can be commands and/or items)", required = true) + public List getObjects() { + return objects; + } + @JsonSetter + public void setObjects(List objects) { + this.objects = objects; + } + + + public CachedCrateReward() { + super(null); + } + public CachedCrateReward(CrateReward reward) { + super(reward); + + this.name = reward.getRewardName(); + this.chance = reward.getChance(); + this.displayItem = reward.getDisplayItem().copy(); + this.announce = reward.shouldAnnounce(); + this.objects = reward.getRewards().stream().map(this::getRewardObject).collect(Collectors.toList()); + } + + private CrateRewardObject getRewardObject(Object obj) { + if (obj instanceof ItemStack) + return new ItemCrateReward(((ItemStack)obj).copy()); + if (obj instanceof String) + return new CommandCrateReward(obj.toString()); + return null; + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/integration/huskycrates/CachedVirtualCrate.java b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CachedVirtualCrate.java similarity index 96% rename from src/main/java/valandur/webapi/integration/huskycrates/CachedVirtualCrate.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CachedVirtualCrate.java index b92e0b6e..dd689717 100644 --- a/src/main/java/valandur/webapi/integration/huskycrates/CachedVirtualCrate.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CachedVirtualCrate.java @@ -1,99 +1,99 @@ -/*package valandur.webapi.integration.huskycrates; - -import com.codehusky.huskycrates.crate.VirtualCrate; -import com.codehusky.huskycrates.crate.config.CrateReward; -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.util.Constants; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@ApiModel("HuskyCratesCrate") -public class CachedVirtualCrate extends CachedObject { - - private String id; - @ApiModelProperty(value = "The unique id of this crate", required = true) - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - - private String name; - @ApiModelProperty(value = "The name of the crate", required = true) - public String getName() { - return name; - } - - private String type; - @ApiModelProperty(value = "The type of crate", allowableValues = "Spinner, Roulette, Instant, Simple", required = true) - public String getType() { - return type; - } - - private boolean free; - @JsonDetails - @ApiModelProperty(value = "True if this crate is free to open, false otherwise", required = true) - public boolean isFree() { - return free; - } - - private Integer freeDelay; - @JsonDetails - @ApiModelProperty(value = "In case this crate is free, this interval specifies the time (in seconds) after which this crate can be opened again", required = true) - public Integer getFreeDelay() { - return freeDelay; - } - - private boolean scrambleRewards; - @JsonDetails - @ApiModelProperty(value = "True if the rewards are scrambled, false otherwise", required = true) - public boolean isScrambleRewards() { - return scrambleRewards; - } - - @JsonIgnore - private Map keys; - @JsonDetails - @ApiModelProperty(value = "A map from currently pending player UUIDs to keys", required = true) - public Map getKeys() { - return keys; - } - - private List rewards; - @JsonDetails - @ApiModelProperty(value = "The possible rewards awarded for opening this crate", required = true) - public List getRewards() { - return rewards; - } - - - public CachedVirtualCrate() { - super(null); - } - public CachedVirtualCrate(VirtualCrate crate) { - super(crate); - - this.id = crate.id; - this.name = crate.displayName; - this.type = crate.crateType; - this.free = crate.freeCrate; - this.freeDelay = (Integer)crate.getOptions().get("freeCrateDelay"); - this.keys = crate.pendingKeys; - this.rewards = crate.getItemSet().stream() - .map(o -> new CachedCrateReward((CrateReward)o[1])) - .collect(Collectors.toList()); - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/husky-crates/crate/" + id; - } -} +/*package valandur.webapi.integration.huskycrates; + +import com.codehusky.huskycrates.crate.VirtualCrate; +import com.codehusky.huskycrates.crate.config.CrateReward; +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.util.Constants; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@ApiModel("HuskyCratesCrate") +public class CachedVirtualCrate extends CachedObject { + + private String id; + @ApiModelProperty(value = "The unique id of this crate", required = true) + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + private String name; + @ApiModelProperty(value = "The name of the crate", required = true) + public String getName() { + return name; + } + + private String type; + @ApiModelProperty(value = "The type of crate", allowableValues = "Spinner, Roulette, Instant, Simple", required = true) + public String getType() { + return type; + } + + private boolean free; + @JsonDetails + @ApiModelProperty(value = "True if this crate is free to open, false otherwise", required = true) + public boolean isFree() { + return free; + } + + private Integer freeDelay; + @JsonDetails + @ApiModelProperty(value = "In case this crate is free, this interval specifies the time (in seconds) after which this crate can be opened again", required = true) + public Integer getFreeDelay() { + return freeDelay; + } + + private boolean scrambleRewards; + @JsonDetails + @ApiModelProperty(value = "True if the rewards are scrambled, false otherwise", required = true) + public boolean isScrambleRewards() { + return scrambleRewards; + } + + @JsonIgnore + private Map keys; + @JsonDetails + @ApiModelProperty(value = "A map from currently pending player UUIDs to keys", required = true) + public Map getKeys() { + return keys; + } + + private List rewards; + @JsonDetails + @ApiModelProperty(value = "The possible rewards awarded for opening this crate", required = true) + public List getRewards() { + return rewards; + } + + + public CachedVirtualCrate() { + super(null); + } + public CachedVirtualCrate(VirtualCrate crate) { + super(crate); + + this.id = crate.id; + this.name = crate.displayName; + this.type = crate.crateType; + this.free = crate.freeCrate; + this.freeDelay = (Integer)crate.getOptions().get("freeCrateDelay"); + this.keys = crate.pendingKeys; + this.rewards = crate.getItemSet().stream() + .map(o -> new CachedCrateReward((CrateReward)o[1])) + .collect(Collectors.toList()); + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/husky-crates/crate/" + id; + } +} */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/integration/huskycrates/CommandCrateReward.java b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CommandCrateReward.java similarity index 96% rename from src/main/java/valandur/webapi/integration/huskycrates/CommandCrateReward.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CommandCrateReward.java index 26207c5a..ed0d9868 100644 --- a/src/main/java/valandur/webapi/integration/huskycrates/CommandCrateReward.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CommandCrateReward.java @@ -1,35 +1,35 @@ -/*package valandur.webapi.integration.huskycrates; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import ninja.leaping.configurate.ConfigurationNode; - -@ApiModel(value = "HuskyCratesCommandReward", parent = CrateRewardObject.class) -public class CommandCrateReward extends CrateRewardObject { - - @Override - public CrateRewardObjecType getType() { - return CrateRewardObjecType.COMMAND; - } - - @JsonDeserialize - private String command; - @ApiModelProperty(value = "The command executed for the player", required = true) - public String getCommand() { - return command; - } - - - public CommandCrateReward() {} - public CommandCrateReward(String command) { - this.command = command.startsWith("/") ? command.substring(1) : command; - } - - @Override - public void saveToNode(ConfigurationNode node) { - super.saveToNode(node); - node.getNode("command").setValue(command); - } -} +/*package valandur.webapi.integration.huskycrates; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import ninja.leaping.configurate.ConfigurationNode; + +@ApiModel(value = "HuskyCratesCommandReward", parent = CrateRewardObject.class) +public class CommandCrateReward extends CrateRewardObject { + + @Override + public CrateRewardObjecType getType() { + return CrateRewardObjecType.COMMAND; + } + + @JsonDeserialize + private String command; + @ApiModelProperty(value = "The command executed for the player", required = true) + public String getCommand() { + return command; + } + + + public CommandCrateReward() {} + public CommandCrateReward(String command) { + this.command = command.startsWith("/") ? command.substring(1) : command; + } + + @Override + public void saveToNode(ConfigurationNode node) { + super.saveToNode(node); + node.getNode("command").setValue(command); + } +} */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/integration/huskycrates/CrateRewardObject.java b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CrateRewardObject.java similarity index 97% rename from src/main/java/valandur/webapi/integration/huskycrates/CrateRewardObject.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CrateRewardObject.java index ea23a949..e3dc1b2e 100644 --- a/src/main/java/valandur/webapi/integration/huskycrates/CrateRewardObject.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/CrateRewardObject.java @@ -1,40 +1,40 @@ -/*package valandur.webapi.integration.huskycrates; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import ninja.leaping.configurate.ConfigurationNode; - -import static com.fasterxml.jackson.annotation.JsonSubTypes.Type; - -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.EXISTING_PROPERTY, - property = "type", - defaultImpl = CrateRewardObject.class -) -@JsonSubTypes({ - @Type(value = CommandCrateReward.class, name = "COMMAND"), - @Type(value = ItemCrateReward.class, name = "ITEM"), -}) -@ApiModel(value = "HuskyCratesCrateRewardObject", discriminator = "type", subTypes = { CommandCrateReward.class, ItemCrateReward.class }) -public abstract class CrateRewardObject { - - public enum CrateRewardObjecType { - ITEM, COMMAND - } - - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @ApiModelProperty(value = "The type of reward object", required = true, allowableValues = "ITEM, COMMAND") - public abstract CrateRewardObjecType getType(); - - - public CrateRewardObject() {} - - public void saveToNode(ConfigurationNode node) { - node.getNode("type").setValue(getType().toString().toLowerCase()); - } -} +/*package valandur.webapi.integration.huskycrates; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import ninja.leaping.configurate.ConfigurationNode; + +import static com.fasterxml.jackson.annotation.JsonSubTypes.Type; + +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, + include = JsonTypeInfo.As.EXISTING_PROPERTY, + property = "type", + defaultImpl = CrateRewardObject.class +) +@JsonSubTypes({ + @Type(value = CommandCrateReward.class, name = "COMMAND"), + @Type(value = ItemCrateReward.class, name = "ITEM"), +}) +@ApiModel(value = "HuskyCratesCrateRewardObject", discriminator = "type", subTypes = { CommandCrateReward.class, ItemCrateReward.class }) +public abstract class CrateRewardObject { + + public enum CrateRewardObjecType { + ITEM, COMMAND + } + + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @ApiModelProperty(value = "The type of reward object", required = true, allowableValues = "ITEM, COMMAND") + public abstract CrateRewardObjecType getType(); + + + public CrateRewardObject() {} + + public void saveToNode(ConfigurationNode node) { + node.getNode("type").setValue(getType().toString().toLowerCase()); + } +} */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/integration/huskycrates/HuskyCratesServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/HuskyCratesServlet.java similarity index 97% rename from src/main/java/valandur/webapi/integration/huskycrates/HuskyCratesServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/HuskyCratesServlet.java index ca03599d..355d8573 100644 --- a/src/main/java/valandur/webapi/integration/huskycrates/HuskyCratesServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/HuskyCratesServlet.java @@ -1,227 +1,227 @@ -/*package valandur.webapi.integration.huskycrates; - -import com.codehusky.huskycrates.HuskyCrates; -import com.codehusky.huskycrates.crate.VirtualCrate; -import com.codehusky.huskycrates.crate.config.CrateReward; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.plugin.PluginContainer; -import valandur.webapi.WebAPI; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Optional; - -@Path("husky-crates") -@Api( - tags = { "Husky Crates" }, - value = "Create, edit and delete the crate types on your server, without having to restart it.") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class HuskyCratesServlet extends BaseServlet { - - public static void onRegister() { - SerializeService srv = WebAPI.getSerializeService(); - srv.registerCache(VirtualCrate.class, CachedVirtualCrate.class); - srv.registerCache(CrateReward.class, CachedCrateReward.class); - } - - - private HuskyCrates getHuskyPlugin() { - Optional optContainer = Sponge.getPluginManager().getPlugin("huskycrates"); - if (!optContainer.isPresent()) { - throw new InternalServerErrorException("HuskyCrates plugin not found"); - } - - Optional optPlugin = optContainer.get().getInstance(); - if (!optPlugin.isPresent()) { - throw new InternalServerErrorException("HuskyCrates plugin instance not found"); - } - - return (HuskyCrates)optPlugin.get(); - } - - @GET - @Path("/crate") - @Permission({ "crate", "list" }) - @ApiOperation( - value = "List crates", - notes = "Get a list of all the crates on the server.") - public Collection listCrates() { - return WebAPI.runOnMain(() -> { - HuskyCrates plugin = getHuskyPlugin(); - List crates = new ArrayList<>(); - for (VirtualCrate crate : plugin.getCrateUtilities().crateTypes.values()) { - crates.add(new CachedVirtualCrate(crate)); - } - return crates; - }); - } - - @GET - @Path("/crate/{id}") - @Permission({ "crate", "one" }) - @ApiOperation( - value = "Get a crate", - notes = "Get detailed information about a crate.") - public CachedVirtualCrate getCrate(@PathParam("id") String id) - throws NotFoundException { - return WebAPI.runOnMain(() -> { - HuskyCrates plugin = getHuskyPlugin(); - VirtualCrate crate = plugin.crateUtilities.getVirtualCrate(id); - if (crate == null) { - throw new NotFoundException("Crate with id " + id + " not found"); - } - - return new CachedVirtualCrate(crate); - }); - } - - @POST - @Path("/crate") - @Permission({ "crate", "create "}) - @ApiOperation( - value = "Create a crate", - response = CachedVirtualCrate.class, - notes = "Creates a new crate.") - public Response createCrate(CachedVirtualCrate req) throws URISyntaxException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - CachedVirtualCrate crate = WebAPI.runOnMain(() -> { - HuskyCrates plugin = getHuskyPlugin(); - saveCrate(plugin.crateConfig, req); - plugin.crateUtilities.generateVirtualCrates(plugin.crateConfig); - - VirtualCrate vCrate = plugin.crateUtilities.getVirtualCrate(req.getId()); - if (vCrate == null) { - throw new InternalServerErrorException("Could not get crate after creating it"); - } - - return new CachedVirtualCrate(vCrate); - }); - - return Response.created(new URI(null, null, crate.getLink(), null)).entity(crate).build(); - } - - @PUT - @Path("/crate/{id}") - @Permission({ "crate", "modify" }) - @ApiOperation( - value = "Change a crate", - notes = "Modify a crate.") - public CachedVirtualCrate modifyCrate(@PathParam("id") String id, CachedVirtualCrate req) - throws NotFoundException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - return WebAPI.runOnMain(() -> { - HuskyCrates plugin = getHuskyPlugin(); - VirtualCrate oldCrate = plugin.crateUtilities.getVirtualCrate(id); - if (oldCrate == null) { - throw new NotFoundException("Crate with id " + id + " not found"); - } - - req.setId(oldCrate.id); - saveCrate(plugin.crateConfig, req); - plugin.crateUtilities.generateVirtualCrates(plugin.crateConfig); - - VirtualCrate crate = plugin.crateUtilities.getVirtualCrate(req.getId()); - - if (crate == null) { - throw new InternalServerErrorException("Could not get crate after modifying it"); - } - - return new CachedVirtualCrate(crate); - }); - } - - @DELETE - @Path("/crate/{id}") - @Permission({ "crate", "delete" }) - @ApiOperation( - value = "Delete a crate", - notes = "Delete a crate.") - public CachedVirtualCrate deleteCrate(@PathParam("id") String id) - throws NotFoundException { - - return WebAPI.runOnMain(() -> { - HuskyCrates plugin = getHuskyPlugin(); - VirtualCrate crate = plugin.crateUtilities.getVirtualCrate(id); - if (crate == null) { - throw new NotFoundException("Crate with id " + id + " not found"); - } - - try { - ConfigurationNode node = node = plugin.crateConfig.load(); - node.getNode("crates").removeChild(crate.id); - plugin.crateConfig.save(node); - - plugin.crateUtilities.generateVirtualCrates(plugin.crateConfig); - - return new CachedVirtualCrate(crate); - } catch (IOException e) { - throw new InternalServerErrorException(e.getMessage()); - } - }); - } - - private void saveCrate(ConfigurationLoader loader, CachedVirtualCrate crate) { - try { - ConfigurationNode root = loader.load(); - ConfigurationNode node = root.getNode("crates", crate.getId()); - - node.getNode("name").setValue(crate.getName()); - node.getNode("type").setValue(crate.getType()); - node.getNode("options", "freeCrate").setValue(crate.isFree()); - node.getNode("options", "freeCrateDelay").setValue(crate.getFreeDelay()); - node.getNode("options", "scrambleRewards").setValue(crate.isScrambleRewards()); - - node.removeChild("items"); - - if (crate.getRewards() != null) { - ConfigurationNode itemsNode = node.getNode("items"); - for (CachedCrateReward reward : crate.getRewards()) { - ConfigurationNode rewardNode = itemsNode.getAppendedNode(); - rewardNode.getNode("name").setValue(reward.getName()); - if (reward.getDisplayItem() != null) - rewardNode.getNode("id").setValue(reward.getDisplayItem().getType().getId()); - else - rewardNode.getNode("id").setValue("minecraft:dirt"); - rewardNode.getNode("count").setValue(1); - - ConfigurationNode huskyNode = rewardNode.getNode("huskydata"); - huskyNode.getNode("weight").setValue(reward.getChance()); - huskyNode.removeChild("rewards"); - - ConfigurationNode rewardsNode = huskyNode.getNode("rewards"); - for (CrateRewardObject object : reward.getObjects()) { - object.saveToNode(rewardsNode.getAppendedNode()); - } - } - } - - loader.save(root); - } catch (IOException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } -} +/*package valandur.webapi.integration.huskycrates; + +import com.codehusky.huskycrates.HuskyCrates; +import com.codehusky.huskycrates.crate.VirtualCrate; +import com.codehusky.huskycrates.crate.config.CrateReward; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.loader.ConfigurationLoader; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.plugin.PluginContainer; +import valandur.webapi.WebAPI; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +@Path("husky-crates") +@Api( + tags = { "Husky Crates" }, + value = "Create, edit and delete the crate types on your server, without having to restart it.") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class HuskyCratesServlet extends BaseServlet { + + public static void onRegister() { + SerializeService srv = WebAPI.getSerializeService(); + srv.registerCache(VirtualCrate.class, CachedVirtualCrate.class); + srv.registerCache(CrateReward.class, CachedCrateReward.class); + } + + + private HuskyCrates getHuskyPlugin() { + Optional optContainer = Sponge.getPluginManager().getPlugin("huskycrates"); + if (!optContainer.isPresent()) { + throw new InternalServerErrorException("HuskyCrates plugin not found"); + } + + Optional optPlugin = optContainer.get().getInstance(); + if (!optPlugin.isPresent()) { + throw new InternalServerErrorException("HuskyCrates plugin instance not found"); + } + + return (HuskyCrates)optPlugin.get(); + } + + @GET + @Path("/crate") + @Permission({ "crate", "list" }) + @ApiOperation( + value = "List crates", + notes = "Get a list of all the crates on the server.") + public Collection listCrates() { + return WebAPI.runOnMain(() -> { + HuskyCrates plugin = getHuskyPlugin(); + List crates = new ArrayList<>(); + for (VirtualCrate crate : plugin.getCrateUtilities().crateTypes.values()) { + crates.add(new CachedVirtualCrate(crate)); + } + return crates; + }); + } + + @GET + @Path("/crate/{id}") + @Permission({ "crate", "one" }) + @ApiOperation( + value = "Get a crate", + notes = "Get detailed information about a crate.") + public CachedVirtualCrate getCrate(@PathParam("id") String id) + throws NotFoundException { + return WebAPI.runOnMain(() -> { + HuskyCrates plugin = getHuskyPlugin(); + VirtualCrate crate = plugin.crateUtilities.getVirtualCrate(id); + if (crate == null) { + throw new NotFoundException("Crate with id " + id + " not found"); + } + + return new CachedVirtualCrate(crate); + }); + } + + @POST + @Path("/crate") + @Permission({ "crate", "create "}) + @ApiOperation( + value = "Create a crate", + response = CachedVirtualCrate.class, + notes = "Creates a new crate.") + public Response createCrate(CachedVirtualCrate req) throws URISyntaxException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + CachedVirtualCrate crate = WebAPI.runOnMain(() -> { + HuskyCrates plugin = getHuskyPlugin(); + saveCrate(plugin.crateConfig, req); + plugin.crateUtilities.generateVirtualCrates(plugin.crateConfig); + + VirtualCrate vCrate = plugin.crateUtilities.getVirtualCrate(req.getId()); + if (vCrate == null) { + throw new InternalServerErrorException("Could not get crate after creating it"); + } + + return new CachedVirtualCrate(vCrate); + }); + + return Response.created(new URI(null, null, crate.getLink(), null)).entity(crate).build(); + } + + @PUT + @Path("/crate/{id}") + @Permission({ "crate", "modify" }) + @ApiOperation( + value = "Change a crate", + notes = "Modify a crate.") + public CachedVirtualCrate modifyCrate(@PathParam("id") String id, CachedVirtualCrate req) + throws NotFoundException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + return WebAPI.runOnMain(() -> { + HuskyCrates plugin = getHuskyPlugin(); + VirtualCrate oldCrate = plugin.crateUtilities.getVirtualCrate(id); + if (oldCrate == null) { + throw new NotFoundException("Crate with id " + id + " not found"); + } + + req.setId(oldCrate.id); + saveCrate(plugin.crateConfig, req); + plugin.crateUtilities.generateVirtualCrates(plugin.crateConfig); + + VirtualCrate crate = plugin.crateUtilities.getVirtualCrate(req.getId()); + + if (crate == null) { + throw new InternalServerErrorException("Could not get crate after modifying it"); + } + + return new CachedVirtualCrate(crate); + }); + } + + @DELETE + @Path("/crate/{id}") + @Permission({ "crate", "delete" }) + @ApiOperation( + value = "Delete a crate", + notes = "Delete a crate.") + public CachedVirtualCrate deleteCrate(@PathParam("id") String id) + throws NotFoundException { + + return WebAPI.runOnMain(() -> { + HuskyCrates plugin = getHuskyPlugin(); + VirtualCrate crate = plugin.crateUtilities.getVirtualCrate(id); + if (crate == null) { + throw new NotFoundException("Crate with id " + id + " not found"); + } + + try { + ConfigurationNode node = node = plugin.crateConfig.load(); + node.getNode("crates").removeChild(crate.id); + plugin.crateConfig.save(node); + + plugin.crateUtilities.generateVirtualCrates(plugin.crateConfig); + + return new CachedVirtualCrate(crate); + } catch (IOException e) { + throw new InternalServerErrorException(e.getMessage()); + } + }); + } + + private void saveCrate(ConfigurationLoader loader, CachedVirtualCrate crate) { + try { + ConfigurationNode root = loader.load(); + ConfigurationNode node = root.getNode("crates", crate.getId()); + + node.getNode("name").setValue(crate.getName()); + node.getNode("type").setValue(crate.getType()); + node.getNode("options", "freeCrate").setValue(crate.isFree()); + node.getNode("options", "freeCrateDelay").setValue(crate.getFreeDelay()); + node.getNode("options", "scrambleRewards").setValue(crate.isScrambleRewards()); + + node.removeChild("items"); + + if (crate.getRewards() != null) { + ConfigurationNode itemsNode = node.getNode("items"); + for (CachedCrateReward reward : crate.getRewards()) { + ConfigurationNode rewardNode = itemsNode.getAppendedNode(); + rewardNode.getNode("name").setValue(reward.getName()); + if (reward.getDisplayItem() != null) + rewardNode.getNode("id").setValue(reward.getDisplayItem().getType().getId()); + else + rewardNode.getNode("id").setValue("minecraft:dirt"); + rewardNode.getNode("count").setValue(1); + + ConfigurationNode huskyNode = rewardNode.getNode("huskydata"); + huskyNode.getNode("weight").setValue(reward.getChance()); + huskyNode.removeChild("rewards"); + + ConfigurationNode rewardsNode = huskyNode.getNode("rewards"); + for (CrateRewardObject object : reward.getObjects()) { + object.saveToNode(rewardsNode.getAppendedNode()); + } + } + } + + loader.save(root); + } catch (IOException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } +} */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/integration/huskycrates/ItemCrateReward.java b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/ItemCrateReward.java similarity index 96% rename from src/main/java/valandur/webapi/integration/huskycrates/ItemCrateReward.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/ItemCrateReward.java index 357990aa..f1f0d3a0 100644 --- a/src/main/java/valandur/webapi/integration/huskycrates/ItemCrateReward.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/huskycrates/ItemCrateReward.java @@ -1,39 +1,39 @@ -/*package valandur.webapi.integration.huskycrates; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import ninja.leaping.configurate.ConfigurationNode; -import org.spongepowered.api.item.inventory.ItemStack; -import valandur.webapi.serialize.JsonDetails; - -@ApiModel(value = "HuskyCratesItemReward", parent = CrateRewardObject.class) -public class ItemCrateReward extends CrateRewardObject { - - @Override - public CrateRewardObjecType getType() { - return CrateRewardObjecType.ITEM; - } - - @JsonDeserialize - private ItemStack item; - @JsonDetails(value = false, simple = true) - @ApiModelProperty(value = "The item that is awarded to the player", required = true) - public ItemStack getItem() { - return item; - } - - - public ItemCrateReward() {} - public ItemCrateReward(ItemStack item) { - this.item = item; - } - - @Override - public void saveToNode(ConfigurationNode node) { - super.saveToNode(node); - node.getNode("overrideItem", "id").setValue(item.getType().getId()); - node.getNode("overrideItem", "count").setValue(item.getQuantity()); - } -} +/*package valandur.webapi.integration.huskycrates; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import ninja.leaping.configurate.ConfigurationNode; +import org.spongepowered.api.item.inventory.ItemStack; +import valandur.webapi.serialize.JsonDetails; + +@ApiModel(value = "HuskyCratesItemReward", parent = CrateRewardObject.class) +public class ItemCrateReward extends CrateRewardObject { + + @Override + public CrateRewardObjecType getType() { + return CrateRewardObjecType.ITEM; + } + + @JsonDeserialize + private ItemStack item; + @JsonDetails(value = false, simple = true) + @ApiModelProperty(value = "The item that is awarded to the player", required = true) + public ItemStack getItem() { + return item; + } + + + public ItemCrateReward() {} + public ItemCrateReward(ItemStack item) { + this.item = item; + } + + @Override + public void saveToNode(ConfigurationNode node) { + super.saveToNode(node); + node.getNode("overrideItem", "id").setValue(item.getType().getId()); + node.getNode("overrideItem", "count").setValue(item.getQuantity()); + } +} */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/integration/mmcrestrict/CachedItemData.java b/webapi-sponge/src/main/java/valandur/webapi/integration/mmcrestrict/CachedItemData.java similarity index 97% rename from src/main/java/valandur/webapi/integration/mmcrestrict/CachedItemData.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/mmcrestrict/CachedItemData.java index 0709ff3c..88edc45f 100644 --- a/src/main/java/valandur/webapi/integration/mmcrestrict/CachedItemData.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/mmcrestrict/CachedItemData.java @@ -1,119 +1,119 @@ -package valandur.webapi.integration.mmcrestrict; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import net.moddedminecraft.mmcrestrict.Data.ItemData; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.item.ItemType; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.cache.misc.CachedCatalogType; -import valandur.webapi.util.Constants; - -import java.util.Optional; - -@ApiModel("MMCRestrictItem") -public class CachedItemData extends CachedObject { - - private CachedCatalogType item; - @ApiModelProperty(value = "The item type that is banned", required = true) - public CachedCatalogType getItem() { - return item; - } - public void setItem(CachedCatalogType item) { - this.item = item; - } - - private String banReason; - @ApiModelProperty(value = "The reason why the item is banned", required = true) - public String getBanReason() { - return banReason; - } - - private Boolean ownershipBanned; - @ApiModelProperty(value = "True if ownership of this item is banned, false otherwise", required = true) - public Boolean getOwnershipBanned() { - return ownershipBanned; - } - - private Boolean usageBanned; - @ApiModelProperty(value = "True if the usage of this item is banned, false otherwise", required = true) - public Boolean getUsageBanned() { - return usageBanned; - } - - private Boolean breakingBanned; - @ApiModelProperty(value = "True if breaking of this item is banned, false otherwise", required = true) - public Boolean getBreakingBanned() { - return breakingBanned; - } - - private Boolean placingBanned; - @ApiModelProperty(value = "True if the placing of this item is banned, false otherwise", required = true) - public Boolean getPlacingBanned() { - return placingBanned; - } - - private Boolean dropBanned; - @ApiModelProperty(value = "True if dropping this item is banned, false otherwise", required = true) - public Boolean getDropBanned() { - return dropBanned; - } - - private Boolean craftBanned; - @ApiModelProperty(value = "True if crafting this item is banned, false otherwise", required = true) - public Boolean getCraftBanned() { - return craftBanned; - } - - private Boolean worldBanned; - @ApiModelProperty(value = "True if this item is banned from the world, false otherwise?", required = true) - public Boolean getWorldBanned() { - return worldBanned; - } - - private Boolean hidden; - @ApiModelProperty(value = "True if this item shows up in the public restricted items list, false otherwise", required = true) - public Boolean getHidden() { - return hidden; - } - - - public CachedItemData() { - super(null); - } - public CachedItemData(ItemData value) { - super(value); - - this.item = new CachedCatalogType<>(Sponge.getRegistry().getType(ItemType.class, value.getItemid()).orElse(null)); - this.banReason = value.getBanreason(); - this.ownershipBanned = value.getOwnershipbanned(); - this.usageBanned = value.getUsagebanned(); - this.breakingBanned = value.getBreakingbanned(); - this.placingBanned = value.getPlacingbanned(); - this.dropBanned = value.getDropbanned(); - this.craftBanned = value.getCraftbanned(); - this.worldBanned = value.getWorldbanned(); - this.hidden = value.getHidden(); - } - - @Override - public Optional getLive() { - return Optional.of(new ItemData( - hidden, - item.getId(), - item.getName(), - banReason != null ? banReason : "", - usageBanned != null ? usageBanned : true, - breakingBanned != null ? breakingBanned : false, - placingBanned != null ? placingBanned : false, - ownershipBanned != null ? ownershipBanned : true, - dropBanned != null ? dropBanned : false, - craftBanned != null ? craftBanned : false, - worldBanned != null ? worldBanned : false)); - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/mmc-restrict/item/" + item.getId(); - } -} +package valandur.webapi.integration.mmcrestrict; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import net.moddedminecraft.mmcrestrict.Data.ItemData; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.item.ItemType; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.cache.misc.CachedCatalogType; +import valandur.webapi.util.Constants; + +import java.util.Optional; + +@ApiModel("MMCRestrictItem") +public class CachedItemData extends CachedObject { + + private CachedCatalogType item; + @ApiModelProperty(value = "The item type that is banned", required = true) + public CachedCatalogType getItem() { + return item; + } + public void setItem(CachedCatalogType item) { + this.item = item; + } + + private String banReason; + @ApiModelProperty(value = "The reason why the item is banned", required = true) + public String getBanReason() { + return banReason; + } + + private Boolean ownershipBanned; + @ApiModelProperty(value = "True if ownership of this item is banned, false otherwise", required = true) + public Boolean getOwnershipBanned() { + return ownershipBanned; + } + + private Boolean usageBanned; + @ApiModelProperty(value = "True if the usage of this item is banned, false otherwise", required = true) + public Boolean getUsageBanned() { + return usageBanned; + } + + private Boolean breakingBanned; + @ApiModelProperty(value = "True if breaking of this item is banned, false otherwise", required = true) + public Boolean getBreakingBanned() { + return breakingBanned; + } + + private Boolean placingBanned; + @ApiModelProperty(value = "True if the placing of this item is banned, false otherwise", required = true) + public Boolean getPlacingBanned() { + return placingBanned; + } + + private Boolean dropBanned; + @ApiModelProperty(value = "True if dropping this item is banned, false otherwise", required = true) + public Boolean getDropBanned() { + return dropBanned; + } + + private Boolean craftBanned; + @ApiModelProperty(value = "True if crafting this item is banned, false otherwise", required = true) + public Boolean getCraftBanned() { + return craftBanned; + } + + private Boolean worldBanned; + @ApiModelProperty(value = "True if this item is banned from the world, false otherwise?", required = true) + public Boolean getWorldBanned() { + return worldBanned; + } + + private Boolean hidden; + @ApiModelProperty(value = "True if this item shows up in the public restricted items list, false otherwise", required = true) + public Boolean getHidden() { + return hidden; + } + + + public CachedItemData() { + super(null); + } + public CachedItemData(ItemData value) { + super(value); + + this.item = new CachedCatalogType<>(Sponge.getRegistry().getType(ItemType.class, value.getItemid()).orElse(null)); + this.banReason = value.getBanreason(); + this.ownershipBanned = value.getOwnershipbanned(); + this.usageBanned = value.getUsagebanned(); + this.breakingBanned = value.getBreakingbanned(); + this.placingBanned = value.getPlacingbanned(); + this.dropBanned = value.getDropbanned(); + this.craftBanned = value.getCraftbanned(); + this.worldBanned = value.getWorldbanned(); + this.hidden = value.getHidden(); + } + + @Override + public Optional getLive() { + return Optional.of(new ItemData( + hidden, + item.getId(), + item.getName(), + banReason != null ? banReason : "", + usageBanned != null ? usageBanned : true, + breakingBanned != null ? breakingBanned : false, + placingBanned != null ? placingBanned : false, + ownershipBanned != null ? ownershipBanned : true, + dropBanned != null ? dropBanned : false, + craftBanned != null ? craftBanned : false, + worldBanned != null ? worldBanned : false)); + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/mmc-restrict/item/" + item.getId(); + } +} diff --git a/src/main/java/valandur/webapi/integration/mmcrestrict/MMCRestrictServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/mmcrestrict/MMCRestrictServlet.java similarity index 97% rename from src/main/java/valandur/webapi/integration/mmcrestrict/MMCRestrictServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/mmcrestrict/MMCRestrictServlet.java index 4fe29047..4faa346c 100644 --- a/src/main/java/valandur/webapi/integration/mmcrestrict/MMCRestrictServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/mmcrestrict/MMCRestrictServlet.java @@ -1,167 +1,167 @@ -package valandur.webapi.integration.mmcrestrict; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import net.moddedminecraft.mmcrestrict.Data.ItemData; -import net.moddedminecraft.mmcrestrict.Main; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.item.ItemType; -import org.spongepowered.api.plugin.PluginContainer; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.misc.CachedCatalogType; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Optional; - -@Path("mmc-restrict") -@Api(tags = { "MMC Restrict" }, value = "Manage restricted items on your server.") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class MMCRestrictServlet extends BaseServlet { - - public static void onRegister() { - SerializeService srv = WebAPI.getSerializeService(); - srv.registerCache(ItemData.class, CachedItemData.class); - } - - private Main getMMCRestrictPlugin() { - Optional optContainer = Sponge.getPluginManager().getPlugin("mmcrestrict"); - if (!optContainer.isPresent()) { - throw new InternalServerErrorException("MMCRestrict plugin not found"); - } - - Optional optPlugin = optContainer.get().getInstance(); - if (!optPlugin.isPresent()) { - throw new InternalServerErrorException("MMCRestrict plugin instance not found"); - } - - return (Main)optPlugin.get(); - } - - @GET - @Path("/item") - @Permission({ "item", "list" }) - @ApiOperation( - value = "List items", - notes = "Gets the list of restricted items on the server.") - public Collection listItems() { - Main plugin = getMMCRestrictPlugin(); - - return WebAPI.runOnMain(() -> { - List items = new ArrayList<>(); - for (ItemData item : plugin.getItemData()) { - items.add(new CachedItemData(item)); - } - return items; - }); - } - - @POST - @Path("/item") - @Permission({ "item", "create" }) - @ApiOperation( - value = "Add an item", - response = CachedItemData.class, - notes = "Adds a new item to the restricted item list.") - public Response addItem(CachedItemData req) - throws BadRequestException, URISyntaxException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - if (req.getItem() == null) { - throw new BadRequestException("Invalid item data"); - } - - CachedItemData item = WebAPI.runOnMain(() -> { - Main plugin = getMMCRestrictPlugin(); - Optional optData = req.getLive(); - if (!optData.isPresent()) { - return null; - } - plugin.addItem(optData.get()); - saveData(plugin); - return new CachedItemData(optData.get()); - }); - - return Response.created(new URI(null, null, item.getLink(), null)).entity(item).build(); - } - - @PUT - @Path("/item/{id}") - @Permission({ "item", "modify" }) - @ApiOperation( - value = "Modify an item", - notes = "Modify an existing restricted item.") - public CachedItemData modifyItem(@PathParam("id") String id, CachedItemData req) - throws NotFoundException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - return WebAPI.runOnMain(() -> { - Main plugin = getMMCRestrictPlugin(); - ItemData item = plugin.removeItem(id); - if (item == null) { - throw new NotFoundException("The specified item is not restricted"); - } - // Transfer the item type of the old item to the new one - Optional optType = Sponge.getRegistry().getType(ItemType.class, item.getItemid()); - if (!optType.isPresent()) { - plugin.addItem(item); // Add the old item because we removed it - throw new InternalServerErrorException("Could not get item type"); - } - req.setItem(new CachedCatalogType<>(optType.get())); - Optional optData = req.getLive(); - if (!optData.isPresent()) { - plugin.addItem(item); // Add the old item because we removed it - throw new InternalServerErrorException("Could not create item data"); - } - plugin.addItem(optData.get()); - saveData(plugin); - return new CachedItemData(optData.get()); - }); - } - - @DELETE - @Path("/item/{id}") - @Permission({ "item", "delete" }) - @ApiOperation( - value = "Delete an item", - notes = "Delete an existing restricted item.") - public CachedItemData deleteItem(@PathParam("id") String id) - throws NotFoundException { - - return WebAPI.runOnMain(() -> { - Main plugin = getMMCRestrictPlugin(); - ItemData item = plugin.removeItem(id); - if (item == null) { - throw new NotFoundException("The specified item is not restricted"); - } - saveData(plugin); - return new CachedItemData(item); - }); - } - - private void saveData(Main plugin) { - try { - plugin.saveData(); - } catch (IOException | ObjectMappingException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } -} +package valandur.webapi.integration.mmcrestrict; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import net.moddedminecraft.mmcrestrict.Data.ItemData; +import net.moddedminecraft.mmcrestrict.Main; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.item.ItemType; +import org.spongepowered.api.plugin.PluginContainer; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.misc.CachedCatalogType; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +@Path("mmc-restrict") +@Api(tags = { "MMC Restrict" }, value = "Manage restricted items on your server.") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class MMCRestrictServlet extends BaseServlet { + + public static void onRegister() { + SerializeService srv = WebAPI.getSerializeService(); + srv.registerCache(ItemData.class, CachedItemData.class); + } + + private Main getMMCRestrictPlugin() { + Optional optContainer = Sponge.getPluginManager().getPlugin("mmcrestrict"); + if (!optContainer.isPresent()) { + throw new InternalServerErrorException("MMCRestrict plugin not found"); + } + + Optional optPlugin = optContainer.get().getInstance(); + if (!optPlugin.isPresent()) { + throw new InternalServerErrorException("MMCRestrict plugin instance not found"); + } + + return (Main)optPlugin.get(); + } + + @GET + @Path("/item") + @Permission({ "item", "list" }) + @ApiOperation( + value = "List items", + notes = "Gets the list of restricted items on the server.") + public Collection listItems() { + Main plugin = getMMCRestrictPlugin(); + + return WebAPI.runOnMain(() -> { + List items = new ArrayList<>(); + for (ItemData item : plugin.getItemData()) { + items.add(new CachedItemData(item)); + } + return items; + }); + } + + @POST + @Path("/item") + @Permission({ "item", "create" }) + @ApiOperation( + value = "Add an item", + response = CachedItemData.class, + notes = "Adds a new item to the restricted item list.") + public Response addItem(CachedItemData req) + throws BadRequestException, URISyntaxException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + if (req.getItem() == null) { + throw new BadRequestException("Invalid item data"); + } + + CachedItemData item = WebAPI.runOnMain(() -> { + Main plugin = getMMCRestrictPlugin(); + Optional optData = req.getLive(); + if (!optData.isPresent()) { + return null; + } + plugin.addItem(optData.get()); + saveData(plugin); + return new CachedItemData(optData.get()); + }); + + return Response.created(new URI(null, null, item.getLink(), null)).entity(item).build(); + } + + @PUT + @Path("/item/{id}") + @Permission({ "item", "modify" }) + @ApiOperation( + value = "Modify an item", + notes = "Modify an existing restricted item.") + public CachedItemData modifyItem(@PathParam("id") String id, CachedItemData req) + throws NotFoundException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + return WebAPI.runOnMain(() -> { + Main plugin = getMMCRestrictPlugin(); + ItemData item = plugin.removeItem(id); + if (item == null) { + throw new NotFoundException("The specified item is not restricted"); + } + // Transfer the item type of the old item to the new one + Optional optType = Sponge.getRegistry().getType(ItemType.class, item.getItemid()); + if (!optType.isPresent()) { + plugin.addItem(item); // Add the old item because we removed it + throw new InternalServerErrorException("Could not get item type"); + } + req.setItem(new CachedCatalogType<>(optType.get())); + Optional optData = req.getLive(); + if (!optData.isPresent()) { + plugin.addItem(item); // Add the old item because we removed it + throw new InternalServerErrorException("Could not create item data"); + } + plugin.addItem(optData.get()); + saveData(plugin); + return new CachedItemData(optData.get()); + }); + } + + @DELETE + @Path("/item/{id}") + @Permission({ "item", "delete" }) + @ApiOperation( + value = "Delete an item", + notes = "Delete an existing restricted item.") + public CachedItemData deleteItem(@PathParam("id") String id) + throws NotFoundException { + + return WebAPI.runOnMain(() -> { + Main plugin = getMMCRestrictPlugin(); + ItemData item = plugin.removeItem(id); + if (item == null) { + throw new NotFoundException("The specified item is not restricted"); + } + saveData(plugin); + return new CachedItemData(item); + }); + } + + private void saveData(Main plugin) { + try { + plugin.saveData(); + } catch (IOException | ObjectMappingException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } +} diff --git a/src/main/java/valandur/webapi/integration/mmctickets/CachedTicketData.java b/webapi-sponge/src/main/java/valandur/webapi/integration/mmctickets/CachedTicketData.java similarity index 96% rename from src/main/java/valandur/webapi/integration/mmctickets/CachedTicketData.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/mmctickets/CachedTicketData.java index df5425fb..72f26f42 100644 --- a/src/main/java/valandur/webapi/integration/mmctickets/CachedTicketData.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/mmctickets/CachedTicketData.java @@ -1,97 +1,97 @@ -package valandur.webapi.integration.mmctickets; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import net.moddedminecraft.mmctickets.data.TicketData; -import net.moddedminecraft.mmctickets.data.ticketStatus; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.cache.player.CachedPlayer; -import valandur.webapi.cache.world.CachedLocation; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.util.Constants; - -@ApiModel("MMCTicketsTicket") -public class CachedTicketData extends CachedObject { - - private int id; - @ApiModelProperty(value = "The unique id of this ticket", required = true) - public int getId() { - return id; - } - - private long timestamp; - @ApiModelProperty(value = "The unix timestamp (in seconds) when this ticket was submitted", required = true) - public long getTimestamp() { - return timestamp; - } - - private ticketStatus status; - @ApiModelProperty(value = "The current status of the ticket", required = true) - public ticketStatus getStatus() { - return status; - } - - private String message; - @ApiModelProperty(value = "The message sent along with this ticket", required = true) - public String getMessage() { - return message; - } - - private CachedPlayer sender; - @JsonDetails - @ApiModelProperty("The sender of this ticket") - public CachedPlayer getSender() { - return sender; - } - - private String comment; - @JsonDetails - @ApiModelProperty("The comment added by staff to this ticket") - public String getComment() { - return comment; - } - - private CachedPlayer staff; - @JsonDetails - @ApiModelProperty("The staff member that was assigned to this ticket") - public CachedPlayer getStaff() { - return staff; - } - - private Integer notified; - @JsonDetails - @ApiModelProperty("True if staff has been notified about this ticket, false otherwise") - public Integer getNotified() { - return notified; - } - - private CachedLocation location; - @JsonDetails - @ApiModelProperty("The location at which this ticket was submitted") - public CachedLocation getLocation() { - return location; - } - - - public CachedTicketData() { - super(null); - } - public CachedTicketData(TicketData ticket) { - super(ticket); - - this.id = ticket.getTicketID(); - this.sender = cacheService.getPlayer(ticket.getPlayerUUID()).orElse(null); - this.timestamp = ticket.getTimestamp(); - this.message = ticket.getMessage(); - this.comment = ticket.getComment(); - this.status = ticket.getStatus(); - this.staff = cacheService.getPlayer(ticket.getPlayerUUID()).orElse(null); - this.notified = ticket.getNotified(); - this.location = new CachedLocation(ticket.getWorld(), ticket.getX(), ticket.getY(), ticket.getZ()); - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/mmc-tickets/ticket/" + id; - } -} +package valandur.webapi.integration.mmctickets; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import net.moddedminecraft.mmctickets.data.TicketData; +import net.moddedminecraft.mmctickets.data.ticketStatus; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.cache.player.CachedPlayer; +import valandur.webapi.cache.world.CachedLocation; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.util.Constants; + +@ApiModel("MMCTicketsTicket") +public class CachedTicketData extends CachedObject { + + private int id; + @ApiModelProperty(value = "The unique id of this ticket", required = true) + public int getId() { + return id; + } + + private long timestamp; + @ApiModelProperty(value = "The unix timestamp (in seconds) when this ticket was submitted", required = true) + public long getTimestamp() { + return timestamp; + } + + private ticketStatus status; + @ApiModelProperty(value = "The current status of the ticket", required = true) + public ticketStatus getStatus() { + return status; + } + + private String message; + @ApiModelProperty(value = "The message sent along with this ticket", required = true) + public String getMessage() { + return message; + } + + private CachedPlayer sender; + @JsonDetails + @ApiModelProperty("The sender of this ticket") + public CachedPlayer getSender() { + return sender; + } + + private String comment; + @JsonDetails + @ApiModelProperty("The comment added by staff to this ticket") + public String getComment() { + return comment; + } + + private CachedPlayer staff; + @JsonDetails + @ApiModelProperty("The staff member that was assigned to this ticket") + public CachedPlayer getStaff() { + return staff; + } + + private Integer notified; + @JsonDetails + @ApiModelProperty("True if staff has been notified about this ticket, false otherwise") + public Integer getNotified() { + return notified; + } + + private CachedLocation location; + @JsonDetails + @ApiModelProperty("The location at which this ticket was submitted") + public CachedLocation getLocation() { + return location; + } + + + public CachedTicketData() { + super(null); + } + public CachedTicketData(TicketData ticket) { + super(ticket); + + this.id = ticket.getTicketID(); + this.sender = cacheService.getPlayer(ticket.getPlayerUUID()).orElse(null); + this.timestamp = ticket.getTimestamp(); + this.message = ticket.getMessage(); + this.comment = ticket.getComment(); + this.status = ticket.getStatus(); + this.staff = cacheService.getPlayer(ticket.getPlayerUUID()).orElse(null); + this.notified = ticket.getNotified(); + this.location = new CachedLocation(ticket.getWorld(), ticket.getX(), ticket.getY(), ticket.getZ()); + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/mmc-tickets/ticket/" + id; + } +} diff --git a/src/main/java/valandur/webapi/integration/mmctickets/MMCTicketsServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/mmctickets/MMCTicketsServlet.java similarity index 97% rename from src/main/java/valandur/webapi/integration/mmctickets/MMCTicketsServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/mmctickets/MMCTicketsServlet.java index e4c57e24..7e98ef50 100644 --- a/src/main/java/valandur/webapi/integration/mmctickets/MMCTicketsServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/mmctickets/MMCTicketsServlet.java @@ -1,117 +1,117 @@ -package valandur.webapi.integration.mmctickets; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import net.moddedminecraft.mmctickets.Main; -import net.moddedminecraft.mmctickets.data.TicketData; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.plugin.PluginContainer; -import valandur.webapi.WebAPI; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Optional; - -@Path("mmc-tickets") -@Api(tags = { "MMC Tickets" }, value = "View, assign and reply-to tickets on the server.") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class MMCTicketsServlet extends BaseServlet { - - public static void onRegister() { - SerializeService srv = WebAPI.getSerializeService(); - srv.registerCache(TicketData.class, CachedTicketData.class); - } - - - private Main getMMCTicketsPlugin() { - Optional optContainer = Sponge.getPluginManager().getPlugin("mmctickets"); - if (!optContainer.isPresent()) { - throw new InternalServerErrorException("MMCTickets plugin not found"); - } - - Optional optPlugin = optContainer.get().getInstance(); - if (!optPlugin.isPresent()) { - throw new InternalServerErrorException("MMCTickets plugin instance not found"); - } - - return (Main)optPlugin.get(); - } - - @GET - @Path("/ticket") - @Permission({ "ticket", "list" }) - @ApiOperation( - value = "List tickets", - notes = "Get a list of all the tickets on the server.") - public Collection listTickets() { - Main plugin = getMMCTicketsPlugin(); - - return WebAPI.runOnMain(() -> { - List tickets = new ArrayList<>(); - for (TicketData ticket : plugin.getTickets()) { - tickets.add(new CachedTicketData(ticket)); - } - return tickets; - }); - } - - @GET - @Path("/ticket/{id}") - @Permission({ "ticket", "one" }) - @ApiOperation( - value = "Get a ticket", - notes = "Get detailed information about a ticket.") - public CachedTicketData getTicket(@PathParam("id") Integer id) - throws NotFoundException { - return WebAPI.runOnMain(() -> { - Main plugin = getMMCTicketsPlugin(); - TicketData ticketData = plugin.getTicket(id); - if (ticketData == null) { - throw new NotFoundException("Ticket with id " + id + " not found"); - } - - return new CachedTicketData(ticketData); - }); - } - - @PUT - @Path("/ticket/{id}") - @Permission({ "ticket", "modify" }) - @ApiOperation( - value = "Modify a ticket", - notes = "Modify the properties of an existing ticket.") - public CachedTicketData modifyTicket(@PathParam("id") Integer id, CachedTicketData req) - throws NotFoundException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - return WebAPI.runOnMain(() -> { - Main plugin = getMMCTicketsPlugin(); - TicketData ticketData = plugin.getTicket(id); - if (ticketData == null) { - throw new NotFoundException("Ticket with id " + id + " not found"); - } - - if (req.getComment() != null) { - ticketData.setComment(req.getComment()); - } - if (req.getNotified() != null) { - ticketData.setNotified(req.getNotified()); - } - if (req.getStatus() != null) { - ticketData.setStatus(req.getStatus()); - } - - return new CachedTicketData(ticketData); - }); - } -} +package valandur.webapi.integration.mmctickets; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import net.moddedminecraft.mmctickets.Main; +import net.moddedminecraft.mmctickets.data.TicketData; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.plugin.PluginContainer; +import valandur.webapi.WebAPI; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +@Path("mmc-tickets") +@Api(tags = { "MMC Tickets" }, value = "View, assign and reply-to tickets on the server.") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class MMCTicketsServlet extends BaseServlet { + + public static void onRegister() { + SerializeService srv = WebAPI.getSerializeService(); + srv.registerCache(TicketData.class, CachedTicketData.class); + } + + + private Main getMMCTicketsPlugin() { + Optional optContainer = Sponge.getPluginManager().getPlugin("mmctickets"); + if (!optContainer.isPresent()) { + throw new InternalServerErrorException("MMCTickets plugin not found"); + } + + Optional optPlugin = optContainer.get().getInstance(); + if (!optPlugin.isPresent()) { + throw new InternalServerErrorException("MMCTickets plugin instance not found"); + } + + return (Main)optPlugin.get(); + } + + @GET + @Path("/ticket") + @Permission({ "ticket", "list" }) + @ApiOperation( + value = "List tickets", + notes = "Get a list of all the tickets on the server.") + public Collection listTickets() { + Main plugin = getMMCTicketsPlugin(); + + return WebAPI.runOnMain(() -> { + List tickets = new ArrayList<>(); + for (TicketData ticket : plugin.getTickets()) { + tickets.add(new CachedTicketData(ticket)); + } + return tickets; + }); + } + + @GET + @Path("/ticket/{id}") + @Permission({ "ticket", "one" }) + @ApiOperation( + value = "Get a ticket", + notes = "Get detailed information about a ticket.") + public CachedTicketData getTicket(@PathParam("id") Integer id) + throws NotFoundException { + return WebAPI.runOnMain(() -> { + Main plugin = getMMCTicketsPlugin(); + TicketData ticketData = plugin.getTicket(id); + if (ticketData == null) { + throw new NotFoundException("Ticket with id " + id + " not found"); + } + + return new CachedTicketData(ticketData); + }); + } + + @PUT + @Path("/ticket/{id}") + @Permission({ "ticket", "modify" }) + @ApiOperation( + value = "Modify a ticket", + notes = "Modify the properties of an existing ticket.") + public CachedTicketData modifyTicket(@PathParam("id") Integer id, CachedTicketData req) + throws NotFoundException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + return WebAPI.runOnMain(() -> { + Main plugin = getMMCTicketsPlugin(); + TicketData ticketData = plugin.getTicket(id); + if (ticketData == null) { + throw new NotFoundException("Ticket with id " + id + " not found"); + } + + if (req.getComment() != null) { + ticketData.setComment(req.getComment()); + } + if (req.getNotified() != null) { + ticketData.setNotified(req.getNotified()); + } + if (req.getStatus() != null) { + ticketData.setStatus(req.getStatus()); + } + + return new CachedTicketData(ticketData); + }); + } +} diff --git a/src/main/java/valandur/webapi/integration/nucleus/CachedKit.java b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedKit.java similarity index 97% rename from src/main/java/valandur/webapi/integration/nucleus/CachedKit.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedKit.java index e7327497..68ec9539 100644 --- a/src/main/java/valandur/webapi/integration/nucleus/CachedKit.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedKit.java @@ -1,84 +1,84 @@ -package valandur.webapi.integration.nucleus; - -import io.github.nucleuspowered.nucleus.api.nucleusdata.Kit; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.value.ValueContainer; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.util.Constants; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -@ApiModel("NucleusKit") -public class CachedKit extends CachedObject { - - private String name; - @ApiModelProperty(value = "The unique name of this kit", required = true) - public String getName() { - return name; - } - - private Double cost; - @ApiModelProperty(value = "The cost to buy this kit", required = true) - public Double getCost() { - return cost; - } - - private Long cooldown; - @ApiModelProperty(value = "The cooldown (in seconds) this kit is on after buying it (per player)", required = true) - public Long getCooldown() { - return cooldown; - } - - private Boolean firstJoinKit; - @ApiModelProperty(value = "True if this kit is awarded for joining the server the first time, false otherwise", required = true) - public Boolean isFirstJoinKit() { - return firstJoinKit; - } - - private Boolean oneTime; - @ApiModelProperty(value = "True if this kit can only be purchased/acquired once, false otherwise", required = true) - public Boolean isOneTime() { - return oneTime; - } - - private List commands; - @JsonDetails - @ApiModelProperty(value = "The commands that are executed when this kit is purchased/acquired by a player", required = true) - public List getCommands() { - return commands; - } - - private List stacks; - @JsonDetails - @ApiModelProperty(value = "The ItemStacks that are awarded to the player who buys/acquires this kit", required = true) - public List getStacks() { - return stacks; - } - - - public CachedKit() { - super(null); - } - public CachedKit(Kit kit) { - super(kit); - - this.name = kit.getName(); - this.cost = kit.getCost(); - this.cooldown = kit.getCooldown().orElse(Duration.ofNanos(0)).toMillis(); - this.firstJoinKit = kit.isFirstJoinKit(); - this.oneTime = kit.isOneTime(); - this.commands = new ArrayList<>(kit.getCommands()); - this.stacks = kit.getStacks().stream().map(ValueContainer::copy).collect(Collectors.toList()); - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/nucleus/kit/" + name; - } -} +package valandur.webapi.integration.nucleus; + +import io.github.nucleuspowered.nucleus.api.nucleusdata.Kit; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.value.ValueContainer; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.util.Constants; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@ApiModel("NucleusKit") +public class CachedKit extends CachedObject { + + private String name; + @ApiModelProperty(value = "The unique name of this kit", required = true) + public String getName() { + return name; + } + + private Double cost; + @ApiModelProperty(value = "The cost to buy this kit", required = true) + public Double getCost() { + return cost; + } + + private Long cooldown; + @ApiModelProperty(value = "The cooldown (in seconds) this kit is on after buying it (per player)", required = true) + public Long getCooldown() { + return cooldown; + } + + private Boolean firstJoinKit; + @ApiModelProperty(value = "True if this kit is awarded for joining the server the first time, false otherwise", required = true) + public Boolean isFirstJoinKit() { + return firstJoinKit; + } + + private Boolean oneTime; + @ApiModelProperty(value = "True if this kit can only be purchased/acquired once, false otherwise", required = true) + public Boolean isOneTime() { + return oneTime; + } + + private List commands; + @JsonDetails + @ApiModelProperty(value = "The commands that are executed when this kit is purchased/acquired by a player", required = true) + public List getCommands() { + return commands; + } + + private List stacks; + @JsonDetails + @ApiModelProperty(value = "The ItemStacks that are awarded to the player who buys/acquires this kit", required = true) + public List getStacks() { + return stacks; + } + + + public CachedKit() { + super(null); + } + public CachedKit(Kit kit) { + super(kit); + + this.name = kit.getName(); + this.cost = kit.getCost(); + this.cooldown = kit.getCooldown().orElse(Duration.ofNanos(0)).toMillis(); + this.firstJoinKit = kit.isFirstJoinKit(); + this.oneTime = kit.isOneTime(); + this.commands = new ArrayList<>(kit.getCommands()); + this.stacks = kit.getStacks().stream().map(ValueContainer::copy).collect(Collectors.toList()); + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/nucleus/kit/" + name; + } +} diff --git a/src/main/java/valandur/webapi/integration/nucleus/CachedMailMessage.java b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedMailMessage.java similarity index 96% rename from src/main/java/valandur/webapi/integration/nucleus/CachedMailMessage.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedMailMessage.java index 255b0880..f00e57d1 100644 --- a/src/main/java/valandur/webapi/integration/nucleus/CachedMailMessage.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedMailMessage.java @@ -1,48 +1,48 @@ -package valandur.webapi.integration.nucleus; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.github.nucleuspowered.nucleus.api.nucleusdata.MailMessage; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.cache.player.CachedPlayer; - -import java.time.Instant; - -@ApiModel("NucleusMailMessage") -public class CachedMailMessage extends CachedObject { - - @ApiModelProperty(value = "The instant when the message was sent", required = true) - private Instant date; - public Instant getDate() { - return date; - } - - @ApiModelProperty(value = "The message content", required = true) - private String message; - public String getMessage() { - return message; - } - - @ApiModelProperty(value = "The sender of the message") - private CachedPlayer sender; - public CachedPlayer getSender() { - return sender; - } - - - public CachedMailMessage(MailMessage value) { - super(value); - - this.date = Instant.ofEpochMilli(value.getDate().toEpochMilli()); - this.message = value.getMessage(); - this.sender = cacheService.getPlayer(value.getSender().orElse(null)); - } - - @Override - @JsonIgnore - @ApiModelProperty(hidden = true) - public String getLink() { - return null; - } -} +package valandur.webapi.integration.nucleus; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.github.nucleuspowered.nucleus.api.nucleusdata.MailMessage; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.cache.player.CachedPlayer; + +import java.time.Instant; + +@ApiModel("NucleusMailMessage") +public class CachedMailMessage extends CachedObject { + + @ApiModelProperty(value = "The instant when the message was sent", required = true) + private Instant date; + public Instant getDate() { + return date; + } + + @ApiModelProperty(value = "The message content", required = true) + private String message; + public String getMessage() { + return message; + } + + @ApiModelProperty(value = "The sender of the message") + private CachedPlayer sender; + public CachedPlayer getSender() { + return sender; + } + + + public CachedMailMessage(MailMessage value) { + super(value); + + this.date = Instant.ofEpochMilli(value.getDate().toEpochMilli()); + this.message = value.getMessage(); + this.sender = cacheService.getPlayer(value.getSender().orElse(null)); + } + + @Override + @JsonIgnore + @ApiModelProperty(hidden = true) + public String getLink() { + return null; + } +} diff --git a/src/main/java/valandur/webapi/integration/nucleus/CachedNamedLocation.java b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedNamedLocation.java similarity index 96% rename from src/main/java/valandur/webapi/integration/nucleus/CachedNamedLocation.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedNamedLocation.java index 4b6ac9f4..749d7bbe 100644 --- a/src/main/java/valandur/webapi/integration/nucleus/CachedNamedLocation.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/CachedNamedLocation.java @@ -1,48 +1,48 @@ -package valandur.webapi.integration.nucleus; - -import com.flowpowered.math.vector.Vector3d; -import io.github.nucleuspowered.nucleus.api.nucleusdata.NamedLocation; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.cache.world.CachedLocation; -import valandur.webapi.util.Constants; - -@ApiModel("NucleusNamedLocation") -public class CachedNamedLocation extends CachedObject { - - private String name; - @ApiModelProperty(value = "The unique name of this jail", required = true) - public String getName() { - return name; - } - - private CachedLocation location; - @ApiModelProperty(value = "The location of the jail", required = true) - public CachedLocation getLocation() { - return location; - } - - private Vector3d rotation; - @ApiModelProperty(value = "The rotation of players within the jail", required = true) - public Vector3d getRotation() { - return rotation; - } - - - public CachedNamedLocation() { - super(null); - } - public CachedNamedLocation(NamedLocation value) { - super(value); - - this.name = value.getName(); - this.location = value.getLocation().map(CachedLocation::new).orElse(null); - this.rotation = value.getRotation(); - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/nucleus/jail/" + name; - } -} +package valandur.webapi.integration.nucleus; + +import com.flowpowered.math.vector.Vector3d; +import io.github.nucleuspowered.nucleus.api.nucleusdata.NamedLocation; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.cache.world.CachedLocation; +import valandur.webapi.util.Constants; + +@ApiModel("NucleusNamedLocation") +public class CachedNamedLocation extends CachedObject { + + private String name; + @ApiModelProperty(value = "The unique name of this jail", required = true) + public String getName() { + return name; + } + + private CachedLocation location; + @ApiModelProperty(value = "The location of the jail", required = true) + public CachedLocation getLocation() { + return location; + } + + private Vector3d rotation; + @ApiModelProperty(value = "The rotation of players within the jail", required = true) + public Vector3d getRotation() { + return rotation; + } + + + public CachedNamedLocation() { + super(null); + } + public CachedNamedLocation(NamedLocation value) { + super(value); + + this.name = value.getName(); + this.location = value.getLocation().map(CachedLocation::new).orElse(null); + this.rotation = value.getRotation(); + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/nucleus/jail/" + name; + } +} diff --git a/src/main/java/valandur/webapi/integration/nucleus/NucleusServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/NucleusServlet.java similarity index 97% rename from src/main/java/valandur/webapi/integration/nucleus/NucleusServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/NucleusServlet.java index d1d55050..e6cc48ce 100644 --- a/src/main/java/valandur/webapi/integration/nucleus/NucleusServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/nucleus/NucleusServlet.java @@ -1,384 +1,384 @@ -package valandur.webapi.integration.nucleus; - -import com.flowpowered.math.vector.Vector3d; -import io.github.nucleuspowered.nucleus.api.NucleusAPI; -import io.github.nucleuspowered.nucleus.api.nucleusdata.Kit; -import io.github.nucleuspowered.nucleus.api.nucleusdata.MailMessage; -import io.github.nucleuspowered.nucleus.api.nucleusdata.NamedLocation; -import io.github.nucleuspowered.nucleus.api.service.*; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import org.spongepowered.api.entity.living.player.User; -import org.spongepowered.api.world.Location; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.player.CachedPlayer; -import valandur.webapi.exceptions.NotImplementedException; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.net.URI; -import java.net.URISyntaxException; -import java.time.Duration; -import java.util.Collection; -import java.util.Optional; -import java.util.stream.Collectors; - -@Path("nucleus") -@Api(tags = { "Nucleus" }, value = "Manage your kits and jails") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class NucleusServlet extends BaseServlet { - - public static void onRegister() { - SerializeService srv = WebAPI.getSerializeService(); - srv.registerCache(NamedLocation.class, CachedNamedLocation.class); - srv.registerCache(MailMessage.class, CachedMailMessage.class); - srv.registerCache(Kit.class, CachedKit.class); - } - - - // Jails - @GET - @Path("/jail") - @Permission({ "jail", "list" }) - @ApiOperation(value = "List jails", notes = "Get a list of all the jails on the server.") - public Collection listJails() { - Optional optSrv = NucleusAPI.getJailService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues jail service not available"); - } - - NucleusJailService srv = optSrv.get(); - - return WebAPI.runOnMain( - () -> srv.getJails().values().stream() - .map(CachedNamedLocation::new) - .collect(Collectors.toList()) - ); - } - - @GET - @Path("/jail/{name}") - @Permission({ "jail", "one" }) - @ApiOperation(value = "Get a jail", notes = "Get detailed information about a jail.") - public CachedNamedLocation getJail(@PathParam("name") String name) - throws NotFoundException { - Optional optSrv = NucleusAPI.getJailService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues jail service not available"); - } - - NucleusJailService srv = optSrv.get(); - - return WebAPI.runOnMain(() -> { - Optional optJail = srv.getJail(name); - if (!optJail.isPresent()) { - throw new NotFoundException("Jail with name " + name + " not found"); - } - - return new CachedNamedLocation(optJail.get()); - }); - } - - @POST - @Path("/jail") - @Permission({ "jail", "create" }) - @ApiOperation(value = "Create a jail", response = CachedNamedLocation.class, notes = "Creates a new jail.") - public Response createJail(CachedNamedLocation req) - throws BadRequestException, URISyntaxException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - Optional optSrv = NucleusAPI.getJailService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues jail service not available"); - } - - NucleusJailService srv = optSrv.get(); - - if (req.getLocation() == null) { - throw new BadRequestException("A location is required"); - } - - CachedNamedLocation jail = WebAPI.runOnMain(() -> { - Optional optLive = req.getLocation().getLive(); - if (!optLive.isPresent()) { - throw new InternalServerErrorException("Could not get live location"); - } - Vector3d rot = req.getRotation() == null ? Vector3d.FORWARD : req.getRotation(); - srv.setJail(req.getName(), optLive.get(), rot); - Optional optJail = srv.getJail(req.getName()); - if (!optJail.isPresent()) { - throw new InternalServerErrorException("Could not get jail after creating it"); - } - return new CachedNamedLocation(optJail.get()); - }); - - return Response.created(new URI(null, null, jail.getLink(), null)).entity(jail).build(); - } - - @PUT - @Path("/jail/{name}") - @Permission({ "jail", "modify" }) - @ApiOperation(value = "Modify a jail", notes = "Modify an existing jail.") - public CachedNamedLocation modifyJail() - throws NotImplementedException { - throw new NotImplementedException(); - } - - @DELETE - @Path("/jail/{name}") - @Permission({ "jail", "delete" }) - @ApiOperation(value = "Delete a jail", notes = "Delete an existing jail.") - public CachedNamedLocation deleteJail(@PathParam("name") String name) - throws NotFoundException { - Optional optSrv = NucleusAPI.getJailService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues jail service not available"); - } - - NucleusJailService srv = optSrv.get(); - - return WebAPI.runOnMain(() -> { - Optional optJail = srv.getJail(name); - if (!optJail.isPresent()) { - throw new NotFoundException("Jail with name " + name + " not found"); - } - - srv.removeJail(name); - - return new CachedNamedLocation(optJail.get()); - }); - } - - - // Kits - @GET - @Path("/kit") - @Permission({ "kit", "list" }) - @ApiOperation(value = "List kits", notes = "Get a list of all the kits on the server.") - public Collection listKits() { - Optional optSrv = NucleusAPI.getKitService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues kit service not available"); - } - - NucleusKitService srv = optSrv.get(); - - return WebAPI.runOnMain( - () -> srv.getKitNames().stream() - .map(name -> srv.getKit(name).map(CachedKit::new).orElse(null)) - .collect(Collectors.toList()) - ); - } - - @GET - @Path("/kit/{name}") - @Permission({ "kit", "one" }) - @ApiOperation(value = "Get a kit", notes = "Get detailed information about a kit.") - public CachedKit getKit(@PathParam("name") String name) - throws NotFoundException { - Optional optSrv = NucleusAPI.getKitService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues kit service not available"); - } - - NucleusKitService srv = optSrv.get(); - - return WebAPI.runOnMain(() -> { - Optional optKit = srv.getKit(name); - if (!optKit.isPresent()) { - throw new NotFoundException("Kit with name " + name + " not found"); - } - - return new CachedKit(optKit.get()); - }); - } - - @POST - @Path("/kit") - @Permission({ "kit", "create" }) - @ApiOperation(value = "Create a kit", response = CachedKit.class, notes = "Creates a new kit.") - public Response createKit(CachedKit req) - throws BadRequestException, URISyntaxException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - Optional optSrv = NucleusAPI.getKitService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues kit service not available"); - } - - NucleusKitService srv = optSrv.get(); - - if (req.getName().isEmpty()) { - throw new BadRequestException("Invalid kit name"); - } - - CachedKit resKit = WebAPI.runOnMain(() -> { - Kit kit = srv.createKit(req.getName()); - kit.setCost(req.getCost()); - kit.setCooldown(Duration.ofMillis(req.getCooldown())); - if (req.getStacks() != null) { - try { - kit.setStacks(req.getStacks()); - } catch (Exception e) { - throw new BadRequestException("Could not process item stack: " + e.getMessage()); - } - } - if (req.getCommands() != null) { - kit.setCommands(req.getCommands()); - } - srv.saveKit(kit); - return new CachedKit(kit); - }); - - return Response.created(new URI(null, null, resKit.getLink(), null)).entity(resKit).build(); - } - - @PUT - @Path("/kit/{name}") - @Permission({ "kit", "modify" }) - @ApiOperation(value = "Modify a kit", notes = "Modify an existing kit.") - public CachedKit modifyKit(@PathParam("name") String name, CachedKit req) - throws NotFoundException, BadRequestException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - Optional optSrv = NucleusAPI.getKitService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues kit service not available"); - } - - NucleusKitService srv = optSrv.get(); - - return WebAPI.runOnMain(() -> { - Optional optKit = srv.getKit(name); - if (!optKit.isPresent()) { - throw new NotFoundException("Kit with name " + name + " not found"); - } - - Kit kit = optKit.get(); - if (req.getCost() != null) { - kit.setCost(req.getCost()); - } - if (req.getCooldown() != null) { - kit.setCooldown(Duration.ofMillis(req.getCooldown())); - } - if (req.getCommands() != null) { - kit.setCommands(req.getCommands()); - } - if (req.getStacks() != null) { - try { - kit.setStacks(req.getStacks()); - } catch (Exception e) { - throw new BadRequestException("Could not process item stack: " + e.getMessage()); - } - } - - srv.saveKit(kit); - - return new CachedKit(kit); - }); - } - - @DELETE - @Path("/kit/{name}") - @Permission({ "kit", "delete" }) - @ApiOperation(value = "Delete a kit", notes = "Delete an existing kit.") - public CachedKit deleteKit(@PathParam("name") String name) - throws NotFoundException { - Optional optSrv = NucleusAPI.getKitService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues kit service not available"); - } - - NucleusKitService srv = optSrv.get(); - - return WebAPI.runOnMain(() -> { - Optional optKit = srv.getKit(name); - if (!optKit.isPresent()) { - throw new NotFoundException("Kit with name " + name + " not found"); - } - - srv.removeKit(name); - return new CachedKit(optKit.get()); - }); - } - - - // Home - @GET - @Path("/home/{player}") - @Permission({ "home", "list" }) - @ApiOperation(value = "List homes", notes = "Get a list of all the homes of a player.") - public Collection listHomes( - @PathParam("player") @ApiParam("The uuid of the player") CachedPlayer player) - throws NotFoundException { - - Optional optSrv = NucleusAPI.getHomeService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues home service not available"); - } - - NucleusHomeService srv = optSrv.get(); - - return WebAPI.runOnMain( - () -> srv.getHomes(player.getUUID()).stream() - .map(CachedNamedLocation::new) - .collect(Collectors.toList()) - ); - } - - - // Mail - @GET - @Path("/mail/{player}") - @Permission({ "mail", "list" }) - @ApiOperation(value = "List mail", notes = "Get a list of all mail messages of a player.") - public Collection listMail( - @PathParam("player") @ApiParam("The uuid of the player") CachedPlayer player) - throws NotFoundException { - - Optional optSrv = NucleusAPI.getMailService(); - if (!optSrv.isPresent()) { - throw new InternalServerErrorException("Nuclues mail service not available"); - } - - NucleusMailService srv = optSrv.get(); - - Optional optUser = player.getUser(); - if (!optUser.isPresent()) { - throw new InternalServerErrorException("Could not get user"); - } - - return WebAPI.runOnMain( - () -> srv.getMail(optUser.get(), mailMessage -> { return true; }).stream() - .map(CachedMailMessage::new) - .collect(Collectors.toList()) - ); - } - - - // Modules - @GET - @Path("/module") - @Permission({ "module", "list" }) - @ApiOperation(value = "List modules", notes = "Get a list of loaded Nucleus modules.") - public Collection listMail() { - - NucleusModuleService srv = NucleusAPI.getModuleService(); - return WebAPI.runOnMain(srv::getModulesToLoad); - } -} +package valandur.webapi.integration.nucleus; + +import com.flowpowered.math.vector.Vector3d; +import io.github.nucleuspowered.nucleus.api.NucleusAPI; +import io.github.nucleuspowered.nucleus.api.nucleusdata.Kit; +import io.github.nucleuspowered.nucleus.api.nucleusdata.MailMessage; +import io.github.nucleuspowered.nucleus.api.nucleusdata.NamedLocation; +import io.github.nucleuspowered.nucleus.api.service.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.world.Location; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.player.CachedPlayer; +import valandur.webapi.exceptions.NotImplementedException; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Duration; +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; + +@Path("nucleus") +@Api(tags = { "Nucleus" }, value = "Manage your kits and jails") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class NucleusServlet extends BaseServlet { + + public static void onRegister() { + SerializeService srv = WebAPI.getSerializeService(); + srv.registerCache(NamedLocation.class, CachedNamedLocation.class); + srv.registerCache(MailMessage.class, CachedMailMessage.class); + srv.registerCache(Kit.class, CachedKit.class); + } + + + // Jails + @GET + @Path("/jail") + @Permission({ "jail", "list" }) + @ApiOperation(value = "List jails", notes = "Get a list of all the jails on the server.") + public Collection listJails() { + Optional optSrv = NucleusAPI.getJailService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues jail service not available"); + } + + NucleusJailService srv = optSrv.get(); + + return WebAPI.runOnMain( + () -> srv.getJails().values().stream() + .map(CachedNamedLocation::new) + .collect(Collectors.toList()) + ); + } + + @GET + @Path("/jail/{name}") + @Permission({ "jail", "one" }) + @ApiOperation(value = "Get a jail", notes = "Get detailed information about a jail.") + public CachedNamedLocation getJail(@PathParam("name") String name) + throws NotFoundException { + Optional optSrv = NucleusAPI.getJailService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues jail service not available"); + } + + NucleusJailService srv = optSrv.get(); + + return WebAPI.runOnMain(() -> { + Optional optJail = srv.getJail(name); + if (!optJail.isPresent()) { + throw new NotFoundException("Jail with name " + name + " not found"); + } + + return new CachedNamedLocation(optJail.get()); + }); + } + + @POST + @Path("/jail") + @Permission({ "jail", "create" }) + @ApiOperation(value = "Create a jail", response = CachedNamedLocation.class, notes = "Creates a new jail.") + public Response createJail(CachedNamedLocation req) + throws BadRequestException, URISyntaxException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + Optional optSrv = NucleusAPI.getJailService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues jail service not available"); + } + + NucleusJailService srv = optSrv.get(); + + if (req.getLocation() == null) { + throw new BadRequestException("A location is required"); + } + + CachedNamedLocation jail = WebAPI.runOnMain(() -> { + Optional optLive = req.getLocation().getLive(); + if (!optLive.isPresent()) { + throw new InternalServerErrorException("Could not get live location"); + } + Vector3d rot = req.getRotation() == null ? Vector3d.FORWARD : req.getRotation(); + srv.setJail(req.getName(), optLive.get(), rot); + Optional optJail = srv.getJail(req.getName()); + if (!optJail.isPresent()) { + throw new InternalServerErrorException("Could not get jail after creating it"); + } + return new CachedNamedLocation(optJail.get()); + }); + + return Response.created(new URI(null, null, jail.getLink(), null)).entity(jail).build(); + } + + @PUT + @Path("/jail/{name}") + @Permission({ "jail", "modify" }) + @ApiOperation(value = "Modify a jail", notes = "Modify an existing jail.") + public CachedNamedLocation modifyJail() + throws NotImplementedException { + throw new NotImplementedException(); + } + + @DELETE + @Path("/jail/{name}") + @Permission({ "jail", "delete" }) + @ApiOperation(value = "Delete a jail", notes = "Delete an existing jail.") + public CachedNamedLocation deleteJail(@PathParam("name") String name) + throws NotFoundException { + Optional optSrv = NucleusAPI.getJailService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues jail service not available"); + } + + NucleusJailService srv = optSrv.get(); + + return WebAPI.runOnMain(() -> { + Optional optJail = srv.getJail(name); + if (!optJail.isPresent()) { + throw new NotFoundException("Jail with name " + name + " not found"); + } + + srv.removeJail(name); + + return new CachedNamedLocation(optJail.get()); + }); + } + + + // Kits + @GET + @Path("/kit") + @Permission({ "kit", "list" }) + @ApiOperation(value = "List kits", notes = "Get a list of all the kits on the server.") + public Collection listKits() { + Optional optSrv = NucleusAPI.getKitService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues kit service not available"); + } + + NucleusKitService srv = optSrv.get(); + + return WebAPI.runOnMain( + () -> srv.getKitNames().stream() + .map(name -> srv.getKit(name).map(CachedKit::new).orElse(null)) + .collect(Collectors.toList()) + ); + } + + @GET + @Path("/kit/{name}") + @Permission({ "kit", "one" }) + @ApiOperation(value = "Get a kit", notes = "Get detailed information about a kit.") + public CachedKit getKit(@PathParam("name") String name) + throws NotFoundException { + Optional optSrv = NucleusAPI.getKitService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues kit service not available"); + } + + NucleusKitService srv = optSrv.get(); + + return WebAPI.runOnMain(() -> { + Optional optKit = srv.getKit(name); + if (!optKit.isPresent()) { + throw new NotFoundException("Kit with name " + name + " not found"); + } + + return new CachedKit(optKit.get()); + }); + } + + @POST + @Path("/kit") + @Permission({ "kit", "create" }) + @ApiOperation(value = "Create a kit", response = CachedKit.class, notes = "Creates a new kit.") + public Response createKit(CachedKit req) + throws BadRequestException, URISyntaxException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + Optional optSrv = NucleusAPI.getKitService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues kit service not available"); + } + + NucleusKitService srv = optSrv.get(); + + if (req.getName().isEmpty()) { + throw new BadRequestException("Invalid kit name"); + } + + CachedKit resKit = WebAPI.runOnMain(() -> { + Kit kit = srv.createKit(req.getName()); + kit.setCost(req.getCost()); + kit.setCooldown(Duration.ofMillis(req.getCooldown())); + if (req.getStacks() != null) { + try { + kit.setStacks(req.getStacks()); + } catch (Exception e) { + throw new BadRequestException("Could not process item stack: " + e.getMessage()); + } + } + if (req.getCommands() != null) { + kit.setCommands(req.getCommands()); + } + srv.saveKit(kit); + return new CachedKit(kit); + }); + + return Response.created(new URI(null, null, resKit.getLink(), null)).entity(resKit).build(); + } + + @PUT + @Path("/kit/{name}") + @Permission({ "kit", "modify" }) + @ApiOperation(value = "Modify a kit", notes = "Modify an existing kit.") + public CachedKit modifyKit(@PathParam("name") String name, CachedKit req) + throws NotFoundException, BadRequestException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + Optional optSrv = NucleusAPI.getKitService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues kit service not available"); + } + + NucleusKitService srv = optSrv.get(); + + return WebAPI.runOnMain(() -> { + Optional optKit = srv.getKit(name); + if (!optKit.isPresent()) { + throw new NotFoundException("Kit with name " + name + " not found"); + } + + Kit kit = optKit.get(); + if (req.getCost() != null) { + kit.setCost(req.getCost()); + } + if (req.getCooldown() != null) { + kit.setCooldown(Duration.ofMillis(req.getCooldown())); + } + if (req.getCommands() != null) { + kit.setCommands(req.getCommands()); + } + if (req.getStacks() != null) { + try { + kit.setStacks(req.getStacks()); + } catch (Exception e) { + throw new BadRequestException("Could not process item stack: " + e.getMessage()); + } + } + + srv.saveKit(kit); + + return new CachedKit(kit); + }); + } + + @DELETE + @Path("/kit/{name}") + @Permission({ "kit", "delete" }) + @ApiOperation(value = "Delete a kit", notes = "Delete an existing kit.") + public CachedKit deleteKit(@PathParam("name") String name) + throws NotFoundException { + Optional optSrv = NucleusAPI.getKitService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues kit service not available"); + } + + NucleusKitService srv = optSrv.get(); + + return WebAPI.runOnMain(() -> { + Optional optKit = srv.getKit(name); + if (!optKit.isPresent()) { + throw new NotFoundException("Kit with name " + name + " not found"); + } + + srv.removeKit(name); + return new CachedKit(optKit.get()); + }); + } + + + // Home + @GET + @Path("/home/{player}") + @Permission({ "home", "list" }) + @ApiOperation(value = "List homes", notes = "Get a list of all the homes of a player.") + public Collection listHomes( + @PathParam("player") @ApiParam("The uuid of the player") CachedPlayer player) + throws NotFoundException { + + Optional optSrv = NucleusAPI.getHomeService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues home service not available"); + } + + NucleusHomeService srv = optSrv.get(); + + return WebAPI.runOnMain( + () -> srv.getHomes(player.getUUID()).stream() + .map(CachedNamedLocation::new) + .collect(Collectors.toList()) + ); + } + + + // Mail + @GET + @Path("/mail/{player}") + @Permission({ "mail", "list" }) + @ApiOperation(value = "List mail", notes = "Get a list of all mail messages of a player.") + public Collection listMail( + @PathParam("player") @ApiParam("The uuid of the player") CachedPlayer player) + throws NotFoundException { + + Optional optSrv = NucleusAPI.getMailService(); + if (!optSrv.isPresent()) { + throw new InternalServerErrorException("Nuclues mail service not available"); + } + + NucleusMailService srv = optSrv.get(); + + Optional optUser = player.getUser(); + if (!optUser.isPresent()) { + throw new InternalServerErrorException("Could not get user"); + } + + return WebAPI.runOnMain( + () -> srv.getMail(optUser.get(), mailMessage -> { return true; }).stream() + .map(CachedMailMessage::new) + .collect(Collectors.toList()) + ); + } + + + // Modules + @GET + @Path("/module") + @Permission({ "module", "list" }) + @ApiOperation(value = "List modules", notes = "Get a list of loaded Nucleus modules.") + public Collection listMail() { + + NucleusModuleService srv = NucleusAPI.getModuleService(); + return WebAPI.runOnMain(srv::getModulesToLoad); + } +} diff --git a/src/main/java/valandur/webapi/integration/redprotect/CachedRegion.java b/webapi-sponge/src/main/java/valandur/webapi/integration/redprotect/CachedRegion.java similarity index 97% rename from src/main/java/valandur/webapi/integration/redprotect/CachedRegion.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/redprotect/CachedRegion.java index 1aa4d1f2..376a2ac1 100644 --- a/src/main/java/valandur/webapi/integration/redprotect/CachedRegion.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/redprotect/CachedRegion.java @@ -1,159 +1,159 @@ -package valandur.webapi.integration.redprotect; - -import br.net.fabiozumbi12.RedProtect.Sponge.Region; -import com.flowpowered.math.vector.Vector3d; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.cache.player.CachedPlayer; -import valandur.webapi.cache.world.CachedLocation; -import valandur.webapi.cache.world.CachedWorld; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.util.Constants; - -import java.util.*; - -@ApiModel("RedProtectRegion") -public class CachedRegion extends CachedObject { - - private String id; - @ApiModelProperty(value = "The unique id of this region", required = true) - public String getId() { - return id; - } - - private String name; - @ApiModelProperty(value = "The name of this region", required = true) - public String getName() { - return name; - } - - private CachedWorld world; - @JsonDetails(value = false, simple = true) - @ApiModelProperty(value = "The world this region is located in", required = true) - public CachedWorld getWorld() { - return world; - } - - private Vector3d min; - @ApiModelProperty(value = "The minimum coordinates that define the region", required = true) - public Vector3d getMin() { - return min; - } - - private Vector3d max; - @ApiModelProperty(value = "The maximum coordinates that define the region", required = true) - public Vector3d getMax() { - return max; - } - - private Integer priority; - @JsonDetails - @ApiModelProperty("The priority of this region compared to other regions") - public Integer getPriority() { - return priority; - } - - private Boolean canDelete; - @JsonDetails - @ApiModelProperty("True if this region can be deleted, false otherwise") - public Boolean getCanDelete() { - return canDelete; - } - - private List leaders; - @JsonDetails(simple = true) - @ApiModelProperty("A list of players that are leaders of this region") - public List getLeaders() { - return leaders; - } - - private List admins; - @JsonDetails(simple = true) - @ApiModelProperty("A list of players that are admins of this region") - public List getAdmins() { - return admins; - } - - private List members; - @JsonDetails(simple = true) - @ApiModelProperty("A list of players that are members of this region") - public List getMembers() { - return members; - } - - private String welcomeMessage; - @JsonDetails - @ApiModelProperty("The welcome message displayed to a player when they enter this region") - public String getWelcomeMessage() { - return welcomeMessage; - } - - private String date; - @JsonDetails - @ApiModelProperty("The date this region was created?") - public String getDate() { - return date; - } - - private HashMap flags; - @JsonDetails - @ApiModelProperty("A map of flags applicable to this region") - public HashMap getFlags() { - return flags; - } - - private CachedLocation tpPoint; - @JsonDetails - @ApiModelProperty("The teleport point for this region") - public CachedLocation getTpPoint() { - return tpPoint; - } - - - public CachedRegion() { - super(null); - } - public CachedRegion(Region region) { - super(region); - - this.id = region.getID(); - this.name = region.getName(); - this.world = cacheService.getWorld(region.getWorld()).orElse(null); - this.min = new Vector3d(region.getMinMbrX(), region.getMinY(), region.getMinMbrZ()); - this.max = new Vector3d(region.getMaxMbrX(), region.getMaxY(), region.getMaxMbrZ()); - this.priority = region.getPrior(); - this.welcomeMessage = region.getWelcome(); - this.date = region.getDate(); - this.canDelete = region.canDelete(); - this.tpPoint = region.getTPPoint() != null ? new CachedLocation(region.getTPPoint()) : null; - - this.leaders = new ArrayList<>(); - for (String uuid : region.getLeaders()) { - Optional optPlayer = cacheService.getPlayer(uuid); - optPlayer.ifPresent(player -> this.leaders.add(player)); - } - - this.admins = new ArrayList<>(); - for (String uuid : region.getAdmins()) { - Optional optPlayer = cacheService.getPlayer(uuid); - optPlayer.ifPresent(player -> this.admins.add(player)); - } - - this.members = new ArrayList<>(); - for (String uuid : region.getLeaders()) { - Optional optPlayer = cacheService.getPlayer(uuid); - optPlayer.ifPresent(player -> this.members.add(player)); - } - - this.flags = new HashMap<>(region.getFlags().size()); - for (Map.Entry entry : region.getFlags().entrySet()) { - this.flags.put(entry.getKey(), cacheService.asCachedObject(entry.getValue())); - } - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/red-protect/region/" + id; - } -} +package valandur.webapi.integration.redprotect; + +import br.net.fabiozumbi12.RedProtect.Sponge.Region; +import com.flowpowered.math.vector.Vector3d; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.cache.player.CachedPlayer; +import valandur.webapi.cache.world.CachedLocation; +import valandur.webapi.cache.world.CachedWorld; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.util.Constants; + +import java.util.*; + +@ApiModel("RedProtectRegion") +public class CachedRegion extends CachedObject { + + private String id; + @ApiModelProperty(value = "The unique id of this region", required = true) + public String getId() { + return id; + } + + private String name; + @ApiModelProperty(value = "The name of this region", required = true) + public String getName() { + return name; + } + + private CachedWorld world; + @JsonDetails(value = false, simple = true) + @ApiModelProperty(value = "The world this region is located in", required = true) + public CachedWorld getWorld() { + return world; + } + + private Vector3d min; + @ApiModelProperty(value = "The minimum coordinates that define the region", required = true) + public Vector3d getMin() { + return min; + } + + private Vector3d max; + @ApiModelProperty(value = "The maximum coordinates that define the region", required = true) + public Vector3d getMax() { + return max; + } + + private Integer priority; + @JsonDetails + @ApiModelProperty("The priority of this region compared to other regions") + public Integer getPriority() { + return priority; + } + + private Boolean canDelete; + @JsonDetails + @ApiModelProperty("True if this region can be deleted, false otherwise") + public Boolean getCanDelete() { + return canDelete; + } + + private List leaders; + @JsonDetails(simple = true) + @ApiModelProperty("A list of players that are leaders of this region") + public List getLeaders() { + return leaders; + } + + private List admins; + @JsonDetails(simple = true) + @ApiModelProperty("A list of players that are admins of this region") + public List getAdmins() { + return admins; + } + + private List members; + @JsonDetails(simple = true) + @ApiModelProperty("A list of players that are members of this region") + public List getMembers() { + return members; + } + + private String welcomeMessage; + @JsonDetails + @ApiModelProperty("The welcome message displayed to a player when they enter this region") + public String getWelcomeMessage() { + return welcomeMessage; + } + + private String date; + @JsonDetails + @ApiModelProperty("The date this region was created?") + public String getDate() { + return date; + } + + private HashMap flags; + @JsonDetails + @ApiModelProperty("A map of flags applicable to this region") + public HashMap getFlags() { + return flags; + } + + private CachedLocation tpPoint; + @JsonDetails + @ApiModelProperty("The teleport point for this region") + public CachedLocation getTpPoint() { + return tpPoint; + } + + + public CachedRegion() { + super(null); + } + public CachedRegion(Region region) { + super(region); + + this.id = region.getID(); + this.name = region.getName(); + this.world = cacheService.getWorld(region.getWorld()).orElse(null); + this.min = new Vector3d(region.getMinMbrX(), region.getMinY(), region.getMinMbrZ()); + this.max = new Vector3d(region.getMaxMbrX(), region.getMaxY(), region.getMaxMbrZ()); + this.priority = region.getPrior(); + this.welcomeMessage = region.getWelcome(); + this.date = region.getDate(); + this.canDelete = region.canDelete(); + this.tpPoint = region.getTPPoint() != null ? new CachedLocation(region.getTPPoint()) : null; + + this.leaders = new ArrayList<>(); + for (String uuid : region.getLeaders()) { + Optional optPlayer = cacheService.getPlayer(uuid); + optPlayer.ifPresent(player -> this.leaders.add(player)); + } + + this.admins = new ArrayList<>(); + for (String uuid : region.getAdmins()) { + Optional optPlayer = cacheService.getPlayer(uuid); + optPlayer.ifPresent(player -> this.admins.add(player)); + } + + this.members = new ArrayList<>(); + for (String uuid : region.getLeaders()) { + Optional optPlayer = cacheService.getPlayer(uuid); + optPlayer.ifPresent(player -> this.members.add(player)); + } + + this.flags = new HashMap<>(region.getFlags().size()); + for (Map.Entry entry : region.getFlags().entrySet()) { + this.flags.put(entry.getKey(), cacheService.asCachedObject(entry.getValue())); + } + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/red-protect/region/" + id; + } +} diff --git a/src/main/java/valandur/webapi/integration/redprotect/RedProtectServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/redprotect/RedProtectServlet.java similarity index 97% rename from src/main/java/valandur/webapi/integration/redprotect/RedProtectServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/redprotect/RedProtectServlet.java index b090f941..c2f2e7ed 100644 --- a/src/main/java/valandur/webapi/integration/redprotect/RedProtectServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/redprotect/RedProtectServlet.java @@ -1,287 +1,287 @@ -package valandur.webapi.integration.redprotect; - -import br.net.fabiozumbi12.RedProtect.Sponge.RedProtect; -import br.net.fabiozumbi12.RedProtect.Sponge.Region; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.EventContext; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.world.CachedWorld; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.stream.Collectors; - -@Path("red-protect") -@Api(tags = { "Red Protect"}, value = "Create, edit and delete protected regions on your server") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class RedProtectServlet extends BaseServlet { - - public static void onRegister() { - SerializeService srv = WebAPI.getSerializeService(); - srv.registerCache(Region.class, CachedRegion.class); - } - - - @GET - @Path("/region") - @Permission({ "region", "list" }) - @ApiOperation( - value = "List regions", - notes = "Lists all the regions being protected") - public Collection listRegions(@QueryParam("world") CachedWorld world) { - Set regions; - if (world != null) { - regions = WebAPI.runOnMain(() -> { - Optional optLive = world.getLive(); - if (!optLive.isPresent()) { - return null; - } - - World live = optLive.get(); - return RedProtect.get().rm.getRegionsByWorld(live).stream() - .map(CachedRegion::new) - .collect(Collectors.toSet()); - }); - } else { - regions = WebAPI.runOnMain(() -> RedProtect.get().rm.getAllRegions().stream() - .map(CachedRegion::new) - .collect(Collectors.toSet())); - } - - return regions; - } - - @GET - @Path("/region/{id}") - @Permission({ "region", "one" }) - @ApiOperation( - value = "Get a region", - notes = "Get details for a specific protected region") - public CachedRegion getRegion(@PathParam("id") String id) - throws BadRequestException { - if (!id.contains("@")) { - throw new BadRequestException("Invalid region id"); - } - - return WebAPI.runOnMain(() -> new CachedRegion(RedProtect.get().rm.getRegionById(id))); - } - - @POST - @Path("/region") - @Permission({ "region", "create" }) - @ApiOperation( - value = "Create a region", - response = CachedRegion.class, - notes = "Create a new region at a specified location") - public Response createRegion(CachedRegion req) - throws BadRequestException, URISyntaxException { - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - CachedRegion resRegion = WebAPI.runOnMain(() -> { - String name = req.getName(); - if (name == null) { - throw new BadRequestException("The region needs a name"); - } - - if (req.getWorld() == null) { - throw new BadRequestException("The region needs a world"); - } - Optional optLive = req.getWorld().getLive(); - if (!optLive.isPresent()) { - throw new InternalServerErrorException("Could not get live world"); - } - - World world = optLive.get(); - - if (req.getMin() == null) { - throw new BadRequestException("The region needs min coordinates"); - } - Location minLoc = new Location<>(world, req.getMin()); - - if (req.getMax() == null) { - throw new BadRequestException("The region needs max coordinates"); - } - Location maxLoc = new Location<>(world, req.getMax()); - - List leaders; - if (req.getLeaders() == null) { - leaders = new ArrayList<>(); - } else { - leaders = req.getLeaders().stream() - .filter(Objects::nonNull) - .map(p -> p.getUUID().toString()) - .collect(Collectors.toList()); - } - - List admins; - if (req.getAdmins() == null) { - admins = new ArrayList<>(); - } else { - admins = req.getAdmins().stream() - .filter(Objects::nonNull) - .map(p -> p.getUUID().toString()) - .collect(Collectors.toList()); - } - - List members; - if (req.getMembers() == null) { - members = new ArrayList<>(); - } else { - members = req.getMembers().stream() - .filter(Objects::nonNull) - .map(p -> p.getUUID().toString()) - .collect(Collectors.toList()); - } - - HashMap flags = req.getFlags(); - if (flags == null) { - flags = new HashMap<>(); - } - - Boolean canDelete = req.getCanDelete(); - if (canDelete == null) { - canDelete = true; - } - - String msg = req.getWelcomeMessage(); - int priority = req.getPriority() != null ? req.getPriority() : 0; - - if (req.getTpPoint() == null) { - throw new BadRequestException("The region needs a tpPoint"); - } - Optional optLiveTpPoint = req.getTpPoint().getLive(); - if (!optLiveTpPoint.isPresent()) { - throw new InternalServerErrorException("Could not get live world"); - } - - Region region = new Region(name, admins, members, leaders, maxLoc.getBlockX(), minLoc.getBlockX(), - maxLoc.getBlockZ(), minLoc.getBlockZ(), minLoc.getBlockY(), maxLoc.getBlockY(), flags, msg, - priority, world.getName(), null, 0, optLiveTpPoint.get(), canDelete); - RedProtect.get().rm.add(region, world); - return new CachedRegion(region); - }); - - return Response.created(new URI(null, null, resRegion.getLink(), null)).entity(resRegion).build(); - } - - @PUT - @Path("/region/{id}") - @Permission({ "region", "modify" }) - @ApiOperation( - value = "Modify a region", - notes = "Update the details for a specific protected region") - public CachedRegion modifyRegion(@PathParam("id") String id, CachedRegion req) - throws BadRequestException { - if (!id.contains("@")) { - throw new BadRequestException("Invalid region id"); - } - - if (req == null) { - throw new BadRequestException("Request body is required"); - } - - return WebAPI.runOnMain(() -> { - Region region = RedProtect.get().rm.getRegionById(id); - if (region == null) { - throw new BadRequestException("Could not find region with id " + id); - } - - if (req.getLeaders() != null) { - region.setLeaders(req.getLeaders().stream() - .filter(Objects::nonNull) - .map(p -> p.getUUID().toString()) - .collect(Collectors.toList())); - } - - if (req.getAdmins() != null) { - region.setAdmins(req.getAdmins().stream() - .filter(Objects::nonNull) - .map(p -> p.getUUID().toString()) - .collect(Collectors.toList())); - } - - if (req.getMembers() != null) { - region.setMembers(req.getMembers().stream() - .filter(Objects::nonNull) - .map(p -> p.getUUID().toString()) - .collect(Collectors.toList())); - } - - if (req.getPriority() != null) { - region.setPrior(req.getPriority()); - } - - if (req.getWelcomeMessage() != null) { - region.setWelcome(req.getWelcomeMessage()); - } - - if (req.getFlags() != null) { - EventContext ctx = EventContext.builder().build(); - Cause cause = Cause.builder().append(WebAPI.getInstance()).build(ctx); - for (Map.Entry entry : req.getFlags().entrySet()) { - region.setFlag(cause, entry.getKey(), entry.getValue()); - } - } - - if (req.getWorld() != null) { - region.setWorld(req.getWorld().getName()); - } - - if (req.getTpPoint() != null) { - Optional optLoc = req.getTpPoint().getLive(); - if (!optLoc.isPresent()) { - return null; - } - - region.setTPPoint(optLoc.get()); - } - - if (req.getCanDelete() != null) { - region.setCanDelete(req.getCanDelete()); - } - - return new CachedRegion(region); - }); - } - - @DELETE - @Path("/region/{id}") - @Permission({ "region", "delete" }) - @ApiOperation( - value = "Delete a region", - notes = "Remove the specified protected region") - public CachedRegion deleteRegion(@PathParam("id") String id) - throws NotFoundException, BadRequestException { - if (!id.contains("@")) { - throw new BadRequestException("Invalid region id"); - } - - return WebAPI.runOnMain(() -> { - Region region = RedProtect.get().rm.getRegionById(id); - if (region == null) { - throw new NotFoundException("Could not find region with id " + id); - } - - World world = Sponge.getServer().getWorld(region.getWorld()).orElse(null); - RedProtect.get().rm.remove(region, world); - - return new CachedRegion(region); - }); - } -} +package valandur.webapi.integration.redprotect; + +import br.net.fabiozumbi12.RedProtect.Sponge.RedProtect; +import br.net.fabiozumbi12.RedProtect.Sponge.Region; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.EventContext; +import org.spongepowered.api.world.Location; +import org.spongepowered.api.world.World; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.world.CachedWorld; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import java.util.stream.Collectors; + +@Path("red-protect") +@Api(tags = { "Red Protect"}, value = "Create, edit and delete protected regions on your server") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class RedProtectServlet extends BaseServlet { + + public static void onRegister() { + SerializeService srv = WebAPI.getSerializeService(); + srv.registerCache(Region.class, CachedRegion.class); + } + + + @GET + @Path("/region") + @Permission({ "region", "list" }) + @ApiOperation( + value = "List regions", + notes = "Lists all the regions being protected") + public Collection listRegions(@QueryParam("world") CachedWorld world) { + Set regions; + if (world != null) { + regions = WebAPI.runOnMain(() -> { + Optional optLive = world.getLive(); + if (!optLive.isPresent()) { + return null; + } + + World live = optLive.get(); + return RedProtect.get().rm.getRegionsByWorld(live).stream() + .map(CachedRegion::new) + .collect(Collectors.toSet()); + }); + } else { + regions = WebAPI.runOnMain(() -> RedProtect.get().rm.getAllRegions().stream() + .map(CachedRegion::new) + .collect(Collectors.toSet())); + } + + return regions; + } + + @GET + @Path("/region/{id}") + @Permission({ "region", "one" }) + @ApiOperation( + value = "Get a region", + notes = "Get details for a specific protected region") + public CachedRegion getRegion(@PathParam("id") String id) + throws BadRequestException { + if (!id.contains("@")) { + throw new BadRequestException("Invalid region id"); + } + + return WebAPI.runOnMain(() -> new CachedRegion(RedProtect.get().rm.getRegionById(id))); + } + + @POST + @Path("/region") + @Permission({ "region", "create" }) + @ApiOperation( + value = "Create a region", + response = CachedRegion.class, + notes = "Create a new region at a specified location") + public Response createRegion(CachedRegion req) + throws BadRequestException, URISyntaxException { + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + CachedRegion resRegion = WebAPI.runOnMain(() -> { + String name = req.getName(); + if (name == null) { + throw new BadRequestException("The region needs a name"); + } + + if (req.getWorld() == null) { + throw new BadRequestException("The region needs a world"); + } + Optional optLive = req.getWorld().getLive(); + if (!optLive.isPresent()) { + throw new InternalServerErrorException("Could not get live world"); + } + + World world = optLive.get(); + + if (req.getMin() == null) { + throw new BadRequestException("The region needs min coordinates"); + } + Location minLoc = new Location<>(world, req.getMin()); + + if (req.getMax() == null) { + throw new BadRequestException("The region needs max coordinates"); + } + Location maxLoc = new Location<>(world, req.getMax()); + + List leaders; + if (req.getLeaders() == null) { + leaders = new ArrayList<>(); + } else { + leaders = req.getLeaders().stream() + .filter(Objects::nonNull) + .map(p -> p.getUUID().toString()) + .collect(Collectors.toList()); + } + + List admins; + if (req.getAdmins() == null) { + admins = new ArrayList<>(); + } else { + admins = req.getAdmins().stream() + .filter(Objects::nonNull) + .map(p -> p.getUUID().toString()) + .collect(Collectors.toList()); + } + + List members; + if (req.getMembers() == null) { + members = new ArrayList<>(); + } else { + members = req.getMembers().stream() + .filter(Objects::nonNull) + .map(p -> p.getUUID().toString()) + .collect(Collectors.toList()); + } + + HashMap flags = req.getFlags(); + if (flags == null) { + flags = new HashMap<>(); + } + + Boolean canDelete = req.getCanDelete(); + if (canDelete == null) { + canDelete = true; + } + + String msg = req.getWelcomeMessage(); + int priority = req.getPriority() != null ? req.getPriority() : 0; + + if (req.getTpPoint() == null) { + throw new BadRequestException("The region needs a tpPoint"); + } + Optional optLiveTpPoint = req.getTpPoint().getLive(); + if (!optLiveTpPoint.isPresent()) { + throw new InternalServerErrorException("Could not get live world"); + } + + Region region = new Region(name, admins, members, leaders, maxLoc.getBlockX(), minLoc.getBlockX(), + maxLoc.getBlockZ(), minLoc.getBlockZ(), minLoc.getBlockY(), maxLoc.getBlockY(), flags, msg, + priority, world.getName(), null, 0, optLiveTpPoint.get(), canDelete); + RedProtect.get().rm.add(region, world); + return new CachedRegion(region); + }); + + return Response.created(new URI(null, null, resRegion.getLink(), null)).entity(resRegion).build(); + } + + @PUT + @Path("/region/{id}") + @Permission({ "region", "modify" }) + @ApiOperation( + value = "Modify a region", + notes = "Update the details for a specific protected region") + public CachedRegion modifyRegion(@PathParam("id") String id, CachedRegion req) + throws BadRequestException { + if (!id.contains("@")) { + throw new BadRequestException("Invalid region id"); + } + + if (req == null) { + throw new BadRequestException("Request body is required"); + } + + return WebAPI.runOnMain(() -> { + Region region = RedProtect.get().rm.getRegionById(id); + if (region == null) { + throw new BadRequestException("Could not find region with id " + id); + } + + if (req.getLeaders() != null) { + region.setLeaders(req.getLeaders().stream() + .filter(Objects::nonNull) + .map(p -> p.getUUID().toString()) + .collect(Collectors.toList())); + } + + if (req.getAdmins() != null) { + region.setAdmins(req.getAdmins().stream() + .filter(Objects::nonNull) + .map(p -> p.getUUID().toString()) + .collect(Collectors.toList())); + } + + if (req.getMembers() != null) { + region.setMembers(req.getMembers().stream() + .filter(Objects::nonNull) + .map(p -> p.getUUID().toString()) + .collect(Collectors.toList())); + } + + if (req.getPriority() != null) { + region.setPrior(req.getPriority()); + } + + if (req.getWelcomeMessage() != null) { + region.setWelcome(req.getWelcomeMessage()); + } + + if (req.getFlags() != null) { + EventContext ctx = EventContext.builder().build(); + Cause cause = Cause.builder().append(WebAPI.getInstance()).build(ctx); + for (Map.Entry entry : req.getFlags().entrySet()) { + region.setFlag(cause, entry.getKey(), entry.getValue()); + } + } + + if (req.getWorld() != null) { + region.setWorld(req.getWorld().getName()); + } + + if (req.getTpPoint() != null) { + Optional optLoc = req.getTpPoint().getLive(); + if (!optLoc.isPresent()) { + return null; + } + + region.setTPPoint(optLoc.get()); + } + + if (req.getCanDelete() != null) { + region.setCanDelete(req.getCanDelete()); + } + + return new CachedRegion(region); + }); + } + + @DELETE + @Path("/region/{id}") + @Permission({ "region", "delete" }) + @ApiOperation( + value = "Delete a region", + notes = "Remove the specified protected region") + public CachedRegion deleteRegion(@PathParam("id") String id) + throws NotFoundException, BadRequestException { + if (!id.contains("@")) { + throw new BadRequestException("Invalid region id"); + } + + return WebAPI.runOnMain(() -> { + Region region = RedProtect.get().rm.getRegionById(id); + if (region == null) { + throw new NotFoundException("Could not find region with id " + id); + } + + World world = Sponge.getServer().getWorld(region.getWorld()).orElse(null); + RedProtect.get().rm.remove(region, world); + + return new CachedRegion(region); + }); + } +} diff --git a/src/main/java/valandur/webapi/integration/universalmarket/CachedMarketItem.java b/webapi-sponge/src/main/java/valandur/webapi/integration/universalmarket/CachedMarketItem.java similarity index 96% rename from src/main/java/valandur/webapi/integration/universalmarket/CachedMarketItem.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/universalmarket/CachedMarketItem.java index 2afccd20..013fc31f 100644 --- a/src/main/java/valandur/webapi/integration/universalmarket/CachedMarketItem.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/universalmarket/CachedMarketItem.java @@ -1,60 +1,60 @@ -package valandur.webapi.integration.universalmarket; - -import com.xwaffle.universalmarket.market.MarketItem; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.item.inventory.ItemStack; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.cache.player.CachedPlayer; -import valandur.webapi.util.Constants; - -@ApiModel("UniversalMarketItem") -public class CachedMarketItem extends CachedObject { - - private ItemStack display; - @ApiModelProperty(value = "The ItemStack displayed to the users", required = true) - public ItemStack getDisplay() { - return display; - } - - private ItemStack item; - @ApiModelProperty(value = "The ItemStack that is being sold", required = true) - public ItemStack getItem() { - return item; - } - - private long expires; - @ApiModelProperty(value = "The unix timestamp (in seconds) at which this offer will expire", required = true) - public long getExpires() { - return expires; - } - - private double price; - @ApiModelProperty(value = "The price this item is being sold for", required = true) - public double getPrice() { - return price; - } - - private CachedPlayer owner; - @ApiModelProperty(value = "The owner that submitted this offer", required = true) - public CachedPlayer getOwner() { - return owner; - } - - - public CachedMarketItem(MarketItem value) { - super(value); - - this.display = value.getDisplay().copy(); - this.item = value.getItem().copy(); - this.expires = value.getExpireTime() / 1000; - this.price = value.getPrice(); - this.owner = WebAPI.getCacheService().getPlayer(value.getOwnerUUID()).orElse(null); - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/universal-market/item/" + item.getType().getId(); - } -} +package valandur.webapi.integration.universalmarket; + +import com.xwaffle.universalmarket.market.MarketItem; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.item.inventory.ItemStack; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.cache.player.CachedPlayer; +import valandur.webapi.util.Constants; + +@ApiModel("UniversalMarketItem") +public class CachedMarketItem extends CachedObject { + + private ItemStack display; + @ApiModelProperty(value = "The ItemStack displayed to the users", required = true) + public ItemStack getDisplay() { + return display; + } + + private ItemStack item; + @ApiModelProperty(value = "The ItemStack that is being sold", required = true) + public ItemStack getItem() { + return item; + } + + private long expires; + @ApiModelProperty(value = "The unix timestamp (in seconds) at which this offer will expire", required = true) + public long getExpires() { + return expires; + } + + private double price; + @ApiModelProperty(value = "The price this item is being sold for", required = true) + public double getPrice() { + return price; + } + + private CachedPlayer owner; + @ApiModelProperty(value = "The owner that submitted this offer", required = true) + public CachedPlayer getOwner() { + return owner; + } + + + public CachedMarketItem(MarketItem value) { + super(value); + + this.display = value.getDisplay().copy(); + this.item = value.getItem().copy(); + this.expires = value.getExpireTime() / 1000; + this.price = value.getPrice(); + this.owner = WebAPI.getCacheService().getPlayer(value.getOwnerUUID()).orElse(null); + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/universal-market/item/" + item.getType().getId(); + } +} diff --git a/src/main/java/valandur/webapi/integration/universalmarket/UniversalMarketServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/universalmarket/UniversalMarketServlet.java similarity index 97% rename from src/main/java/valandur/webapi/integration/universalmarket/UniversalMarketServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/universalmarket/UniversalMarketServlet.java index 8e8ae8ee..48eda402 100644 --- a/src/main/java/valandur/webapi/integration/universalmarket/UniversalMarketServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/universalmarket/UniversalMarketServlet.java @@ -1,59 +1,59 @@ -package valandur.webapi.integration.universalmarket; - -import com.xwaffle.universalmarket.UniversalMarket; -import com.xwaffle.universalmarket.market.Market; -import com.xwaffle.universalmarket.market.MarketItem; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.plugin.PluginContainer; -import valandur.webapi.WebAPI; -import valandur.webapi.serialize.SerializeService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import java.util.Collection; -import java.util.Optional; -import java.util.stream.Collectors; - -@Path("universal-market") -@Api(tags = { "Universal Market" }, value = "View the current items on the market") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class UniversalMarketServlet extends BaseServlet { - - public static void onRegister() { - SerializeService srv = WebAPI.getSerializeService(); - srv.registerCache(MarketItem.class, CachedMarketItem.class); - } - - @GET - @Path("/item") - @Permission({ "item", "list" }) - @ApiOperation( - value = "List items", - notes = "Lists all the items in the market currently available for sale") - public Collection listMarketItems() { - return WebAPI.runOnMain(() -> { - UniversalMarket plugin = getUMPlugin(); - Market market = plugin.getMarket(); - return market.getListings().stream().map(CachedMarketItem::new).collect(Collectors.toList()); - }); - } - - private UniversalMarket getUMPlugin() { - Optional optContainer = Sponge.getPluginManager().getPlugin("universalmarket"); - if (!optContainer.isPresent()) { - throw new InternalServerErrorException("UniversalMarket plugin not found"); - } - - Optional optPlugin = optContainer.get().getInstance(); - if (!optPlugin.isPresent()) { - throw new InternalServerErrorException("UniversalMarket plugin instance not found"); - } - - return (UniversalMarket)optPlugin.get(); - } -} +package valandur.webapi.integration.universalmarket; + +import com.xwaffle.universalmarket.UniversalMarket; +import com.xwaffle.universalmarket.market.Market; +import com.xwaffle.universalmarket.market.MarketItem; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.plugin.PluginContainer; +import valandur.webapi.WebAPI; +import valandur.webapi.serialize.SerializeService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; + +@Path("universal-market") +@Api(tags = { "Universal Market" }, value = "View the current items on the market") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class UniversalMarketServlet extends BaseServlet { + + public static void onRegister() { + SerializeService srv = WebAPI.getSerializeService(); + srv.registerCache(MarketItem.class, CachedMarketItem.class); + } + + @GET + @Path("/item") + @Permission({ "item", "list" }) + @ApiOperation( + value = "List items", + notes = "Lists all the items in the market currently available for sale") + public Collection listMarketItems() { + return WebAPI.runOnMain(() -> { + UniversalMarket plugin = getUMPlugin(); + Market market = plugin.getMarket(); + return market.getListings().stream().map(CachedMarketItem::new).collect(Collectors.toList()); + }); + } + + private UniversalMarket getUMPlugin() { + Optional optContainer = Sponge.getPluginManager().getPlugin("universalmarket"); + if (!optContainer.isPresent()) { + throw new InternalServerErrorException("UniversalMarket plugin not found"); + } + + Optional optPlugin = optContainer.get().getInstance(); + if (!optPlugin.isPresent()) { + throw new InternalServerErrorException("UniversalMarket plugin instance not found"); + } + + return (UniversalMarket)optPlugin.get(); + } +} diff --git a/src/main/java/valandur/webapi/integration/villagershops/VShopCompareUtils.java b/webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/VShopCompareUtils.java similarity index 100% rename from src/main/java/valandur/webapi/integration/villagershops/VShopCompareUtils.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/VShopCompareUtils.java diff --git a/src/main/java/valandur/webapi/integration/villagershops/VShopServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/VShopServlet.java similarity index 100% rename from src/main/java/valandur/webapi/integration/villagershops/VShopServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/VShopServlet.java diff --git a/src/main/java/valandur/webapi/integration/villagershops/VShopsConfig.java b/webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/VShopsConfig.java similarity index 100% rename from src/main/java/valandur/webapi/integration/villagershops/VShopsConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/VShopsConfig.java diff --git a/src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedStockItem.java b/webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedStockItem.java similarity index 100% rename from src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedStockItem.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedStockItem.java diff --git a/src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedVShop.java b/webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedVShop.java similarity index 100% rename from src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedVShop.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/villagershops/wrapper/CachedVShop.java diff --git a/src/main/java/valandur/webapi/integration/webbooks/WebBook.java b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBook.java similarity index 96% rename from src/main/java/valandur/webapi/integration/webbooks/WebBook.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBook.java index ba0e3638..dc776778 100644 --- a/src/main/java/valandur/webapi/integration/webbooks/WebBook.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBook.java @@ -1,62 +1,62 @@ -package valandur.webapi.integration.webbooks; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.util.Constants; - -import java.util.List; - -@ConfigSerializable -@ApiModel("WebBooksBook") -public class WebBook { - - @Setting - @JsonProperty(required = true) - private String id; - @ApiModelProperty(value = "The unique id of this book", required = true) - public String getId() { - return id; - } - - private String title; - @ApiModelProperty(value = "The title of this book", required = true) - public String getTitle() { - return title; - } - - private List lines; - @ApiModelProperty(value = "A list of lines that make up this book", required = true) - public List getLines() { - return lines; - } - - - public WebBook() { - } - public WebBook(String id, String title, List lines) { - this.id = id; - this.title = title; - this.lines = lines; - } - - @JsonDetails - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - @ApiModelProperty(value = "The HTML representation of this book", required = true) - public String getHtml() { - StringBuilder html = new StringBuilder("" + title + - "
    "); - for (String line : lines) { - html.append("
  • ").append(line).append("
  • "); - } - return html + "
"; - } - - @ApiModelProperty(value = "The API link that can be used to obtain more information about this object", required = true, readOnly = true) - public String getLink() { - return Constants.BASE_PATH + "/web-books/book/" + id; - } -} +package valandur.webapi.integration.webbooks; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.util.Constants; + +import java.util.List; + +@ConfigSerializable +@ApiModel("WebBooksBook") +public class WebBook { + + @Setting + @JsonProperty(required = true) + private String id; + @ApiModelProperty(value = "The unique id of this book", required = true) + public String getId() { + return id; + } + + private String title; + @ApiModelProperty(value = "The title of this book", required = true) + public String getTitle() { + return title; + } + + private List lines; + @ApiModelProperty(value = "A list of lines that make up this book", required = true) + public List getLines() { + return lines; + } + + + public WebBook() { + } + public WebBook(String id, String title, List lines) { + this.id = id; + this.title = title; + this.lines = lines; + } + + @JsonDetails + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @ApiModelProperty(value = "The HTML representation of this book", required = true) + public String getHtml() { + StringBuilder html = new StringBuilder("" + title + + "
    "); + for (String line : lines) { + html.append("
  • ").append(line).append("
  • "); + } + return html + "
"; + } + + @ApiModelProperty(value = "The API link that can be used to obtain more information about this object", required = true, readOnly = true) + public String getLink() { + return Constants.BASE_PATH + "/web-books/book/" + id; + } +} diff --git a/src/main/java/valandur/webapi/integration/webbooks/WebBookConfigSerializer.java b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBookConfigSerializer.java similarity index 97% rename from src/main/java/valandur/webapi/integration/webbooks/WebBookConfigSerializer.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBookConfigSerializer.java index e2e0a9e8..efbd081f 100644 --- a/src/main/java/valandur/webapi/integration/webbooks/WebBookConfigSerializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBookConfigSerializer.java @@ -1,26 +1,26 @@ -package valandur.webapi.integration.webbooks; - -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; - -import java.util.List; - -public class WebBookConfigSerializer implements TypeSerializer { - - @Override - public WebBook deserialize(TypeToken type, ConfigurationNode value) throws ObjectMappingException { - String id = value.getNode("id").getString(); - String title = value.getNode("title").getString(); - List lines = value.getNode("lines").getList(TypeToken.of(String.class)); - return new WebBook(id, title, lines); - } - - @Override - public void serialize(TypeToken type, WebBook obj, ConfigurationNode value) throws ObjectMappingException { - value.getNode("id").setValue(obj.getId()); - value.getNode("title").setValue(obj.getTitle()); - value.getNode("lines").setValue(obj.getLines()); - } -} +package valandur.webapi.integration.webbooks; + +import com.google.common.reflect.TypeToken; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; + +import java.util.List; + +public class WebBookConfigSerializer implements TypeSerializer { + + @Override + public WebBook deserialize(TypeToken type, ConfigurationNode value) throws ObjectMappingException { + String id = value.getNode("id").getString(); + String title = value.getNode("title").getString(); + List lines = value.getNode("lines").getList(TypeToken.of(String.class)); + return new WebBook(id, title, lines); + } + + @Override + public void serialize(TypeToken type, WebBook obj, ConfigurationNode value) throws ObjectMappingException { + value.getNode("id").setValue(obj.getId()); + value.getNode("title").setValue(obj.getTitle()); + value.getNode("lines").setValue(obj.getLines()); + } +} diff --git a/src/main/java/valandur/webapi/integration/webbooks/WebBooksConfig.java b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBooksConfig.java similarity index 96% rename from src/main/java/valandur/webapi/integration/webbooks/WebBooksConfig.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBooksConfig.java index 09477a16..30471b5b 100644 --- a/src/main/java/valandur/webapi/integration/webbooks/WebBooksConfig.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBooksConfig.java @@ -1,15 +1,15 @@ -package valandur.webapi.integration.webbooks; - -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import valandur.webapi.config.BaseConfig; - -import java.util.HashMap; -import java.util.Map; - -@ConfigSerializable -public class WebBooksConfig extends BaseConfig { - - @Setting(comment = "A map of book ids to books") - public Map books = new HashMap<>(); -} +package valandur.webapi.integration.webbooks; + +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import valandur.webapi.config.BaseConfig; + +import java.util.HashMap; +import java.util.Map; + +@ConfigSerializable +public class WebBooksConfig extends BaseConfig { + + @Setting(comment = "A map of book ids to books") + public Map books = new HashMap<>(); +} diff --git a/src/main/java/valandur/webapi/integration/webbooks/WebBooksServlet.java b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBooksServlet.java similarity index 96% rename from src/main/java/valandur/webapi/integration/webbooks/WebBooksServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBooksServlet.java index 62ddb3f4..e22d925a 100644 --- a/src/main/java/valandur/webapi/integration/webbooks/WebBooksServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/integration/webbooks/WebBooksServlet.java @@ -1,207 +1,207 @@ -package valandur.webapi.integration.webbooks; - -import com.google.common.reflect.TypeToken; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; -import valandur.webapi.WebAPI; -import valandur.webapi.config.BaseConfig; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -@Path("web-books") -@Api( - tags = { "Web Books" }, - value = "Create, edit and delete web books that have unique links which work on your server in-game.") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class WebBooksServlet extends BaseServlet { - - private static final String configFileName = "web-books.conf"; - - private Map books = new ConcurrentHashMap<>(); - - private static WebBooksConfig config; - - - public WebBooksServlet() { - java.nio.file.Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); - config = BaseConfig.load(configPath, new WebBooksConfig()); - books = config.books; - } - - public static void onRegister() { - TypeSerializers.getDefaultSerializers().registerType( - TypeToken.of(WebBook.class), new WebBookConfigSerializer()); - } - - private void saveBooks() { - config.save(); - } - - @GET - @Path("/book") - @Permission({ "book", "list" }) - @ApiOperation( - value = "List books", - notes = "Get a list of all the web books on the server.") - public Collection listWebBooks() { - return books.values(); - } - - @GET - @Path("/book/{id}") - @Permission({ "book", "one" }) - @ApiOperation( - value = "Get a book", - notes = "Get detailed information about a web book.") - public WebBook getWebBook(@PathParam("id") String id) - throws NotFoundException { - WebBook book = books.get(id); - if (book == null) { - throw new NotFoundException("Book with id " + id + " not found"); - } - - return book; - } - - @GET - @Path("/book/{id}/html") - @ApiOperation( - value = "Book HTML", - notes = "Get the web book content as HTML.") - @Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces(MediaType.TEXT_HTML) - public String getWebBookContent(@PathParam("id") String id) - throws NotFoundException { - WebBook book = books.get(id); - if (book == null) { - throw new NotFoundException("Book with id " + id + " not found"); - } - - return book.getHtml(); - } - - @POST - @Path("/book/{id}/html") - @ApiOperation( - value = "Book HTML", - notes = "Get the web book content as HTML.") - @Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces(MediaType.TEXT_HTML) - public String getWebBookContentPost(@PathParam("id") String id) - throws NotFoundException { - WebBook book = books.get(id); - if (book == null) { - throw new NotFoundException("Book with id " + id + " not found"); - } - - return book.getHtml(); - } - - @POST - @Path("/book") - @Permission({ "book", "create" }) - @ApiOperation( - value = "Create a book", - response = WebBook.class, - notes = "Create a new web book from the specified data.") - public Response createWebBook(WebBook book) - throws BadRequestException, URISyntaxException { - - if (book == null) { - throw new BadRequestException("Request body is required"); - } - - String id = book.getId(); - if (id == null || id.isEmpty()) { - throw new BadRequestException("The book needs an id"); - } - - if (books.containsKey(id)) { - throw new BadRequestException("A book with this id already exists"); - } - - String title = ""; - if (book.getTitle() != null) - title = book.getTitle(); - - List lines = new ArrayList<>(); - if (book.getLines() != null) { - lines = book.getLines(); - } - - WebBook newBook = new WebBook(id, title, lines); - - books.put(id, book); - saveBooks(); - - return Response.created(new URI(null, null, newBook.getLink(), null)).entity(newBook).build(); - } - - @PUT - @Path("/book/{id}") - @Permission({ "book", "modify" }) - @ApiOperation( - value = "Modify a book", - notes = "Modify an existing book.") - public WebBook modifyWebBook(@PathParam("id") String id, WebBook newBook) - throws NotFoundException { - - if (newBook == null) { - throw new BadRequestException("Request body is required"); - } - - WebBook oldBook = books.get(id); - if (oldBook == null) { - throw new NotFoundException("Book with id " + id + " not found"); - } - - String title = oldBook.getTitle(); - if (newBook.getTitle() != null) { - title = newBook.getTitle(); - } - - List lines = oldBook.getLines(); - if (newBook.getLines() != null) { - lines = newBook.getLines(); - } - - WebBook book = new WebBook(id, title, lines); - - books.put(id, book); - saveBooks(); - - return book; - } - - @DELETE - @Path("/book/{id}") - @Permission({ "book", "delete" }) - @ApiOperation( - value = "Delete a book", - notes = "Delete a web book.") - public WebBook deleteWebBook(@PathParam("id") String id) - throws NotFoundException { - WebBook book = books.get(id); - if (book == null) { - throw new NotFoundException("Book with id " + id + " not found"); - } - - books.remove(book.getId()); - saveBooks(); - - return book; - } -} +package valandur.webapi.integration.webbooks; + +import com.google.common.reflect.TypeToken; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; +import valandur.webapi.WebAPI; +import valandur.webapi.config.BaseConfig; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Path("web-books") +@Api( + tags = { "Web Books" }, + value = "Create, edit and delete web books that have unique links which work on your server in-game.") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class WebBooksServlet extends BaseServlet { + + private static final String configFileName = "web-books.conf"; + + private Map books = new ConcurrentHashMap<>(); + + private static WebBooksConfig config; + + + public WebBooksServlet() { + java.nio.file.Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); + config = BaseConfig.load(configPath, new WebBooksConfig()); + books = config.books; + } + + public static void onRegister() { + TypeSerializers.getDefaultSerializers().registerType( + TypeToken.of(WebBook.class), new WebBookConfigSerializer()); + } + + private void saveBooks() { + config.save(); + } + + @GET + @Path("/book") + @Permission({ "book", "list" }) + @ApiOperation( + value = "List books", + notes = "Get a list of all the web books on the server.") + public Collection listWebBooks() { + return books.values(); + } + + @GET + @Path("/book/{id}") + @Permission({ "book", "one" }) + @ApiOperation( + value = "Get a book", + notes = "Get detailed information about a web book.") + public WebBook getWebBook(@PathParam("id") String id) + throws NotFoundException { + WebBook book = books.get(id); + if (book == null) { + throw new NotFoundException("Book with id " + id + " not found"); + } + + return book; + } + + @GET + @Path("/book/{id}/html") + @ApiOperation( + value = "Book HTML", + notes = "Get the web book content as HTML.") + @Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces(MediaType.TEXT_HTML) + public String getWebBookContent(@PathParam("id") String id) + throws NotFoundException { + WebBook book = books.get(id); + if (book == null) { + throw new NotFoundException("Book with id " + id + " not found"); + } + + return book.getHtml(); + } + + @POST + @Path("/book/{id}/html") + @ApiOperation( + value = "Book HTML", + notes = "Get the web book content as HTML.") + @Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces(MediaType.TEXT_HTML) + public String getWebBookContentPost(@PathParam("id") String id) + throws NotFoundException { + WebBook book = books.get(id); + if (book == null) { + throw new NotFoundException("Book with id " + id + " not found"); + } + + return book.getHtml(); + } + + @POST + @Path("/book") + @Permission({ "book", "create" }) + @ApiOperation( + value = "Create a book", + response = WebBook.class, + notes = "Create a new web book from the specified data.") + public Response createWebBook(WebBook book) + throws BadRequestException, URISyntaxException { + + if (book == null) { + throw new BadRequestException("Request body is required"); + } + + String id = book.getId(); + if (id == null || id.isEmpty()) { + throw new BadRequestException("The book needs an id"); + } + + if (books.containsKey(id)) { + throw new BadRequestException("A book with this id already exists"); + } + + String title = ""; + if (book.getTitle() != null) + title = book.getTitle(); + + List lines = new ArrayList<>(); + if (book.getLines() != null) { + lines = book.getLines(); + } + + WebBook newBook = new WebBook(id, title, lines); + + books.put(id, book); + saveBooks(); + + return Response.created(new URI(null, null, newBook.getLink(), null)).entity(newBook).build(); + } + + @PUT + @Path("/book/{id}") + @Permission({ "book", "modify" }) + @ApiOperation( + value = "Modify a book", + notes = "Modify an existing book.") + public WebBook modifyWebBook(@PathParam("id") String id, WebBook newBook) + throws NotFoundException { + + if (newBook == null) { + throw new BadRequestException("Request body is required"); + } + + WebBook oldBook = books.get(id); + if (oldBook == null) { + throw new NotFoundException("Book with id " + id + " not found"); + } + + String title = oldBook.getTitle(); + if (newBook.getTitle() != null) { + title = newBook.getTitle(); + } + + List lines = oldBook.getLines(); + if (newBook.getLines() != null) { + lines = newBook.getLines(); + } + + WebBook book = new WebBook(id, title, lines); + + books.put(id, book); + saveBooks(); + + return book; + } + + @DELETE + @Path("/book/{id}") + @Permission({ "book", "delete" }) + @ApiOperation( + value = "Delete a book", + notes = "Delete a web book.") + public WebBook deleteWebBook(@PathParam("id") String id) + throws NotFoundException { + WebBook book = books.get(id); + if (book == null) { + throw new NotFoundException("Book with id " + id + " not found"); + } + + books.remove(book.getId()); + saveBooks(); + + return book; + } +} diff --git a/src/main/java/valandur/webapi/link/LinkClient.java b/webapi-sponge/src/main/java/valandur/webapi/link/LinkClient.java similarity index 100% rename from src/main/java/valandur/webapi/link/LinkClient.java rename to webapi-sponge/src/main/java/valandur/webapi/link/LinkClient.java diff --git a/src/main/java/valandur/webapi/link/LinkService.java b/webapi-sponge/src/main/java/valandur/webapi/link/LinkService.java similarity index 100% rename from src/main/java/valandur/webapi/link/LinkService.java rename to webapi-sponge/src/main/java/valandur/webapi/link/LinkService.java diff --git a/src/main/java/valandur/webapi/link/internal/InternalChannelState.java b/webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalChannelState.java similarity index 100% rename from src/main/java/valandur/webapi/link/internal/InternalChannelState.java rename to webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalChannelState.java diff --git a/src/main/java/valandur/webapi/link/internal/InternalHttpRequest.java b/webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalHttpRequest.java similarity index 100% rename from src/main/java/valandur/webapi/link/internal/InternalHttpRequest.java rename to webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalHttpRequest.java diff --git a/src/main/java/valandur/webapi/link/internal/InternalHttpResponse.java b/webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalHttpResponse.java similarity index 100% rename from src/main/java/valandur/webapi/link/internal/InternalHttpResponse.java rename to webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalHttpResponse.java diff --git a/src/main/java/valandur/webapi/link/internal/InternalInputStream.java b/webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalInputStream.java similarity index 100% rename from src/main/java/valandur/webapi/link/internal/InternalInputStream.java rename to webapi-sponge/src/main/java/valandur/webapi/link/internal/InternalInputStream.java diff --git a/src/main/java/valandur/webapi/link/rabbitmq/RabbitMQClient.java b/webapi-sponge/src/main/java/valandur/webapi/link/rabbitmq/RabbitMQClient.java similarity index 100% rename from src/main/java/valandur/webapi/link/rabbitmq/RabbitMQClient.java rename to webapi-sponge/src/main/java/valandur/webapi/link/rabbitmq/RabbitMQClient.java diff --git a/src/main/java/valandur/webapi/link/redis/RedisClient.java b/webapi-sponge/src/main/java/valandur/webapi/link/redis/RedisClient.java similarity index 100% rename from src/main/java/valandur/webapi/link/redis/RedisClient.java rename to webapi-sponge/src/main/java/valandur/webapi/link/redis/RedisClient.java diff --git a/src/main/java/valandur/webapi/link/ws/WSClient.java b/webapi-sponge/src/main/java/valandur/webapi/link/ws/WSClient.java similarity index 100% rename from src/main/java/valandur/webapi/link/ws/WSClient.java rename to webapi-sponge/src/main/java/valandur/webapi/link/ws/WSClient.java diff --git a/src/main/java/valandur/webapi/link/ws/WSClientSocket.java b/webapi-sponge/src/main/java/valandur/webapi/link/ws/WSClientSocket.java similarity index 100% rename from src/main/java/valandur/webapi/link/ws/WSClientSocket.java rename to webapi-sponge/src/main/java/valandur/webapi/link/ws/WSClientSocket.java diff --git a/src/main/java/valandur/webapi/message/InteractiveMessage.java b/webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessage.java similarity index 96% rename from src/main/java/valandur/webapi/message/InteractiveMessage.java rename to webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessage.java index 386348b1..43bd487a 100644 --- a/src/main/java/valandur/webapi/message/InteractiveMessage.java +++ b/webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessage.java @@ -1,130 +1,130 @@ -package valandur.webapi.message; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.serializer.TextSerializers; -import valandur.webapi.cache.CachedObject; -import valandur.webapi.serialize.JsonDetails; -import valandur.webapi.util.Constants; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -/** - * Represents an interactive message which can be sent to players. - */ -@ApiModel("InteractiveMessage") -public class InteractiveMessage extends CachedObject { - - private UUID uuid; - /** - * Gets the unique id of the message. This is generated when the messages is created. - * @return The unique id of the message. - */ - @ApiModelProperty(value = "The unique UUID of this message", required = true) - public UUID getUUID() { - return uuid; - } - - private String id; - /** - * The id of the message. Useful to identify it in the response. - * @return The id of the message. - */ - @ApiModelProperty(value = "The id of the message. Used to identify responses.", required = true) - public String getId() { - return id; - } - - private String target; - /** - * The target of the message, usually a player uuid. Can be set to "server" to send to all online players. - * @return The uuid of the target, or "server" to send to all online players. - */ - @ApiModelProperty(value = "The target of the message, usually this is a player UUID. Can be set to \"server\" to send to all online players.", required = true) - @JsonDetails - public String getTarget() { - return target; - } - - private List targets; - /** - * Gets all the targets this message is sent to, in case it is sent to multiple players. - * @return The list of target UUIDs. - */ - @ApiModelProperty("A list of targets that will receive the message. Usually a list of player UUIDs") - @JsonDetails - public List getTargets() { return targets; } - - private String message; - /** - * The message that is sent. - * @return The message content. - */ - @ApiModelProperty(dataType = "string", value = "The actual content of the message") - @JsonDetails - public Text getMessage() { - if (message == null) { - return null; - } - return TextSerializers.FORMATTING_CODE.deserialize(message); - } - - private Boolean once; - /** - * Specifies wether the targets can reply multiple times or just once to this message. (This is per target) - * @return True if the targets can only reply once, false otherwise. - */ - @ApiModelProperty("True if this message can only be replied to once per target, false otherwise") - @JsonDetails - public boolean isOnce() { - return once != null && once; - } - - private List options; - /** - * A map of answer keys to values. The value is displayed to the player as a clickable option, and upon clicking - * it the key is sent to the message web hook. - * @return A map of option keys to values. - */ - @ApiModelProperty("Clickable options that the player can select from") - @JsonDetails - public List getOptions() { - if (options != null) { - return new ArrayList<>(options); - } - return new ArrayList<>(); - } - - /** - * True if the message object has options attached, false otherwise. - * @return True if the message object has options, false otherwise. - */ - @JsonIgnore - public boolean hasOptions() { - return options != null; - } - - - - - public InteractiveMessage() { - super(null); - - this.uuid = UUID.randomUUID(); - } - - @Override - public String getLink() { - return Constants.BASE_PATH + "/interactive-message/" + uuid; - } - - @Override - public Optional getLive() { - return super.getLive(); - } -} +package valandur.webapi.message; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.serializer.TextSerializers; +import valandur.webapi.cache.CachedObject; +import valandur.webapi.serialize.JsonDetails; +import valandur.webapi.util.Constants; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +/** + * Represents an interactive message which can be sent to players. + */ +@ApiModel("InteractiveMessage") +public class InteractiveMessage extends CachedObject { + + private UUID uuid; + /** + * Gets the unique id of the message. This is generated when the messages is created. + * @return The unique id of the message. + */ + @ApiModelProperty(value = "The unique UUID of this message", required = true) + public UUID getUUID() { + return uuid; + } + + private String id; + /** + * The id of the message. Useful to identify it in the response. + * @return The id of the message. + */ + @ApiModelProperty(value = "The id of the message. Used to identify responses.", required = true) + public String getId() { + return id; + } + + private String target; + /** + * The target of the message, usually a player uuid. Can be set to "server" to send to all online players. + * @return The uuid of the target, or "server" to send to all online players. + */ + @ApiModelProperty(value = "The target of the message, usually this is a player UUID. Can be set to \"server\" to send to all online players.", required = true) + @JsonDetails + public String getTarget() { + return target; + } + + private List targets; + /** + * Gets all the targets this message is sent to, in case it is sent to multiple players. + * @return The list of target UUIDs. + */ + @ApiModelProperty("A list of targets that will receive the message. Usually a list of player UUIDs") + @JsonDetails + public List getTargets() { return targets; } + + private String message; + /** + * The message that is sent. + * @return The message content. + */ + @ApiModelProperty(dataType = "string", value = "The actual content of the message") + @JsonDetails + public Text getMessage() { + if (message == null) { + return null; + } + return TextSerializers.FORMATTING_CODE.deserialize(message); + } + + private Boolean once; + /** + * Specifies wether the targets can reply multiple times or just once to this message. (This is per target) + * @return True if the targets can only reply once, false otherwise. + */ + @ApiModelProperty("True if this message can only be replied to once per target, false otherwise") + @JsonDetails + public boolean isOnce() { + return once != null && once; + } + + private List options; + /** + * A map of answer keys to values. The value is displayed to the player as a clickable option, and upon clicking + * it the key is sent to the message web hook. + * @return A map of option keys to values. + */ + @ApiModelProperty("Clickable options that the player can select from") + @JsonDetails + public List getOptions() { + if (options != null) { + return new ArrayList<>(options); + } + return new ArrayList<>(); + } + + /** + * True if the message object has options attached, false otherwise. + * @return True if the message object has options, false otherwise. + */ + @JsonIgnore + public boolean hasOptions() { + return options != null; + } + + + + + public InteractiveMessage() { + super(null); + + this.uuid = UUID.randomUUID(); + } + + @Override + public String getLink() { + return Constants.BASE_PATH + "/interactive-message/" + uuid; + } + + @Override + public Optional getLive() { + return super.getLive(); + } +} diff --git a/src/main/java/valandur/webapi/message/InteractiveMessageOption.java b/webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessageOption.java similarity index 96% rename from src/main/java/valandur/webapi/message/InteractiveMessageOption.java rename to webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessageOption.java index e9a70a13..d49b2fc5 100644 --- a/src/main/java/valandur/webapi/message/InteractiveMessageOption.java +++ b/webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessageOption.java @@ -1,45 +1,45 @@ -package valandur.webapi.message; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.serializer.TextSerializers; - -@ApiModel("InteractiveMessageOption") -public class InteractiveMessageOption { - - private String key; - /** - * Gets the key of the message option that is returned to the server - * @return The key of the message option. - */ - @ApiModelProperty(value = "The key of the option (this is sent to the WebHook)", required = true) - public String getKey() { - return key; - } - - private String value; - /** - * Gets the value of the message option that is displayed to the user. - * @return The value of the message option. - */ - @ApiModelProperty(dataType = "string", value = "The value of the option (this is displayed to the player)", required = true) - @JsonIgnore - public Text getValue() { - if (value == null) { - return null; - } - return TextSerializers.FORMATTING_CODE.deserialize(value); - } - - @JsonProperty("value") - public String getRawValue() { - return value; - } - @JsonProperty("value") - public void setValue(String value) { - this.value = value; - } -} +package valandur.webapi.message; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.serializer.TextSerializers; + +@ApiModel("InteractiveMessageOption") +public class InteractiveMessageOption { + + private String key; + /** + * Gets the key of the message option that is returned to the server + * @return The key of the message option. + */ + @ApiModelProperty(value = "The key of the option (this is sent to the WebHook)", required = true) + public String getKey() { + return key; + } + + private String value; + /** + * Gets the value of the message option that is displayed to the user. + * @return The value of the message option. + */ + @ApiModelProperty(dataType = "string", value = "The value of the option (this is displayed to the player)", required = true) + @JsonIgnore + public Text getValue() { + if (value == null) { + return null; + } + return TextSerializers.FORMATTING_CODE.deserialize(value); + } + + @JsonProperty("value") + public String getRawValue() { + return value; + } + @JsonProperty("value") + public void setValue(String value) { + this.value = value; + } +} diff --git a/src/main/java/valandur/webapi/message/InteractiveMessageResponse.java b/webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessageResponse.java similarity index 100% rename from src/main/java/valandur/webapi/message/InteractiveMessageResponse.java rename to webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessageResponse.java diff --git a/src/main/java/valandur/webapi/message/InteractiveMessageService.java b/webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessageService.java similarity index 100% rename from src/main/java/valandur/webapi/message/InteractiveMessageService.java rename to webapi-sponge/src/main/java/valandur/webapi/message/InteractiveMessageService.java diff --git a/src/main/java/valandur/webapi/security/PermissionStruct.java b/webapi-sponge/src/main/java/valandur/webapi/security/PermissionStruct.java similarity index 100% rename from src/main/java/valandur/webapi/security/PermissionStruct.java rename to webapi-sponge/src/main/java/valandur/webapi/security/PermissionStruct.java diff --git a/src/main/java/valandur/webapi/security/PermissionStructSerializer.java b/webapi-sponge/src/main/java/valandur/webapi/security/PermissionStructSerializer.java similarity index 97% rename from src/main/java/valandur/webapi/security/PermissionStructSerializer.java rename to webapi-sponge/src/main/java/valandur/webapi/security/PermissionStructSerializer.java index 339affc3..6e9d10e3 100644 --- a/src/main/java/valandur/webapi/security/PermissionStructSerializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/security/PermissionStructSerializer.java @@ -1,27 +1,27 @@ -package valandur.webapi.security; - -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; -import valandur.webapi.WebAPI; -import valandur.webapi.util.TreeNode; - -public class PermissionStructSerializer implements TypeSerializer { - - @Override - public PermissionStruct deserialize(TypeToken type, ConfigurationNode value) throws ObjectMappingException { - String key = value.getKey().toString(); - - TreeNode perms = WebAPI.getSecurityService().permissionTreeFromConfig(value.getNode("permissions")); - int rateLimit = value.getNode("rateLimit").getInt(); - - return new PermissionStruct(key, perms, rateLimit); - } - - @Override - public void serialize(TypeToken type, PermissionStruct obj, ConfigurationNode value) throws ObjectMappingException { - WebAPI.getSecurityService().permissionTreeToConfig(value.getNode("permissions"), obj.getPermissions()); - value.getNode("rateLimit").setValue(obj.getRateLimit()); - } -} +package valandur.webapi.security; + +import com.google.common.reflect.TypeToken; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import valandur.webapi.WebAPI; +import valandur.webapi.util.TreeNode; + +public class PermissionStructSerializer implements TypeSerializer { + + @Override + public PermissionStruct deserialize(TypeToken type, ConfigurationNode value) throws ObjectMappingException { + String key = value.getKey().toString(); + + TreeNode perms = WebAPI.getSecurityService().permissionTreeFromConfig(value.getNode("permissions")); + int rateLimit = value.getNode("rateLimit").getInt(); + + return new PermissionStruct(key, perms, rateLimit); + } + + @Override + public void serialize(TypeToken type, PermissionStruct obj, ConfigurationNode value) throws ObjectMappingException { + WebAPI.getSecurityService().permissionTreeToConfig(value.getNode("permissions"), obj.getPermissions()); + value.getNode("rateLimit").setValue(obj.getRateLimit()); + } +} diff --git a/src/main/java/valandur/webapi/security/SecurityContext.java b/webapi-sponge/src/main/java/valandur/webapi/security/SecurityContext.java similarity index 95% rename from src/main/java/valandur/webapi/security/SecurityContext.java rename to webapi-sponge/src/main/java/valandur/webapi/security/SecurityContext.java index b1b1c01a..cedad3f4 100644 --- a/src/main/java/valandur/webapi/security/SecurityContext.java +++ b/webapi-sponge/src/main/java/valandur/webapi/security/SecurityContext.java @@ -1,52 +1,52 @@ -package valandur.webapi.security; - -import valandur.webapi.WebAPI; -import valandur.webapi.user.UserPermissionStruct; -import valandur.webapi.util.TreeNode; - -import java.security.Principal; - -public class SecurityContext implements javax.ws.rs.core.SecurityContext { - - private PermissionStruct perms; - public PermissionStruct getPermissionStruct() { - return perms; - } - - private TreeNode endpointPerms; - public TreeNode getEndpointPerms() { - return endpointPerms; - } - public void setEndpointPerms(TreeNode endpointPerms) { - this.endpointPerms = endpointPerms; - } - - @Override - public Principal getUserPrincipal() { - return perms; - } - - @Override - public boolean isUserInRole(String role) { - return false; - } - - @Override - public boolean isSecure() { - return perms instanceof UserPermissionStruct; - } - - @Override - public String getAuthenticationScheme() { - return "WEBAPI-PERMS"; - } - - public boolean hasPerms(String... reqPerms) { - return WebAPI.getSecurityService().subPermissions(endpointPerms, reqPerms).getValue(); - } - - - public SecurityContext(PermissionStruct perms) { - this.perms = perms; - } -} +package valandur.webapi.security; + +import valandur.webapi.WebAPI; +import valandur.webapi.user.UserPermissionStruct; +import valandur.webapi.util.TreeNode; + +import java.security.Principal; + +public class SecurityContext implements javax.ws.rs.core.SecurityContext { + + private PermissionStruct perms; + public PermissionStruct getPermissionStruct() { + return perms; + } + + private TreeNode endpointPerms; + public TreeNode getEndpointPerms() { + return endpointPerms; + } + public void setEndpointPerms(TreeNode endpointPerms) { + this.endpointPerms = endpointPerms; + } + + @Override + public Principal getUserPrincipal() { + return perms; + } + + @Override + public boolean isUserInRole(String role) { + return false; + } + + @Override + public boolean isSecure() { + return perms instanceof UserPermissionStruct; + } + + @Override + public String getAuthenticationScheme() { + return "WEBAPI-PERMS"; + } + + public boolean hasPerms(String... reqPerms) { + return WebAPI.getSecurityService().subPermissions(endpointPerms, reqPerms).getValue(); + } + + + public SecurityContext(PermissionStruct perms) { + this.perms = perms; + } +} diff --git a/src/main/java/valandur/webapi/security/SecurityFilter.java b/webapi-sponge/src/main/java/valandur/webapi/security/SecurityFilter.java similarity index 97% rename from src/main/java/valandur/webapi/security/SecurityFilter.java rename to webapi-sponge/src/main/java/valandur/webapi/security/SecurityFilter.java index bc1b0990..a3c00345 100644 --- a/src/main/java/valandur/webapi/security/SecurityFilter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/security/SecurityFilter.java @@ -1,189 +1,189 @@ -package valandur.webapi.security; - -import com.google.common.net.HttpHeaders; -import org.eclipse.jetty.http.HttpMethod; -import valandur.webapi.WebAPI; -import valandur.webapi.servlet.base.ExplicitDetails; -import valandur.webapi.servlet.base.Permission; -import valandur.webapi.util.TreeNode; - -import javax.annotation.Priority; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.*; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ResourceInfo; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; - -import static valandur.webapi.security.SecurityService.*; - -@Provider -@Priority(Priorities.AUTHENTICATION) -public class SecurityFilter implements ContainerRequestFilter { - - private SecurityService srv; - - private Map lastCall = new ConcurrentHashMap<>(); - private AtomicLong calls = new AtomicLong(0); - - @Context - private ResourceInfo resourceInfo; - @Context - private HttpServletRequest request; - @Context - private HttpServletResponse response; - - - public SecurityFilter() { - this.srv = WebAPI.getSecurityService(); - } - - @Override - public void filter(ContainerRequestContext context) { - String addr = getRealAddr(request); - String target = context.getUriInfo().getPath(); - - request.setAttribute("ip", addr); - - response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ORIGIN); - response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_METHODS); - response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_HEADERS); - - // Exit early on options requests - if (HttpMethod.OPTIONS.asString().equalsIgnoreCase(context.getMethod())) { - context.abortWith(Response.ok().build()); - return; - } - - if (!srv.whitelistContains(addr)) { - WebAPI.getLogger().warn(addr + " is not on whitelist: " + target); - throw new ForbiddenException(); - } else if (srv.blacklistContains(addr)) { - WebAPI.getLogger().warn(addr + " is on blacklist: " + target); - throw new ForbiddenException(); - } - - String key = context.getHeaderString(API_KEY_HEADER); - if (key == null || key.isEmpty()) { - key = context.getUriInfo().getQueryParameters().getFirst("key"); - } - if (key == null || key.isEmpty()) { - key = context.getHeaderString(HttpHeaders.AUTHORIZATION); - if (key != null) key = key.substring(key.indexOf(" ") + 1); - } - - PermissionStruct permStruct; - if (key != null) { - permStruct = srv.getPermissions(key); - } else { - key = DEFAULT_KEY; - permStruct = srv.getDefaultPermissions(); - } - - // Add new security context - SecurityContext securityContext = new SecurityContext(permStruct); - context.setSecurityContext(securityContext); - request.setAttribute("security", securityContext); - - // Do rate limiting - calls.incrementAndGet(); - - if (permStruct.getRateLimit() > 0) { - double time = System.nanoTime() / 1000000000d; - - if (lastCall.containsKey(key) && time - lastCall.get(key) < 1d / permStruct.getRateLimit()) { - WebAPI.getLogger().warn(addr + " has exceeded the rate limit when requesting " + - request.getRequestURI()); - throw new ClientErrorException("Rate limit exceeded", Response.Status.TOO_MANY_REQUESTS); - } - - lastCall.put(key, time); - } - - boolean details = true; - Method method = resourceInfo.getResourceMethod(); - if (method.isAnnotationPresent(ExplicitDetails.class)) { - ExplicitDetails dets = method.getAnnotation(ExplicitDetails.class); - if (dets.value()) { - details = false; - } - } - request.setAttribute("details", details); - - String basePath = resourceInfo.getResourceClass().getAnnotation(Path.class).value(); - TreeNode perms = permStruct.getPermissions(); - - Permission[] reqPerms = method.getAnnotationsByType(Permission.class); - if (reqPerms.length == 0) { - return; - } - - // Calculate the sub-perms that apply for our endpoint - for (Permission reqPerm : reqPerms) { - if (!reqPerm.autoCheck()) { - continue; - } - - List reqPermList = new ArrayList<>(Arrays.asList(reqPerm.value())); - reqPermList.add(0, basePath); - - TreeNode methodPerms = SecurityService.subPermissions(perms, reqPermList); - if (!methodPerms.getValue()) { - WebAPI.getLogger().warn(addr + " does not have permisson to access " + target); - if (key.equalsIgnoreCase(DEFAULT_KEY)) { - throw new NotAuthorizedException("Bearer realm=\"Web-API Access\""); - } else { - throw new ForbiddenException(); - } - } - - // Set the endpoint permissions to the first permissions listed - if (securityContext.getEndpointPerms() == null) - securityContext.setEndpointPerms(methodPerms); - } - } - - private String getRealAddr(HttpServletRequest request) { - final String addr = request.getRemoteAddr(); - String forwardedFor = request.getHeader(HttpHeaders.X_FORWARDED_FOR); - if (forwardedFor == null) - return addr; - - // First check the actual IP that we got. If that is not a trusted proxy we're done. - if (!srv.containsProxyIP(addr)) { - WebAPI.getLogger().warn(addr + " sent " + HttpHeaders.X_FORWARDED_FOR + - " header, but is not a proxy. Header will be ignored!"); - return addr; - } - - String[] ips = forwardedFor.split(","); - - // Traverse the X-Forwarded-For header backwards and take the first IP that we don't trust. - for (int i = ips.length - 1; i >= 0; i--) { - String ip = ips[i].trim(); - if (srv.containsProxyIP(ip)) { - continue; - } - - if (i > 0) { - WebAPI.getLogger().warn(ips[i].trim() + " sent " + HttpHeaders.X_FORWARDED_FOR + - " header, but is not a proxy. Header will be ignored!"); - } - return ips[i]; - } - - // We usually shouldn't get here, but if we don't it means we trusted all proxy ips, so just - // return the last one of those. - return ips[ips.length - 1]; - } -} +package valandur.webapi.security; + +import com.google.common.net.HttpHeaders; +import org.eclipse.jetty.http.HttpMethod; +import valandur.webapi.WebAPI; +import valandur.webapi.servlet.base.ExplicitDetails; +import valandur.webapi.servlet.base.Permission; +import valandur.webapi.util.TreeNode; + +import javax.annotation.Priority; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +import static valandur.webapi.security.SecurityService.*; + +@Provider +@Priority(Priorities.AUTHENTICATION) +public class SecurityFilter implements ContainerRequestFilter { + + private SecurityService srv; + + private Map lastCall = new ConcurrentHashMap<>(); + private AtomicLong calls = new AtomicLong(0); + + @Context + private ResourceInfo resourceInfo; + @Context + private HttpServletRequest request; + @Context + private HttpServletResponse response; + + + public SecurityFilter() { + this.srv = WebAPI.getSecurityService(); + } + + @Override + public void filter(ContainerRequestContext context) { + String addr = getRealAddr(request); + String target = context.getUriInfo().getPath(); + + request.setAttribute("ip", addr); + + response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ORIGIN); + response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_METHODS); + response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_HEADERS); + + // Exit early on options requests + if (HttpMethod.OPTIONS.asString().equalsIgnoreCase(context.getMethod())) { + context.abortWith(Response.ok().build()); + return; + } + + if (!srv.whitelistContains(addr)) { + WebAPI.getLogger().warn(addr + " is not on whitelist: " + target); + throw new ForbiddenException(); + } else if (srv.blacklistContains(addr)) { + WebAPI.getLogger().warn(addr + " is on blacklist: " + target); + throw new ForbiddenException(); + } + + String key = context.getHeaderString(API_KEY_HEADER); + if (key == null || key.isEmpty()) { + key = context.getUriInfo().getQueryParameters().getFirst("key"); + } + if (key == null || key.isEmpty()) { + key = context.getHeaderString(HttpHeaders.AUTHORIZATION); + if (key != null) key = key.substring(key.indexOf(" ") + 1); + } + + PermissionStruct permStruct; + if (key != null) { + permStruct = srv.getPermissions(key); + } else { + key = DEFAULT_KEY; + permStruct = srv.getDefaultPermissions(); + } + + // Add new security context + SecurityContext securityContext = new SecurityContext(permStruct); + context.setSecurityContext(securityContext); + request.setAttribute("security", securityContext); + + // Do rate limiting + calls.incrementAndGet(); + + if (permStruct.getRateLimit() > 0) { + double time = System.nanoTime() / 1000000000d; + + if (lastCall.containsKey(key) && time - lastCall.get(key) < 1d / permStruct.getRateLimit()) { + WebAPI.getLogger().warn(addr + " has exceeded the rate limit when requesting " + + request.getRequestURI()); + throw new ClientErrorException("Rate limit exceeded", Response.Status.TOO_MANY_REQUESTS); + } + + lastCall.put(key, time); + } + + boolean details = true; + Method method = resourceInfo.getResourceMethod(); + if (method.isAnnotationPresent(ExplicitDetails.class)) { + ExplicitDetails dets = method.getAnnotation(ExplicitDetails.class); + if (dets.value()) { + details = false; + } + } + request.setAttribute("details", details); + + String basePath = resourceInfo.getResourceClass().getAnnotation(Path.class).value(); + TreeNode perms = permStruct.getPermissions(); + + Permission[] reqPerms = method.getAnnotationsByType(Permission.class); + if (reqPerms.length == 0) { + return; + } + + // Calculate the sub-perms that apply for our endpoint + for (Permission reqPerm : reqPerms) { + if (!reqPerm.autoCheck()) { + continue; + } + + List reqPermList = new ArrayList<>(Arrays.asList(reqPerm.value())); + reqPermList.add(0, basePath); + + TreeNode methodPerms = SecurityService.subPermissions(perms, reqPermList); + if (!methodPerms.getValue()) { + WebAPI.getLogger().warn(addr + " does not have permisson to access " + target); + if (key.equalsIgnoreCase(DEFAULT_KEY)) { + throw new NotAuthorizedException("Bearer realm=\"Web-API Access\""); + } else { + throw new ForbiddenException(); + } + } + + // Set the endpoint permissions to the first permissions listed + if (securityContext.getEndpointPerms() == null) + securityContext.setEndpointPerms(methodPerms); + } + } + + private String getRealAddr(HttpServletRequest request) { + final String addr = request.getRemoteAddr(); + String forwardedFor = request.getHeader(HttpHeaders.X_FORWARDED_FOR); + if (forwardedFor == null) + return addr; + + // First check the actual IP that we got. If that is not a trusted proxy we're done. + if (!srv.containsProxyIP(addr)) { + WebAPI.getLogger().warn(addr + " sent " + HttpHeaders.X_FORWARDED_FOR + + " header, but is not a proxy. Header will be ignored!"); + return addr; + } + + String[] ips = forwardedFor.split(","); + + // Traverse the X-Forwarded-For header backwards and take the first IP that we don't trust. + for (int i = ips.length - 1; i >= 0; i--) { + String ip = ips[i].trim(); + if (srv.containsProxyIP(ip)) { + continue; + } + + if (i > 0) { + WebAPI.getLogger().warn(ips[i].trim() + " sent " + HttpHeaders.X_FORWARDED_FOR + + " header, but is not a proxy. Header will be ignored!"); + } + return ips[i]; + } + + // We usually shouldn't get here, but if we don't it means we trusted all proxy ips, so just + // return the last one of those. + return ips[ips.length - 1]; + } +} diff --git a/src/main/java/valandur/webapi/security/SecurityService.java b/webapi-sponge/src/main/java/valandur/webapi/security/SecurityService.java similarity index 100% rename from src/main/java/valandur/webapi/security/SecurityService.java rename to webapi-sponge/src/main/java/valandur/webapi/security/SecurityService.java diff --git a/src/main/java/valandur/webapi/serialize/AnnotationIntrospector.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/AnnotationIntrospector.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/AnnotationIntrospector.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/AnnotationIntrospector.java index 41182dc0..45bf146a 100644 --- a/src/main/java/valandur/webapi/serialize/AnnotationIntrospector.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/AnnotationIntrospector.java @@ -1,13 +1,13 @@ -package valandur.webapi.serialize; - -import com.fasterxml.jackson.databind.introspect.Annotated; -import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; - -public class AnnotationIntrospector extends JacksonAnnotationIntrospector { - - @Override - public Object findFilterId(Annotated a) { - Object filter = super.findFilterId(a); - return filter != null ? filter : BaseFilter.ID; - } -} +package valandur.webapi.serialize; + +import com.fasterxml.jackson.databind.introspect.Annotated; +import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; + +public class AnnotationIntrospector extends JacksonAnnotationIntrospector { + + @Override + public Object findFilterId(Annotated a) { + Object filter = super.findFilterId(a); + return filter != null ? filter : BaseFilter.ID; + } +} diff --git a/src/main/java/valandur/webapi/serialize/BaseFilter.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/BaseFilter.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/BaseFilter.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/BaseFilter.java index 7b2f9ef7..9830b41f 100644 --- a/src/main/java/valandur/webapi/serialize/BaseFilter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/BaseFilter.java @@ -1,62 +1,62 @@ -package valandur.webapi.serialize; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.PropertyWriter; -import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; -import valandur.webapi.WebAPI; -import valandur.webapi.security.SecurityService; -import valandur.webapi.util.TreeNode; - -import java.util.ArrayList; - -public class BaseFilter extends SimpleBeanPropertyFilter { - - public static String ID = "WEBAPI-BASE-FILTER"; - - private SecurityService permissionService; - private TreeNode perms; - private ArrayList path; - private boolean details; - - - public BaseFilter(boolean details, TreeNode perms) { - this.permissionService = WebAPI.getSecurityService(); - this.details = details; - this.path = new ArrayList<>(); - this.perms = perms; - } - - @Override - public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) - throws Exception { - String key = writer.getName(); - boolean prevDetails = details; - - // Check if we have to skip the field because it is marked as "details" and details is set to false - // or if we have to turn details off temporarily in case the field is marked as "simple" - JsonDetails det = writer.getAnnotation(JsonDetails.class); - if (det != null) { - if (!details && det.value()) { - return; - } - - if (det.simple()) { - details = false; - } - } - - // Add our object to the path - path.add(key); - - // Check if the permission service allows access to our path - // If yes then we want to serialize the rest of our object - if (permissionService.permits(perms, path)) { - super.serializeAsField(pojo, jgen, provider, writer); - } - - // Reset path and details after our object is done - path.remove(key); - details = prevDetails; - } -} +package valandur.webapi.serialize; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.PropertyWriter; +import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; +import valandur.webapi.WebAPI; +import valandur.webapi.security.SecurityService; +import valandur.webapi.util.TreeNode; + +import java.util.ArrayList; + +public class BaseFilter extends SimpleBeanPropertyFilter { + + public static String ID = "WEBAPI-BASE-FILTER"; + + private SecurityService permissionService; + private TreeNode perms; + private ArrayList path; + private boolean details; + + + public BaseFilter(boolean details, TreeNode perms) { + this.permissionService = WebAPI.getSecurityService(); + this.details = details; + this.path = new ArrayList<>(); + this.perms = perms; + } + + @Override + public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) + throws Exception { + String key = writer.getName(); + boolean prevDetails = details; + + // Check if we have to skip the field because it is marked as "details" and details is set to false + // or if we have to turn details off temporarily in case the field is marked as "simple" + JsonDetails det = writer.getAnnotation(JsonDetails.class); + if (det != null) { + if (!details && det.value()) { + return; + } + + if (det.simple()) { + details = false; + } + } + + // Add our object to the path + path.add(key); + + // Check if the permission service allows access to our path + // If yes then we want to serialize the rest of our object + if (permissionService.permits(perms, path)) { + super.serializeAsField(pojo, jgen, provider, writer); + } + + // Reset path and details after our object is done + path.remove(key); + details = prevDetails; + } +} diff --git a/src/main/java/valandur/webapi/serialize/BaseSerializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/BaseSerializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/BaseSerializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/BaseSerializer.java index 5f2d4b64..e9c1c216 100644 --- a/src/main/java/valandur/webapi/serialize/BaseSerializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/BaseSerializer.java @@ -1,56 +1,56 @@ -package valandur.webapi.serialize; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.eclipse.jetty.io.EofException; -import valandur.webapi.WebAPI; - -import javax.ws.rs.InternalServerErrorException; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -public class BaseSerializer extends StdSerializer { - - private Class clazz; - private Class cache; - private Constructor ctr; - - public Class getHandledClass() { - return clazz; - } - public Class getCacheClass() { - return cache; - } - - - public BaseSerializer(Class handledClass, Class cacheClass) { - super(handledClass); - - this.clazz = handledClass; - this.cache = cacheClass; - try { - this.ctr = cache.getDeclaredConstructor(clazz); - } catch (NoSuchMethodException e) { - WebAPI.getLogger().error("The cache class " + cacheClass.getName() + - " does not contain a constructor accepting one argument of type " + - handledClass.getName() + " (it's handled class)"); - WebAPI.sentryCapture(e); - } - } - - @Override - public void serialize(T value, JsonGenerator gen, SerializerProvider provider) { - try { - Object inst = ctr.newInstance(value); - gen.writeObject(inst); - } catch (IllegalAccessException | InvocationTargetException | InstantiationException | IOException e) { - if (gen.isClosed()) return; // Don't try and write the error if the stream is already closed - if (value instanceof Throwable) return; // Don't throw an exception if we're already processing an exception - if (e instanceof EofException) return; // Don't throw on EofExceptions, because likely the remote stream was closed - e.printStackTrace(); - throw new InternalServerErrorException(e.getMessage()); - } - } -} +package valandur.webapi.serialize; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.eclipse.jetty.io.EofException; +import valandur.webapi.WebAPI; + +import javax.ws.rs.InternalServerErrorException; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +public class BaseSerializer extends StdSerializer { + + private Class clazz; + private Class cache; + private Constructor ctr; + + public Class getHandledClass() { + return clazz; + } + public Class getCacheClass() { + return cache; + } + + + public BaseSerializer(Class handledClass, Class cacheClass) { + super(handledClass); + + this.clazz = handledClass; + this.cache = cacheClass; + try { + this.ctr = cache.getDeclaredConstructor(clazz); + } catch (NoSuchMethodException e) { + WebAPI.getLogger().error("The cache class " + cacheClass.getName() + + " does not contain a constructor accepting one argument of type " + + handledClass.getName() + " (it's handled class)"); + WebAPI.sentryCapture(e); + } + } + + @Override + public void serialize(T value, JsonGenerator gen, SerializerProvider provider) { + try { + Object inst = ctr.newInstance(value); + gen.writeObject(inst); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException | IOException e) { + if (gen.isClosed()) return; // Don't try and write the error if the stream is already closed + if (value instanceof Throwable) return; // Don't throw an exception if we're already processing an exception + if (e instanceof EofException) return; // Don't throw on EofExceptions, because likely the remote stream was closed + e.printStackTrace(); + throw new InternalServerErrorException(e.getMessage()); + } + } +} diff --git a/src/main/java/valandur/webapi/serialize/BaseView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/BaseView.java similarity index 93% rename from src/main/java/valandur/webapi/serialize/BaseView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/BaseView.java index d3e6e5b9..08fe9477 100644 --- a/src/main/java/valandur/webapi/serialize/BaseView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/BaseView.java @@ -1,10 +1,10 @@ -package valandur.webapi.serialize; - -public class BaseView { - - protected T value; - - public BaseView(T value) { - this.value = value; - } -} +package valandur.webapi.serialize; + +public class BaseView { + + protected T value; + + public BaseView(T value) { + this.value = value; + } +} diff --git a/src/main/java/valandur/webapi/serialize/JsonDetails.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/JsonDetails.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/JsonDetails.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/JsonDetails.java index 3325931c..6343e8e4 100644 --- a/src/main/java/valandur/webapi/serialize/JsonDetails.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/JsonDetails.java @@ -1,28 +1,28 @@ -package valandur.webapi.serialize; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * This annotation causes fields or methods to only be included in serialized responses if details were explicitly - * requested while serializing the object. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD}) -public @interface JsonDetails { - - /** - * Specifies if the annotated value should only be included in the response when details are requested. - * @return True if the annotated value is only serialized when details where requested, false otherwise. - */ - boolean value() default true; - - /** - * Specifies whether the annotated value should always be serialized without details, even if they were requested. - * @return True if the annotated value should always be serialized without details, even if they were requested, - * false otherwise. - */ - boolean simple() default false; -} +package valandur.webapi.serialize; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation causes fields or methods to only be included in serialized responses if details were explicitly + * requested while serializing the object. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD}) +public @interface JsonDetails { + + /** + * Specifies if the annotated value should only be included in the response when details are requested. + * @return True if the annotated value is only serialized when details where requested, false otherwise. + */ + boolean value() default true; + + /** + * Specifies whether the annotated value should always be serialized without details, even if they were requested. + * @return True if the annotated value should always be serialized without details, even if they were requested, + * false otherwise. + */ + boolean simple() default false; +} diff --git a/src/main/java/valandur/webapi/serialize/SerializationFeature.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/SerializationFeature.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/SerializationFeature.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/SerializationFeature.java index 5567e4ab..9a306613 100644 --- a/src/main/java/valandur/webapi/serialize/SerializationFeature.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/SerializationFeature.java @@ -1,15 +1,15 @@ -package valandur.webapi.serialize; - -import javax.ws.rs.core.Feature; -import javax.ws.rs.core.FeatureContext; -import javax.ws.rs.ext.MessageBodyReader; -import javax.ws.rs.ext.MessageBodyWriter; - -public class SerializationFeature implements Feature { - - @Override - public boolean configure(FeatureContext context) { - context.register(SerializationProvider.class, MessageBodyReader.class, MessageBodyWriter.class); - return true; - } -} +package valandur.webapi.serialize; + +import javax.ws.rs.core.Feature; +import javax.ws.rs.core.FeatureContext; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.MessageBodyWriter; + +public class SerializationFeature implements Feature { + + @Override + public boolean configure(FeatureContext context) { + context.register(SerializationProvider.class, MessageBodyReader.class, MessageBodyWriter.class); + return true; + } +} diff --git a/src/main/java/valandur/webapi/serialize/SerializationProvider.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/SerializationProvider.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/SerializationProvider.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/SerializationProvider.java index 7a779cf8..4b5216aa 100644 --- a/src/main/java/valandur/webapi/serialize/SerializationProvider.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/SerializationProvider.java @@ -1,118 +1,118 @@ -package valandur.webapi.serialize; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import com.fasterxml.jackson.jaxrs.cfg.JaxRSFeature; -import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; -import com.fasterxml.jackson.jaxrs.json.JsonEndpointConfig; -import org.eclipse.jetty.io.EofException; -import valandur.webapi.WebAPI; -import valandur.webapi.security.SecurityContext; -import valandur.webapi.security.SecurityService; -import valandur.webapi.util.TreeNode; -import valandur.webapi.util.Util; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.ext.Provider; -import java.io.IOException; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.Map; - -@Provider -@Consumes(MediaType.WILDCARD) -@Produces(MediaType.WILDCARD) -public class SerializationProvider extends JacksonJsonProvider { - - @Context - HttpServletRequest request; - - @Context - HttpServletResponse response; - - public SerializationProvider() { - disable(JaxRSFeature.CACHE_ENDPOINT_WRITERS); - disable(JaxRSFeature.CACHE_ENDPOINT_READERS); - } - - @Override - protected boolean hasMatchingMediaType(MediaType mediaType) { - return MediaType.TEXT_PLAIN_TYPE.isCompatible(mediaType) || - MediaType.TEXT_HTML_TYPE.isCompatible(mediaType) || - MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType) || - super.hasMatchingMediaType(mediaType); - } - - @Override - protected void _modifyHeaders(Object value, Class type, Type genericType, Annotation[] annotations, - MultivaluedMap httpHeaders, JsonEndpointConfig endpoint) - throws IOException { - super._modifyHeaders(value, type, genericType, annotations, httpHeaders, endpoint); - - // If the mapper was changed with a query parameter, we have to update - // the content type header to reflect that - Map queryParams = Util.getQueryParams(request); - if (queryParams.containsKey("accept")) { - String acc = queryParams.get("accept"); - if (acc.equalsIgnoreCase("json")) { - httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - } - if (acc.equalsIgnoreCase("xml")) { - httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML); - } - } - } - - @Override - public ObjectMapper locateMapper(Class type, MediaType mediaType) { - Map queryParams = Util.getQueryParams(request); - boolean xml = MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType); - // Allow override the media type with a header (for better browser debugging) - if (queryParams.containsKey("accept")) { - String acc = queryParams.get("accept"); - if (acc.equalsIgnoreCase("json")) xml = false; - if (acc.equalsIgnoreCase("xml")) xml = true; - } - - // If we're serializing an error return a normal XML/Object mapper, just in case the error - // happened while creating the mapper, so that we don't get an infinite recursion - if (Throwable.class.isAssignableFrom(type)) { - return xml ? new XmlMapper() : new ObjectMapper(); - } - - SecurityContext ctx = (SecurityContext)request.getAttribute("security"); - TreeNode perms = SecurityService.permitAllNode(); - if (ctx != null && ctx.getEndpointPerms() != null) { - perms = ctx.getEndpointPerms(); - } - - Boolean det = (Boolean)request.getAttribute("details"); - boolean details = (det != null && det) || queryParams.containsKey("details"); - - SerializeService srv = WebAPI.getSerializeService(); - ObjectMapper mapper = srv.getDefaultObjectMapper(xml, details, perms); - if (queryParams.containsKey("pretty")) - mapper.enable(SerializationFeature.INDENT_OUTPUT); - return mapper; - } - - @Override - public void writeTo(Object value, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, OutputStream entityStream) { - try { - super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream); - } catch (IOException e) { - if (e instanceof EofException) return; - e.printStackTrace(); - } - } -} +package valandur.webapi.serialize; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.fasterxml.jackson.jaxrs.cfg.JaxRSFeature; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import com.fasterxml.jackson.jaxrs.json.JsonEndpointConfig; +import org.eclipse.jetty.io.EofException; +import valandur.webapi.WebAPI; +import valandur.webapi.security.SecurityContext; +import valandur.webapi.security.SecurityService; +import valandur.webapi.util.TreeNode; +import valandur.webapi.util.Util; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Map; + +@Provider +@Consumes(MediaType.WILDCARD) +@Produces(MediaType.WILDCARD) +public class SerializationProvider extends JacksonJsonProvider { + + @Context + HttpServletRequest request; + + @Context + HttpServletResponse response; + + public SerializationProvider() { + disable(JaxRSFeature.CACHE_ENDPOINT_WRITERS); + disable(JaxRSFeature.CACHE_ENDPOINT_READERS); + } + + @Override + protected boolean hasMatchingMediaType(MediaType mediaType) { + return MediaType.TEXT_PLAIN_TYPE.isCompatible(mediaType) || + MediaType.TEXT_HTML_TYPE.isCompatible(mediaType) || + MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType) || + super.hasMatchingMediaType(mediaType); + } + + @Override + protected void _modifyHeaders(Object value, Class type, Type genericType, Annotation[] annotations, + MultivaluedMap httpHeaders, JsonEndpointConfig endpoint) + throws IOException { + super._modifyHeaders(value, type, genericType, annotations, httpHeaders, endpoint); + + // If the mapper was changed with a query parameter, we have to update + // the content type header to reflect that + Map queryParams = Util.getQueryParams(request); + if (queryParams.containsKey("accept")) { + String acc = queryParams.get("accept"); + if (acc.equalsIgnoreCase("json")) { + httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + } + if (acc.equalsIgnoreCase("xml")) { + httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML); + } + } + } + + @Override + public ObjectMapper locateMapper(Class type, MediaType mediaType) { + Map queryParams = Util.getQueryParams(request); + boolean xml = MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType); + // Allow override the media type with a header (for better browser debugging) + if (queryParams.containsKey("accept")) { + String acc = queryParams.get("accept"); + if (acc.equalsIgnoreCase("json")) xml = false; + if (acc.equalsIgnoreCase("xml")) xml = true; + } + + // If we're serializing an error return a normal XML/Object mapper, just in case the error + // happened while creating the mapper, so that we don't get an infinite recursion + if (Throwable.class.isAssignableFrom(type)) { + return xml ? new XmlMapper() : new ObjectMapper(); + } + + SecurityContext ctx = (SecurityContext)request.getAttribute("security"); + TreeNode perms = SecurityService.permitAllNode(); + if (ctx != null && ctx.getEndpointPerms() != null) { + perms = ctx.getEndpointPerms(); + } + + Boolean det = (Boolean)request.getAttribute("details"); + boolean details = (det != null && det) || queryParams.containsKey("details"); + + SerializeService srv = WebAPI.getSerializeService(); + ObjectMapper mapper = srv.getDefaultObjectMapper(xml, details, perms); + if (queryParams.containsKey("pretty")) + mapper.enable(SerializationFeature.INDENT_OUTPUT); + return mapper; + } + + @Override + public void writeTo(Object value, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, OutputStream entityStream) { + try { + super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream); + } catch (IOException e) { + if (e instanceof EofException) return; + e.printStackTrace(); + } + } +} diff --git a/src/main/java/valandur/webapi/serialize/SerializeService.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/SerializeService.java similarity index 100% rename from src/main/java/valandur/webapi/serialize/SerializeService.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/SerializeService.java diff --git a/src/main/java/valandur/webapi/serialize/deserialize/BlockStateDeserializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/BlockStateDeserializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/deserialize/BlockStateDeserializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/BlockStateDeserializer.java index 6ec9fbe4..55c5d337 100644 --- a/src/main/java/valandur/webapi/serialize/deserialize/BlockStateDeserializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/BlockStateDeserializer.java @@ -1,91 +1,91 @@ -package valandur.webapi.serialize.deserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.block.trait.BlockTrait; - -import java.io.IOException; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -public class BlockStateDeserializer extends StdDeserializer { - - public BlockStateDeserializer() { - super(BlockState.class); - } - - @Override - public BlockState deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - JsonNode root = p.readValueAsTree(); - if (root.path("type").isMissingNode()) { - throw new IOException("Missing block type"); - } - - String typeStr = root.path("type").isTextual() - ? root.path("type").asText() - : root.path("type").path("id").asText(); - Optional optType = Sponge.getRegistry().getType(BlockType.class, typeStr); - if (!optType.isPresent()) { - throw new IOException("Invalid block type " + typeStr); - } - BlockType type = optType.get(); - - BlockState state = type.getDefaultState(); - Collection> traits = type.getTraits(); - - if (!root.path("data").isMissingNode()) { - Iterator> it = root.path("data").fields(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - - Optional> optTrait = traits.stream().filter(t -> - t.getName().equalsIgnoreCase(entry.getKey()) - ).findAny(); - - if (!optTrait.isPresent()) - throw new IOException("Unknown trait '" + entry.getKey() + "'"); - - BlockTrait trait = optTrait.get(); - Object value = null; - - JsonNode nodeValue = entry.getValue(); - if (nodeValue.isBoolean()) { - value = nodeValue.asBoolean(); - } else if (nodeValue.isInt()) { - value = nodeValue.asInt(); - } else if (nodeValue.isTextual()) { - Collection values = trait.getPossibleValues(); - Optional val = values.stream() - .filter(v -> v.toString().equalsIgnoreCase(nodeValue.asText())) - .findAny(); - - if (!val.isPresent()) { - String allowedValues = values.stream() - .map(Object::toString) - .collect(Collectors.joining(", ")); - throw new IOException("Trait '" + trait.getName() + "' has value '" + - nodeValue.asText() + "' but can only have one of: " + allowedValues); - } else { - value = val.get(); - } - } - - Optional newState = state.withTrait(trait, value); - if (!newState.isPresent()) - throw new IOException("Could not apply trait '" + trait.getName() + " to block state"); - - state = newState.get(); - } - } - - return state; - } -} +package valandur.webapi.serialize.deserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.block.BlockType; +import org.spongepowered.api.block.trait.BlockTrait; + +import java.io.IOException; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +public class BlockStateDeserializer extends StdDeserializer { + + public BlockStateDeserializer() { + super(BlockState.class); + } + + @Override + public BlockState deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + JsonNode root = p.readValueAsTree(); + if (root.path("type").isMissingNode()) { + throw new IOException("Missing block type"); + } + + String typeStr = root.path("type").isTextual() + ? root.path("type").asText() + : root.path("type").path("id").asText(); + Optional optType = Sponge.getRegistry().getType(BlockType.class, typeStr); + if (!optType.isPresent()) { + throw new IOException("Invalid block type " + typeStr); + } + BlockType type = optType.get(); + + BlockState state = type.getDefaultState(); + Collection> traits = type.getTraits(); + + if (!root.path("data").isMissingNode()) { + Iterator> it = root.path("data").fields(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + + Optional> optTrait = traits.stream().filter(t -> + t.getName().equalsIgnoreCase(entry.getKey()) + ).findAny(); + + if (!optTrait.isPresent()) + throw new IOException("Unknown trait '" + entry.getKey() + "'"); + + BlockTrait trait = optTrait.get(); + Object value = null; + + JsonNode nodeValue = entry.getValue(); + if (nodeValue.isBoolean()) { + value = nodeValue.asBoolean(); + } else if (nodeValue.isInt()) { + value = nodeValue.asInt(); + } else if (nodeValue.isTextual()) { + Collection values = trait.getPossibleValues(); + Optional val = values.stream() + .filter(v -> v.toString().equalsIgnoreCase(nodeValue.asText())) + .findAny(); + + if (!val.isPresent()) { + String allowedValues = values.stream() + .map(Object::toString) + .collect(Collectors.joining(", ")); + throw new IOException("Trait '" + trait.getName() + "' has value '" + + nodeValue.asText() + "' but can only have one of: " + allowedValues); + } else { + value = val.get(); + } + } + + Optional newState = state.withTrait(trait, value); + if (!newState.isPresent()) + throw new IOException("Could not apply trait '" + trait.getName() + " to block state"); + + state = newState.get(); + } + } + + return state; + } +} diff --git a/src/main/java/valandur/webapi/serialize/deserialize/CachedCatalogTypeDeserializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedCatalogTypeDeserializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/deserialize/CachedCatalogTypeDeserializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedCatalogTypeDeserializer.java index 00b95956..cc2d70e4 100644 --- a/src/main/java/valandur/webapi/serialize/deserialize/CachedCatalogTypeDeserializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedCatalogTypeDeserializer.java @@ -1,49 +1,49 @@ -package valandur.webapi.serialize.deserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.BeanProperty; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.ContextualDeserializer; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import org.spongepowered.api.CatalogType; -import org.spongepowered.api.Sponge; -import valandur.webapi.cache.misc.CachedCatalogType; - -import java.io.IOException; -import java.util.Optional; - -public class CachedCatalogTypeDeserializer extends StdDeserializer> - implements ContextualDeserializer { - - public CachedCatalogTypeDeserializer(Class vc) { - super(vc); - } - - @Override - public JsonDeserializer createContextual(DeserializationContext ctxt, BeanProperty property) { - Class c = property.getType().containedType(0).getRawClass(); - return new CachedCatalogTypeDeserializer<>(c); - } - - @Override - public CachedCatalogType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - JsonNode tree = p.readValueAsTree(); - - if (tree == null) { - return null; - } - - if (tree.isTextual()) { - Optional type = Sponge.getRegistry().getType((Class) _valueClass, tree.asText()); - return type.map(CachedCatalogType::new).orElse(null); - } else { - if (tree.path("id").isMissingNode()) { - return null; - } - Optional type = Sponge.getRegistry().getType((Class) _valueClass, tree.get("id").asText()); - return type.map(CachedCatalogType::new).orElse(null); - } - } -} +package valandur.webapi.serialize.deserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import org.spongepowered.api.CatalogType; +import org.spongepowered.api.Sponge; +import valandur.webapi.cache.misc.CachedCatalogType; + +import java.io.IOException; +import java.util.Optional; + +public class CachedCatalogTypeDeserializer extends StdDeserializer> + implements ContextualDeserializer { + + public CachedCatalogTypeDeserializer(Class vc) { + super(vc); + } + + @Override + public JsonDeserializer createContextual(DeserializationContext ctxt, BeanProperty property) { + Class c = property.getType().containedType(0).getRawClass(); + return new CachedCatalogTypeDeserializer<>(c); + } + + @Override + public CachedCatalogType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + JsonNode tree = p.readValueAsTree(); + + if (tree == null) { + return null; + } + + if (tree.isTextual()) { + Optional type = Sponge.getRegistry().getType((Class) _valueClass, tree.asText()); + return type.map(CachedCatalogType::new).orElse(null); + } else { + if (tree.path("id").isMissingNode()) { + return null; + } + Optional type = Sponge.getRegistry().getType((Class) _valueClass, tree.get("id").asText()); + return type.map(CachedCatalogType::new).orElse(null); + } + } +} diff --git a/src/main/java/valandur/webapi/serialize/deserialize/CachedLocationDeserializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedLocationDeserializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/deserialize/CachedLocationDeserializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedLocationDeserializer.java index 4d113d4f..720471c9 100644 --- a/src/main/java/valandur/webapi/serialize/deserialize/CachedLocationDeserializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedLocationDeserializer.java @@ -1,41 +1,41 @@ -package valandur.webapi.serialize.deserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.world.CachedLocation; -import valandur.webapi.cache.world.CachedWorld; - -import java.io.IOException; -import java.util.Optional; - -public class CachedLocationDeserializer extends StdDeserializer { - - public CachedLocationDeserializer() { - super(CachedLocation.class); - } - - @Override - public CachedLocation deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - JsonNode root = p.readValueAsTree(); - - if (root.isNull() || root.isMissingNode()) - return null; - - Optional optWorld = WebAPI.getCacheService().getWorld(root.path("world").asText()); - if (!optWorld.isPresent()) - throw new IOException("Invalid world name / uuid"); - - JsonNode posNode = root.path("position"); - if (posNode.isMissingNode()) - throw new IOException("Invalid position"); - - double x = posNode.path("x").asDouble(); - double y = posNode.path("y").asDouble(); - double z = posNode.path("z").asDouble(); - - return new CachedLocation(optWorld.get(), x, y, z); - } -} +package valandur.webapi.serialize.deserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.world.CachedLocation; +import valandur.webapi.cache.world.CachedWorld; + +import java.io.IOException; +import java.util.Optional; + +public class CachedLocationDeserializer extends StdDeserializer { + + public CachedLocationDeserializer() { + super(CachedLocation.class); + } + + @Override + public CachedLocation deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + JsonNode root = p.readValueAsTree(); + + if (root.isNull() || root.isMissingNode()) + return null; + + Optional optWorld = WebAPI.getCacheService().getWorld(root.path("world").asText()); + if (!optWorld.isPresent()) + throw new IOException("Invalid world name / uuid"); + + JsonNode posNode = root.path("position"); + if (posNode.isMissingNode()) + throw new IOException("Invalid position"); + + double x = posNode.path("x").asDouble(); + double y = posNode.path("y").asDouble(); + double z = posNode.path("z").asDouble(); + + return new CachedLocation(optWorld.get(), x, y, z); + } +} diff --git a/src/main/java/valandur/webapi/serialize/deserialize/CachedPlayerDeserializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedPlayerDeserializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/deserialize/CachedPlayerDeserializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedPlayerDeserializer.java index 8d0d1194..6cb24615 100644 --- a/src/main/java/valandur/webapi/serialize/deserialize/CachedPlayerDeserializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedPlayerDeserializer.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.deserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.player.CachedPlayer; - -import java.io.IOException; -import java.util.Optional; - -public class CachedPlayerDeserializer extends StdDeserializer { - - public CachedPlayerDeserializer() { - super(CachedPlayer.class); - } - - @Override - public CachedPlayer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String nameOrUuid = p.getValueAsString(); - Optional optPlayer = WebAPI.getCacheService().getPlayer(nameOrUuid); - return optPlayer.orElse(null); - } -} +package valandur.webapi.serialize.deserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.player.CachedPlayer; + +import java.io.IOException; +import java.util.Optional; + +public class CachedPlayerDeserializer extends StdDeserializer { + + public CachedPlayerDeserializer() { + super(CachedPlayer.class); + } + + @Override + public CachedPlayer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + String nameOrUuid = p.getValueAsString(); + Optional optPlayer = WebAPI.getCacheService().getPlayer(nameOrUuid); + return optPlayer.orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/deserialize/CachedWorldDeserializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedWorldDeserializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/deserialize/CachedWorldDeserializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedWorldDeserializer.java index b26be311..5c54f25c 100644 --- a/src/main/java/valandur/webapi/serialize/deserialize/CachedWorldDeserializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/CachedWorldDeserializer.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.deserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.world.CachedWorld; - -import java.io.IOException; -import java.util.Optional; - -public class CachedWorldDeserializer extends StdDeserializer { - - public CachedWorldDeserializer() { - super(CachedWorld.class); - } - - @Override - public CachedWorld deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String nameOrUuid = p.getValueAsString(); - Optional optWorld = WebAPI.getCacheService().getWorld(nameOrUuid); - return optWorld.orElse(null); - } -} +package valandur.webapi.serialize.deserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.world.CachedWorld; + +import java.io.IOException; +import java.util.Optional; + +public class CachedWorldDeserializer extends StdDeserializer { + + public CachedWorldDeserializer() { + super(CachedWorld.class); + } + + @Override + public CachedWorld deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + String nameOrUuid = p.getValueAsString(); + Optional optWorld = WebAPI.getCacheService().getWorld(nameOrUuid); + return optWorld.orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/deserialize/ItemStackDeserializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/ItemStackDeserializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/deserialize/ItemStackDeserializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/ItemStackDeserializer.java index fc1dcd1e..b6d8c788 100644 --- a/src/main/java/valandur/webapi/serialize/deserialize/ItemStackDeserializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/ItemStackDeserializer.java @@ -1,60 +1,60 @@ -package valandur.webapi.serialize.deserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.data.manipulator.DataManipulator; -import org.spongepowered.api.item.ItemType; -import org.spongepowered.api.item.inventory.ItemStack; -import valandur.webapi.WebAPI; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Map; -import java.util.Optional; - -public class ItemStackDeserializer extends StdDeserializer { - - public ItemStackDeserializer() { - super(ItemStack.class); - } - - @Override - public ItemStack deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - JsonNode root = p.readValueAsTree(); - if (root.path("type").isMissingNode()) - throw new IOException("Missing item type"); - - String id = root.path("type").isTextual() - ? root.path("type").asText() - : root.path("type").path("id").asText(); - Optional optType = Sponge.getRegistry().getType(ItemType.class, id); - if (!optType.isPresent()) - throw new IOException("Invalid item type " + id); - - Integer amount = root.path("quantity").isMissingNode() ? 1 : root.path("quantity").asInt(); - - ItemType type = optType.get(); - - ItemStack.Builder builder = ItemStack.builder().itemType(type).quantity(amount); - ItemStack item = builder.build(); - - if (!root.path("data").isMissingNode()) { - Iterator> it = root.path("data").fields(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - Class c = WebAPI.getSerializeService().getSupportedData().get(entry.getKey()); - if (c == null) continue; - Optional optData = item.getOrCreate(c); - if (!optData.isPresent()) - throw new IOException("Invalid item data: " + entry.getKey()); - DataManipulator data = optData.get(); - item.offer(data); - } - } - - return item; - } -} +package valandur.webapi.serialize.deserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.data.manipulator.DataManipulator; +import org.spongepowered.api.item.ItemType; +import org.spongepowered.api.item.inventory.ItemStack; +import valandur.webapi.WebAPI; + +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; +import java.util.Optional; + +public class ItemStackDeserializer extends StdDeserializer { + + public ItemStackDeserializer() { + super(ItemStack.class); + } + + @Override + public ItemStack deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + JsonNode root = p.readValueAsTree(); + if (root.path("type").isMissingNode()) + throw new IOException("Missing item type"); + + String id = root.path("type").isTextual() + ? root.path("type").asText() + : root.path("type").path("id").asText(); + Optional optType = Sponge.getRegistry().getType(ItemType.class, id); + if (!optType.isPresent()) + throw new IOException("Invalid item type " + id); + + Integer amount = root.path("quantity").isMissingNode() ? 1 : root.path("quantity").asInt(); + + ItemType type = optType.get(); + + ItemStack.Builder builder = ItemStack.builder().itemType(type).quantity(amount); + ItemStack item = builder.build(); + + if (!root.path("data").isMissingNode()) { + Iterator> it = root.path("data").fields(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + Class c = WebAPI.getSerializeService().getSupportedData().get(entry.getKey()); + if (c == null) continue; + Optional optData = item.getOrCreate(c); + if (!optData.isPresent()) + throw new IOException("Invalid item data: " + entry.getKey()); + DataManipulator data = optData.get(); + item.offer(data); + } + } + + return item; + } +} diff --git a/src/main/java/valandur/webapi/serialize/deserialize/ItemStackSnapshotDeserializer.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/ItemStackSnapshotDeserializer.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/deserialize/ItemStackSnapshotDeserializer.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/ItemStackSnapshotDeserializer.java index b9a1bf53..f9666ef9 100644 --- a/src/main/java/valandur/webapi/serialize/deserialize/ItemStackSnapshotDeserializer.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/deserialize/ItemStackSnapshotDeserializer.java @@ -1,62 +1,62 @@ -package valandur.webapi.serialize.deserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.data.manipulator.DataManipulator; -import org.spongepowered.api.item.ItemType; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import valandur.webapi.WebAPI; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Map; -import java.util.Optional; - -public class ItemStackSnapshotDeserializer extends StdDeserializer { - - - public ItemStackSnapshotDeserializer() { - super(ItemStackSnapshot.class); - } - - @Override - public ItemStackSnapshot deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - JsonNode root = p.readValueAsTree(); - if (root.path("type").isMissingNode()) - throw new IOException("Missing item type"); - - String id = root.path("type").isTextual() - ? root.path("type").asText() - : root.path("type").path("id").asText(); - Optional optType = Sponge.getRegistry().getType(ItemType.class, id); - if (!optType.isPresent()) - throw new IOException("Invalid item type " + id); - - Integer amount = root.path("quantity").isMissingNode() ? 1 : root.path("quantity").asInt(); - - ItemType type = optType.get(); - - ItemStack.Builder builder = ItemStack.builder().itemType(type).quantity(amount); - ItemStack item = builder.build(); - - if (!root.path("data").isMissingNode()) { - Iterator> it = root.path("data").fields(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - Class c = WebAPI.getSerializeService().getSupportedData().get(entry.getKey()); - if (c == null) continue; - Optional optData = item.getOrCreate(c); - if (!optData.isPresent()) - throw new IOException("Invalid item data: " + entry.getKey()); - DataManipulator data = optData.get(); - item.offer(data); - } - } - - return item.createSnapshot(); - } -} +package valandur.webapi.serialize.deserialize; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.data.manipulator.DataManipulator; +import org.spongepowered.api.item.ItemType; +import org.spongepowered.api.item.inventory.ItemStack; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import valandur.webapi.WebAPI; + +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; +import java.util.Optional; + +public class ItemStackSnapshotDeserializer extends StdDeserializer { + + + public ItemStackSnapshotDeserializer() { + super(ItemStackSnapshot.class); + } + + @Override + public ItemStackSnapshot deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + JsonNode root = p.readValueAsTree(); + if (root.path("type").isMissingNode()) + throw new IOException("Missing item type"); + + String id = root.path("type").isTextual() + ? root.path("type").asText() + : root.path("type").path("id").asText(); + Optional optType = Sponge.getRegistry().getType(ItemType.class, id); + if (!optType.isPresent()) + throw new IOException("Invalid item type " + id); + + Integer amount = root.path("quantity").isMissingNode() ? 1 : root.path("quantity").asInt(); + + ItemType type = optType.get(); + + ItemStack.Builder builder = ItemStack.builder().itemType(type).quantity(amount); + ItemStack item = builder.build(); + + if (!root.path("data").isMissingNode()) { + Iterator> it = root.path("data").fields(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + Class c = WebAPI.getSerializeService().getSupportedData().get(entry.getKey()); + if (c == null) continue; + Optional optData = item.getOrCreate(c); + if (!optData.isPresent()) + throw new IOException("Invalid item data: " + entry.getKey()); + DataManipulator data = optData.get(); + item.offer(data); + } + } + + return item.createSnapshot(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodParam.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodParam.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/objects/ExecuteMethodParam.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodParam.java index 23f0c8f5..db56a9bf 100644 --- a/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodParam.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodParam.java @@ -1,107 +1,107 @@ -package valandur.webapi.serialize.objects; - -import com.flowpowered.math.vector.Vector3d; -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.item.ItemType; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.util.Tuple; -import org.spongepowered.api.world.World; - -import java.lang.reflect.Field; -import java.util.Optional; -import java.util.UUID; - -@ApiModel("ExecuteMethodParam") -public class ExecuteMethodParam { - - public enum ParameterType { - INT, INTEGER, FLOAT, DOUBLE, BOOL, BOOLEAN, BYTE, CHAR, LONG, SHORT, STRING, CLASS, ENUM, - VECTOR3D, VECTOR3I, TEXT, WORLD, PLAYER, ITEMSTACK, STATIC, - } - - private ParameterType type; - @ApiModelProperty(value = "The type of the parameter", required = true) - public ParameterType getType() { - return type; - } - - private String value; - @ApiModelProperty(value = "The value of the parameter", required = true) - public String getValue() { - return value; - } - - - public Tuple toObject() - throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { - String val = value; - String[] vals = val.split(":"); - - switch (type) { - case INT: - case INTEGER: - return new Tuple<>(Integer.class, Integer.parseInt(val)); - case FLOAT: - return new Tuple<>(Float.class, Float.parseFloat(val)); - case DOUBLE: - return new Tuple<>(Double.class, Double.parseDouble(val)); - case BOOL: - case BOOLEAN: - return new Tuple<>(Boolean.class, Boolean.parseBoolean(val)); - case BYTE: - return new Tuple<>(Byte.class, Byte.parseByte(val)); - case CHAR: - return new Tuple<>(Character.class, val.charAt(0)); - case LONG: - return new Tuple<>(Long.class, Long.parseLong(val)); - case SHORT: - return new Tuple<>(Short.class, Short.parseShort(val)); - case STRING: - return new Tuple<>(String.class, val); - case CLASS: - return new Tuple<>(Class.class, Class.forName(val)); - case ENUM: - Class clazz = Class.forName(vals[0]); - return new Tuple(clazz, Enum.valueOf(clazz, vals[1])); - - case VECTOR3D: - return new Tuple<>(Vector3d.class, new Vector3d( - Double.parseDouble(vals[0]), Double.parseDouble(vals[1]), Double.parseDouble(vals[2]))); - - case VECTOR3I: - return new Tuple<>(Vector3i.class, new Vector3i( - Integer.parseInt(vals[0]), Integer.parseInt(vals[1]), Integer.parseInt(vals[2]))); - - case TEXT: - return new Tuple<>(Text.class, Text.of(val)); - - case WORLD: - Optional w = Sponge.getServer().getWorld(UUID.fromString(val)); - return new Tuple<>(World.class, w.orElse(null)); - - case PLAYER: - Optional p = Sponge.getServer().getPlayer(UUID.fromString(val)); - return new Tuple<>(Player.class, p.orElse(null)); - - case ITEMSTACK: - Optional t = Sponge.getRegistry().getType(ItemType.class, vals[0]); - if (!t.isPresent()) - throw new ClassNotFoundException(vals[0]); - - return new Tuple<>(ItemStack.class, ItemStack.of(t.get(), Integer.parseInt(vals[1]))); - - case STATIC: - Class c = Class.forName(vals[0]); - Field f = c.getField(vals[1]); - return new Tuple<>(f.getType(), f.get(null)); - - default: - return null; - } - } -} +package valandur.webapi.serialize.objects; + +import com.flowpowered.math.vector.Vector3d; +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.item.ItemType; +import org.spongepowered.api.item.inventory.ItemStack; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.util.Tuple; +import org.spongepowered.api.world.World; + +import java.lang.reflect.Field; +import java.util.Optional; +import java.util.UUID; + +@ApiModel("ExecuteMethodParam") +public class ExecuteMethodParam { + + public enum ParameterType { + INT, INTEGER, FLOAT, DOUBLE, BOOL, BOOLEAN, BYTE, CHAR, LONG, SHORT, STRING, CLASS, ENUM, + VECTOR3D, VECTOR3I, TEXT, WORLD, PLAYER, ITEMSTACK, STATIC, + } + + private ParameterType type; + @ApiModelProperty(value = "The type of the parameter", required = true) + public ParameterType getType() { + return type; + } + + private String value; + @ApiModelProperty(value = "The value of the parameter", required = true) + public String getValue() { + return value; + } + + + public Tuple toObject() + throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { + String val = value; + String[] vals = val.split(":"); + + switch (type) { + case INT: + case INTEGER: + return new Tuple<>(Integer.class, Integer.parseInt(val)); + case FLOAT: + return new Tuple<>(Float.class, Float.parseFloat(val)); + case DOUBLE: + return new Tuple<>(Double.class, Double.parseDouble(val)); + case BOOL: + case BOOLEAN: + return new Tuple<>(Boolean.class, Boolean.parseBoolean(val)); + case BYTE: + return new Tuple<>(Byte.class, Byte.parseByte(val)); + case CHAR: + return new Tuple<>(Character.class, val.charAt(0)); + case LONG: + return new Tuple<>(Long.class, Long.parseLong(val)); + case SHORT: + return new Tuple<>(Short.class, Short.parseShort(val)); + case STRING: + return new Tuple<>(String.class, val); + case CLASS: + return new Tuple<>(Class.class, Class.forName(val)); + case ENUM: + Class clazz = Class.forName(vals[0]); + return new Tuple(clazz, Enum.valueOf(clazz, vals[1])); + + case VECTOR3D: + return new Tuple<>(Vector3d.class, new Vector3d( + Double.parseDouble(vals[0]), Double.parseDouble(vals[1]), Double.parseDouble(vals[2]))); + + case VECTOR3I: + return new Tuple<>(Vector3i.class, new Vector3i( + Integer.parseInt(vals[0]), Integer.parseInt(vals[1]), Integer.parseInt(vals[2]))); + + case TEXT: + return new Tuple<>(Text.class, Text.of(val)); + + case WORLD: + Optional w = Sponge.getServer().getWorld(UUID.fromString(val)); + return new Tuple<>(World.class, w.orElse(null)); + + case PLAYER: + Optional p = Sponge.getServer().getPlayer(UUID.fromString(val)); + return new Tuple<>(Player.class, p.orElse(null)); + + case ITEMSTACK: + Optional t = Sponge.getRegistry().getType(ItemType.class, vals[0]); + if (!t.isPresent()) + throw new ClassNotFoundException(vals[0]); + + return new Tuple<>(ItemStack.class, ItemStack.of(t.get(), Integer.parseInt(vals[1]))); + + case STATIC: + Class c = Class.forName(vals[0]); + Field f = c.getField(vals[1]); + return new Tuple<>(f.getType(), f.get(null)); + + default: + return null; + } + } +} diff --git a/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodRequest.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodRequest.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/objects/ExecuteMethodRequest.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodRequest.java index 86968b4f..5bbb98a0 100644 --- a/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodRequest.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodRequest.java @@ -1,50 +1,50 @@ -package valandur.webapi.serialize.objects; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.util.Tuple; - -import javax.ws.rs.ForbiddenException; -import javax.ws.rs.NotFoundException; -import java.util.List; - -@ApiModel("ExecuteMethodRequest") -public class ExecuteMethodRequest { - - private String method; - @ApiModelProperty(value = "The method that is executed", required = true) - public String getMethod() { - return method; - } - - private List parameters; - @ApiModelProperty("The parameters of the method (if applicable)") - public List getParameters() { - return parameters; - } - - - @JsonIgnore - @ApiModelProperty(hidden = true) - public Tuple getParsedParameters() { - Class[] paramTypes = new Class[parameters.size()]; - Object[] paramValues = new Object[parameters.size()]; - - try { - for (int i = 0; i < parameters.size(); i++) { - Tuple tup = parameters.get(i).toObject(); - paramTypes[i] = tup.getFirst(); - paramValues[i] = tup.getSecond(); - } - } catch (ClassNotFoundException e) { - throw new NotFoundException("Class could not be found: " + e.getMessage()); - } catch (NoSuchFieldException e) { - throw new NotFoundException("Field could not be found: " + e.getMessage()); - } catch (IllegalAccessException e) { - throw new ForbiddenException("Access not allowed: " + e.getMessage()); - } - - return new Tuple<>(paramTypes, paramValues); - } -} +package valandur.webapi.serialize.objects; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.util.Tuple; + +import javax.ws.rs.ForbiddenException; +import javax.ws.rs.NotFoundException; +import java.util.List; + +@ApiModel("ExecuteMethodRequest") +public class ExecuteMethodRequest { + + private String method; + @ApiModelProperty(value = "The method that is executed", required = true) + public String getMethod() { + return method; + } + + private List parameters; + @ApiModelProperty("The parameters of the method (if applicable)") + public List getParameters() { + return parameters; + } + + + @JsonIgnore + @ApiModelProperty(hidden = true) + public Tuple getParsedParameters() { + Class[] paramTypes = new Class[parameters.size()]; + Object[] paramValues = new Object[parameters.size()]; + + try { + for (int i = 0; i < parameters.size(); i++) { + Tuple tup = parameters.get(i).toObject(); + paramTypes[i] = tup.getFirst(); + paramValues[i] = tup.getSecond(); + } + } catch (ClassNotFoundException e) { + throw new NotFoundException("Class could not be found: " + e.getMessage()); + } catch (NoSuchFieldException e) { + throw new NotFoundException("Field could not be found: " + e.getMessage()); + } catch (IllegalAccessException e) { + throw new ForbiddenException("Access not allowed: " + e.getMessage()); + } + + return new Tuple<>(paramTypes, paramValues); + } +} diff --git a/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodResponse.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodResponse.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/objects/ExecuteMethodResponse.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodResponse.java index 335f87ea..f5beba77 100644 --- a/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodResponse.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/objects/ExecuteMethodResponse.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.objects; - -import io.swagger.annotations.ApiModel; -import valandur.webapi.cache.CachedObject; - -@ApiModel("ExecuteMethodResponse") -public class ExecuteMethodResponse { - - private CachedObject object; - public CachedObject getObject() { - return object; - } - - private Object result; - public Object getResult() { - return result; - } - - - public ExecuteMethodResponse(CachedObject object, Object result) { - this.object = object; - this.result = result; - } -} +package valandur.webapi.serialize.objects; + +import io.swagger.annotations.ApiModel; +import valandur.webapi.cache.CachedObject; + +@ApiModel("ExecuteMethodResponse") +public class ExecuteMethodResponse { + + private CachedObject object; + public CachedObject getObject() { + return object; + } + + private Object result; + public Object getResult() { + return result; + } + + + public ExecuteMethodResponse(CachedObject object, Object result) { + this.object = object; + this.result = result; + } +} diff --git a/src/main/java/valandur/webapi/serialize/param/ParamConverterProvider.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/ParamConverterProvider.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/param/ParamConverterProvider.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/param/ParamConverterProvider.java index 714a1864..fab6100f 100644 --- a/src/main/java/valandur/webapi/serialize/param/ParamConverterProvider.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/ParamConverterProvider.java @@ -1,29 +1,29 @@ -package valandur.webapi.serialize.param; - -import com.flowpowered.math.vector.Vector3d; -import com.flowpowered.math.vector.Vector3i; -import valandur.webapi.cache.player.CachedPlayer; -import valandur.webapi.cache.world.CachedWorld; - -import javax.ws.rs.ext.ParamConverter; -import javax.ws.rs.ext.Provider; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; - -@Provider -public class ParamConverterProvider implements javax.ws.rs.ext.ParamConverterProvider { - - @Override - public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { - if (CachedWorld.class.isAssignableFrom(rawType)) { - return (ParamConverter) new WorldParamConverter(); - } else if (CachedPlayer.class.isAssignableFrom(rawType)) { - return (ParamConverter) new PlayerParamConverter(); - } else if (Vector3d.class.isAssignableFrom(rawType)) { - return (ParamConverter) new Vector3dParamConverter(); - } else if (Vector3i.class.isAssignableFrom(rawType)) { - return (ParamConverter) new Vector3iParamConverter(); - } - return null; - } -} +package valandur.webapi.serialize.param; + +import com.flowpowered.math.vector.Vector3d; +import com.flowpowered.math.vector.Vector3i; +import valandur.webapi.cache.player.CachedPlayer; +import valandur.webapi.cache.world.CachedWorld; + +import javax.ws.rs.ext.ParamConverter; +import javax.ws.rs.ext.Provider; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +@Provider +public class ParamConverterProvider implements javax.ws.rs.ext.ParamConverterProvider { + + @Override + public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { + if (CachedWorld.class.isAssignableFrom(rawType)) { + return (ParamConverter) new WorldParamConverter(); + } else if (CachedPlayer.class.isAssignableFrom(rawType)) { + return (ParamConverter) new PlayerParamConverter(); + } else if (Vector3d.class.isAssignableFrom(rawType)) { + return (ParamConverter) new Vector3dParamConverter(); + } else if (Vector3i.class.isAssignableFrom(rawType)) { + return (ParamConverter) new Vector3iParamConverter(); + } + return null; + } +} diff --git a/src/main/java/valandur/webapi/serialize/param/PlayerParamConverter.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/PlayerParamConverter.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/param/PlayerParamConverter.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/param/PlayerParamConverter.java index 91d0ee3a..cad1c44f 100644 --- a/src/main/java/valandur/webapi/serialize/param/PlayerParamConverter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/PlayerParamConverter.java @@ -1,37 +1,37 @@ -package valandur.webapi.serialize.param; - -import valandur.webapi.WebAPI; -import valandur.webapi.cache.CacheService; -import valandur.webapi.cache.player.CachedPlayer; -import valandur.webapi.util.Util; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.ext.ParamConverter; -import java.util.Optional; -import java.util.UUID; - -public class PlayerParamConverter implements ParamConverter { - - @Override - public CachedPlayer fromString(String value) { - // If we didn't request a player don't try to find one - if (value == null) - return null; - - if (!Util.isValidUUID(value)) - throw new BadRequestException("Invalid player/user uuid"); - - CacheService srv = WebAPI.getCacheService(); - - Optional optPlayer = srv.getPlayer(UUID.fromString(value)); - if (!optPlayer.isPresent()) - throw new NotFoundException("Could not find player/user with uuid " + value); - return optPlayer.get(); - } - - @Override - public String toString(CachedPlayer value) { - return value.getLink(); - } -} +package valandur.webapi.serialize.param; + +import valandur.webapi.WebAPI; +import valandur.webapi.cache.CacheService; +import valandur.webapi.cache.player.CachedPlayer; +import valandur.webapi.util.Util; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.ext.ParamConverter; +import java.util.Optional; +import java.util.UUID; + +public class PlayerParamConverter implements ParamConverter { + + @Override + public CachedPlayer fromString(String value) { + // If we didn't request a player don't try to find one + if (value == null) + return null; + + if (!Util.isValidUUID(value)) + throw new BadRequestException("Invalid player/user uuid"); + + CacheService srv = WebAPI.getCacheService(); + + Optional optPlayer = srv.getPlayer(UUID.fromString(value)); + if (!optPlayer.isPresent()) + throw new NotFoundException("Could not find player/user with uuid " + value); + return optPlayer.get(); + } + + @Override + public String toString(CachedPlayer value) { + return value.getLink(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/param/Vector3dParamConverter.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/Vector3dParamConverter.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/param/Vector3dParamConverter.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/param/Vector3dParamConverter.java index 01b938f0..73bdde94 100644 --- a/src/main/java/valandur/webapi/serialize/param/Vector3dParamConverter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/Vector3dParamConverter.java @@ -1,35 +1,35 @@ -package valandur.webapi.serialize.param; - -import com.flowpowered.math.vector.Vector3d; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.ext.ParamConverter; - -public class Vector3dParamConverter implements ParamConverter { - - @Override - public Vector3d fromString(String value) { - // If we didn't specify a vector3d don't try to parse one - if (value == null) - return null; - - String[] splits = value.split("\\|"); - if (splits.length < 3) { - throw new BadRequestException("Invalid Vector3d"); - } - - try { - double x = Double.parseDouble(splits[0]); - double y = Double.parseDouble(splits[1]); - double z = Double.parseDouble(splits[2]); - return new Vector3d(x, y, z); - } catch (NumberFormatException e) { - throw new BadRequestException(e.getMessage()); - } - } - - @Override - public String toString(Vector3d value) { - return value.getX() + "|" + value.getY() + "|" + value.getZ(); - } -} +package valandur.webapi.serialize.param; + +import com.flowpowered.math.vector.Vector3d; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.ext.ParamConverter; + +public class Vector3dParamConverter implements ParamConverter { + + @Override + public Vector3d fromString(String value) { + // If we didn't specify a vector3d don't try to parse one + if (value == null) + return null; + + String[] splits = value.split("\\|"); + if (splits.length < 3) { + throw new BadRequestException("Invalid Vector3d"); + } + + try { + double x = Double.parseDouble(splits[0]); + double y = Double.parseDouble(splits[1]); + double z = Double.parseDouble(splits[2]); + return new Vector3d(x, y, z); + } catch (NumberFormatException e) { + throw new BadRequestException(e.getMessage()); + } + } + + @Override + public String toString(Vector3d value) { + return value.getX() + "|" + value.getY() + "|" + value.getZ(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/param/Vector3iParamConverter.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/Vector3iParamConverter.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/param/Vector3iParamConverter.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/param/Vector3iParamConverter.java index 8701e6a4..356b0d95 100644 --- a/src/main/java/valandur/webapi/serialize/param/Vector3iParamConverter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/Vector3iParamConverter.java @@ -1,35 +1,35 @@ -package valandur.webapi.serialize.param; - -import com.flowpowered.math.vector.Vector3i; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.ext.ParamConverter; - -public class Vector3iParamConverter implements ParamConverter { - - @Override - public Vector3i fromString(String value) { - // If we didn't specify a vector3i don't try to parse one - if (value == null) - return null; - - String[] splits = value.split("\\|"); - if (splits.length < 3) { - throw new BadRequestException("Invalid Vector3i"); - } - - try { - int x = Integer.parseInt(splits[0]); - int y = Integer.parseInt(splits[1]); - int z = Integer.parseInt(splits[2]); - return new Vector3i(x, y, z); - } catch (NumberFormatException e) { - throw new BadRequestException(e.getMessage()); - } - } - - @Override - public String toString(Vector3i value) { - return value.getX() + "|" + value.getY() + "|" + value.getZ(); - } -} +package valandur.webapi.serialize.param; + +import com.flowpowered.math.vector.Vector3i; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.ext.ParamConverter; + +public class Vector3iParamConverter implements ParamConverter { + + @Override + public Vector3i fromString(String value) { + // If we didn't specify a vector3i don't try to parse one + if (value == null) + return null; + + String[] splits = value.split("\\|"); + if (splits.length < 3) { + throw new BadRequestException("Invalid Vector3i"); + } + + try { + int x = Integer.parseInt(splits[0]); + int y = Integer.parseInt(splits[1]); + int z = Integer.parseInt(splits[2]); + return new Vector3i(x, y, z); + } catch (NumberFormatException e) { + throw new BadRequestException(e.getMessage()); + } + } + + @Override + public String toString(Vector3i value) { + return value.getX() + "|" + value.getY() + "|" + value.getZ(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/param/WorldParamConverter.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/WorldParamConverter.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/param/WorldParamConverter.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/param/WorldParamConverter.java index 07cd5186..d6855902 100644 --- a/src/main/java/valandur/webapi/serialize/param/WorldParamConverter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/param/WorldParamConverter.java @@ -1,37 +1,37 @@ -package valandur.webapi.serialize.param; - -import valandur.webapi.WebAPI; -import valandur.webapi.cache.CacheService; -import valandur.webapi.cache.world.CachedWorld; -import valandur.webapi.util.Util; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.ext.ParamConverter; -import java.util.Optional; -import java.util.UUID; - -public class WorldParamConverter implements ParamConverter { - - @Override - public CachedWorld fromString(String value) { - // If we didn't request a world don't try to find one - if (value == null) - return null; - - if (!Util.isValidUUID(value)) - throw new BadRequestException("Invalid world uuid"); - - CacheService srv = WebAPI.getCacheService(); - - Optional optWorld = srv.getWorld(UUID.fromString(value)); - if (!optWorld.isPresent()) - throw new NotFoundException("Could not find world with uuid " + value); - return optWorld.get(); - } - - @Override - public String toString(CachedWorld value) { - return value.getLink(); - } -} +package valandur.webapi.serialize.param; + +import valandur.webapi.WebAPI; +import valandur.webapi.cache.CacheService; +import valandur.webapi.cache.world.CachedWorld; +import valandur.webapi.util.Util; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.ext.ParamConverter; +import java.util.Optional; +import java.util.UUID; + +public class WorldParamConverter implements ParamConverter { + + @Override + public CachedWorld fromString(String value) { + // If we didn't request a world don't try to find one + if (value == null) + return null; + + if (!Util.isValidUUID(value)) + throw new BadRequestException("Invalid world uuid"); + + CacheService srv = WebAPI.getCacheService(); + + Optional optWorld = srv.getWorld(UUID.fromString(value)); + if (!optWorld.isPresent()) + throw new NotFoundException("Could not find world with uuid " + value); + return optWorld.get(); + } + + @Override + public String toString(CachedWorld value) { + return value.getLink(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/block/BlockSnapshotView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/block/BlockSnapshotView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/block/BlockSnapshotView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/block/BlockSnapshotView.java index fa6ff20a..c89ca57c 100644 --- a/src/main/java/valandur/webapi/serialize/view/block/BlockSnapshotView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/block/BlockSnapshotView.java @@ -1,33 +1,33 @@ -package valandur.webapi.serialize.view.block; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.block.BlockSnapshot; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; -import valandur.webapi.serialize.BaseView; - -import java.util.UUID; - -@ApiModel("BlockSnapshot") -public class BlockSnapshotView extends BaseView { - - @ApiModelProperty("The creator of this snapshot") - public UUID creator; - - @ApiModelProperty("The location of the snapshot") - public Location location; - - @ApiModelProperty(value = "The block state that was captured", required = true) - public BlockState state; - - - public BlockSnapshotView(BlockSnapshot value) { - super(value); - - this.creator = value.getCreator().orElse(null); - this.location = value.getLocation().orElse(null); - this.state = value.getState(); - } -} +package valandur.webapi.serialize.view.block; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.block.BlockSnapshot; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.world.Location; +import org.spongepowered.api.world.World; +import valandur.webapi.serialize.BaseView; + +import java.util.UUID; + +@ApiModel("BlockSnapshot") +public class BlockSnapshotView extends BaseView { + + @ApiModelProperty("The creator of this snapshot") + public UUID creator; + + @ApiModelProperty("The location of the snapshot") + public Location location; + + @ApiModelProperty(value = "The block state that was captured", required = true) + public BlockState state; + + + public BlockSnapshotView(BlockSnapshot value) { + super(value); + + this.creator = value.getCreator().orElse(null); + this.location = value.getLocation().orElse(null); + this.state = value.getState(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/block/BlockStateView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/block/BlockStateView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/block/BlockStateView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/block/BlockStateView.java index 055e2f50..3b851e56 100644 --- a/src/main/java/valandur/webapi/serialize/view/block/BlockStateView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/block/BlockStateView.java @@ -1,57 +1,57 @@ -package valandur.webapi.serialize.view.block; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.block.trait.BlockTrait; -import org.spongepowered.api.data.manipulator.DataManipulator; -import valandur.webapi.WebAPI; -import valandur.webapi.serialize.BaseView; -import valandur.webapi.serialize.JsonDetails; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -@ApiModel("BlockState") -public class BlockStateView extends BaseView { - - @ApiModelProperty(value = "The type of block this block state is from") - public BlockType getType() { - return value.getType(); - } - - public void setType(String type) { } - - - public BlockStateView(BlockState value) { - super(value); - } - - @JsonDetails - @ApiModelProperty("Additional data attached to the block state") - public Map getData() { - HashMap data = new HashMap<>(); - // Add traits - for (Map.Entry, ?> entry : value.getTraitMap().entrySet()) { - data.put(entry.getKey().getName(), entry.getValue()); - } - // Add data - Map>> supData = WebAPI.getSerializeService().getSupportedData(); - for (Map.Entry>> entry : supData.entrySet()) { - try { - Optional m = value.getManipulators().stream() - .filter(i -> i.asMutable().getClass().equals(entry.getValue())) - .findFirst(); - - if (!m.isPresent()) - continue; - - data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); - } catch (IllegalArgumentException | IllegalStateException ignored) { - } - } - return data; - } -} +package valandur.webapi.serialize.view.block; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.block.BlockType; +import org.spongepowered.api.block.trait.BlockTrait; +import org.spongepowered.api.data.manipulator.DataManipulator; +import valandur.webapi.WebAPI; +import valandur.webapi.serialize.BaseView; +import valandur.webapi.serialize.JsonDetails; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +@ApiModel("BlockState") +public class BlockStateView extends BaseView { + + @ApiModelProperty(value = "The type of block this block state is from") + public BlockType getType() { + return value.getType(); + } + + public void setType(String type) { } + + + public BlockStateView(BlockState value) { + super(value); + } + + @JsonDetails + @ApiModelProperty("Additional data attached to the block state") + public Map getData() { + HashMap data = new HashMap<>(); + // Add traits + for (Map.Entry, ?> entry : value.getTraitMap().entrySet()) { + data.put(entry.getKey().getName(), entry.getValue()); + } + // Add data + Map>> supData = WebAPI.getSerializeService().getSupportedData(); + for (Map.Entry>> entry : supData.entrySet()) { + try { + Optional m = value.getManipulators().stream() + .filter(i -> i.asMutable().getClass().equals(entry.getValue())) + .findFirst(); + + if (!m.isPresent()) + continue; + + data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); + } catch (IllegalArgumentException | IllegalStateException ignored) { + } + } + return data; + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/AbsorptionDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AbsorptionDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/AbsorptionDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AbsorptionDataView.java index 0db4048f..a4a8593a 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AbsorptionDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AbsorptionDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.AbsorptionData; -import valandur.webapi.serialize.BaseView; - -public class AbsorptionDataView extends BaseView { - - @JsonValue - public double abs; - - - public AbsorptionDataView(AbsorptionData value) { - super(value); - - this.abs = value.absorption().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.AbsorptionData; +import valandur.webapi.serialize.BaseView; + +public class AbsorptionDataView extends BaseView { + + @JsonValue + public double abs; + + + public AbsorptionDataView(AbsorptionData value) { + super(value); + + this.abs = value.absorption().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/AchievementDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AchievementDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/AchievementDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AchievementDataView.java index e9500d5a..1c6c29e0 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AchievementDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AchievementDataView.java @@ -1,22 +1,22 @@ -/*package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.AchievementData; -import org.spongepowered.api.statistic.achievement.Achievement; -import valandur.webapi.api.serialize.BaseView; - -import java.util.Set; - -public class AchievementDataView extends BaseView { - - @JsonValue - public Set achievements; - - - public AchievementDataView(AchievementData value) { - super(value); - - this.achievements = value.achievements().get(); - } -} +/*package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.AchievementData; +import org.spongepowered.api.statistic.achievement.Achievement; +import valandur.webapi.api.serialize.BaseView; + +import java.util.Set; + +public class AchievementDataView extends BaseView { + + @JsonValue + public Set achievements; + + + public AchievementDataView(AchievementData value) { + super(value); + + this.achievements = value.achievements().get(); + } +} */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/serialize/view/data/AgeableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AgeableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/AgeableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AgeableDataView.java index 030e668b..e7b30a63 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AgeableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AgeableDataView.java @@ -1,23 +1,23 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.AgeableData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("AgeableData") -public class AgeableDataView extends BaseView { - - @ApiModelProperty(value = "True if this entity is an adult, false otherwise", required = true) - public boolean adult; - - @ApiModelProperty(value = "The age of the entity", required = true) - public int age; - - public AgeableDataView(AgeableData value) { - super(value); - - this.adult = value.adult().get(); - this.age = value.age().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.AgeableData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("AgeableData") +public class AgeableDataView extends BaseView { + + @ApiModelProperty(value = "True if this entity is an adult, false otherwise", required = true) + public boolean adult; + + @ApiModelProperty(value = "The age of the entity", required = true) + public int age; + + public AgeableDataView(AgeableData value) { + super(value); + + this.adult = value.adult().get(); + this.age = value.age().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/AgentDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AgentDataView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/data/AgentDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AgentDataView.java index 6e5ad10c..cd33e6c2 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AgentDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AgentDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.AgentData; -import valandur.webapi.serialize.BaseView; - -public class AgentDataView extends BaseView { - - @JsonValue - public boolean ai; - - - public AgentDataView(AgentData value) { - super(value); - - this.ai = value.aiEnabled().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.AgentData; +import valandur.webapi.serialize.BaseView; + +public class AgentDataView extends BaseView { + + @JsonValue + public boolean ai; + + + public AgentDataView(AgentData value) { + super(value); + + this.ai = value.aiEnabled().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/AggressiveDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AggressiveDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/AggressiveDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AggressiveDataView.java index e593f4d6..b6bc55d1 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AggressiveDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AggressiveDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.AggressiveData; -import valandur.webapi.serialize.BaseView; - -public class AggressiveDataView extends BaseView { - - @JsonValue - public boolean aggressive; - - - public AggressiveDataView(AggressiveData value) { - super(value); - - this.aggressive = value.aggressive().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.AggressiveData; +import valandur.webapi.serialize.BaseView; + +public class AggressiveDataView extends BaseView { + + @JsonValue + public boolean aggressive; + + + public AggressiveDataView(AggressiveData value) { + super(value); + + this.aggressive = value.aggressive().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/AngerableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AngerableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/AngerableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AngerableDataView.java index f68d0832..1c9dfbee 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AngerableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AngerableDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.AngerableData; -import valandur.webapi.serialize.BaseView; - -public class AngerableDataView extends BaseView { - - @JsonValue - public int anger; - - - public AngerableDataView(AngerableData value) { - super(value); - - this.anger = value.angerLevel().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.AngerableData; +import valandur.webapi.serialize.BaseView; + +public class AngerableDataView extends BaseView { + + @JsonValue + public int anger; + + + public AngerableDataView(AngerableData value) { + super(value); + + this.anger = value.angerLevel().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ArmorStandDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ArmorStandDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/ArmorStandDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ArmorStandDataView.java index 3be01f0f..2d676377 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ArmorStandDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ArmorStandDataView.java @@ -1,32 +1,32 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.ArmorStandData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("ArmorStandData") -public class ArmorStandDataView extends BaseView { - - @ApiModelProperty(value = "True if the armor stand has arms, false otherwise", required = true) - public boolean arms; - - @ApiModelProperty(value = "True if the armor stand has a base plate, false otherwise", required = true) - public boolean basePlate; - - @ApiModelProperty(value = "True if the armor stand has a marker, false otherwise", required = true) - public boolean marker; - - @ApiModelProperty(value = "True if the armor stand is small, false otherwise", required = true) - public boolean small; - - - public ArmorStandDataView(ArmorStandData value) { - super(value); - - this.arms = value.arms().get(); - this.basePlate = value.basePlate().get(); - this.marker = value.marker().get(); - this.small = value.small().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.ArmorStandData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("ArmorStandData") +public class ArmorStandDataView extends BaseView { + + @ApiModelProperty(value = "True if the armor stand has arms, false otherwise", required = true) + public boolean arms; + + @ApiModelProperty(value = "True if the armor stand has a base plate, false otherwise", required = true) + public boolean basePlate; + + @ApiModelProperty(value = "True if the armor stand has a marker, false otherwise", required = true) + public boolean marker; + + @ApiModelProperty(value = "True if the armor stand is small, false otherwise", required = true) + public boolean small; + + + public ArmorStandDataView(ArmorStandData value) { + super(value); + + this.arms = value.arms().get(); + this.basePlate = value.basePlate().get(); + this.marker = value.marker().get(); + this.small = value.small().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/AttachedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AttachedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/AttachedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AttachedDataView.java index 467ccaa7..2f34972b 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AttachedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AttachedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.AttachedData; -import valandur.webapi.serialize.BaseView; - -public class AttachedDataView extends BaseView { - - @JsonValue - public boolean attached; - - - public AttachedDataView(AttachedData value) { - super(value); - - this.attached = value.attached().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.AttachedData; +import valandur.webapi.serialize.BaseView; + +public class AttachedDataView extends BaseView { + + @JsonValue + public boolean attached; + + + public AttachedDataView(AttachedData value) { + super(value); + + this.attached = value.attached().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/AuthorDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AuthorDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/AuthorDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AuthorDataView.java index 588e6acf..47aaf148 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/AuthorDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/AuthorDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.item.AuthorData; -import org.spongepowered.api.text.Text; -import valandur.webapi.serialize.BaseView; - -public class AuthorDataView extends BaseView { - - @JsonValue - public Text getAuthor() { - return value.author().get(); - } - - - public AuthorDataView(AuthorData value) { - super(value); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.item.AuthorData; +import org.spongepowered.api.text.Text; +import valandur.webapi.serialize.BaseView; + +public class AuthorDataView extends BaseView { + + @JsonValue + public Text getAuthor() { + return value.author().get(); + } + + + public AuthorDataView(AuthorData value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/BannerDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BannerDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/BannerDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BannerDataView.java index 06b1a5cf..94fdbe42 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/BannerDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BannerDataView.java @@ -1,28 +1,28 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.tileentity.BannerData; -import org.spongepowered.api.data.meta.PatternLayer; -import org.spongepowered.api.data.type.DyeColor; -import valandur.webapi.serialize.BaseView; - -import java.util.List; - -@ApiModel("BannerData") -public class BannerDataView extends BaseView { - - @ApiModelProperty(value = "The color of the banner", required = true) - public DyeColor color; - - @ApiModelProperty(value = "The patterns on the banner", required = true) - public List patterns; - - - public BannerDataView(BannerData value) { - super(value); - - this.color = value.baseColor().get(); - this.patterns = value.patternsList().getAll(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.tileentity.BannerData; +import org.spongepowered.api.data.meta.PatternLayer; +import org.spongepowered.api.data.type.DyeColor; +import valandur.webapi.serialize.BaseView; + +import java.util.List; + +@ApiModel("BannerData") +public class BannerDataView extends BaseView { + + @ApiModelProperty(value = "The color of the banner", required = true) + public DyeColor color; + + @ApiModelProperty(value = "The patterns on the banner", required = true) + public List patterns; + + + public BannerDataView(BannerData value) { + super(value); + + this.color = value.baseColor().get(); + this.patterns = value.patternsList().getAll(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/BeaconDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BeaconDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/BeaconDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BeaconDataView.java index f451914e..2f3e904c 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/BeaconDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BeaconDataView.java @@ -1,25 +1,25 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.tileentity.BeaconData; -import org.spongepowered.api.effect.potion.PotionEffectType; -import valandur.webapi.serialize.BaseView; - -@ApiModel("BeaconData") -public class BeaconDataView extends BaseView { - - @ApiModelProperty("The primary effect of the beacon") - public PotionEffectType primary; - - @ApiModelProperty("The secondary effect of the beacon") - public PotionEffectType secondary; - - - public BeaconDataView(BeaconData value) { - super(value); - - this.primary = value.primaryEffect().get().orElse(null); - this.secondary = value.secondaryEffect().get().orElse(null); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.tileentity.BeaconData; +import org.spongepowered.api.effect.potion.PotionEffectType; +import valandur.webapi.serialize.BaseView; + +@ApiModel("BeaconData") +public class BeaconDataView extends BaseView { + + @ApiModelProperty("The primary effect of the beacon") + public PotionEffectType primary; + + @ApiModelProperty("The secondary effect of the beacon") + public PotionEffectType secondary; + + + public BeaconDataView(BeaconData value) { + super(value); + + this.primary = value.primaryEffect().get().orElse(null); + this.secondary = value.secondaryEffect().get().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/BlockItemDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BlockItemDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/BlockItemDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BlockItemDataView.java index f0c9e681..b0182853 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/BlockItemDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BlockItemDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.data.manipulator.mutable.item.BlockItemData; -import valandur.webapi.serialize.BaseView; - -public class BlockItemDataView extends BaseView { - - @JsonValue - public BlockState state; - - - public BlockItemDataView(BlockItemData value) { - super(value); - - this.state = value.state().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.data.manipulator.mutable.item.BlockItemData; +import valandur.webapi.serialize.BaseView; + +public class BlockItemDataView extends BaseView { + + @JsonValue + public BlockState state; + + + public BlockItemDataView(BlockItemData value) { + super(value); + + this.state = value.state().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/BreathingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BreathingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/BreathingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BreathingDataView.java index 452bb193..cc8136f7 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/BreathingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BreathingDataView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.BreathingData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("BreathingData") -public class BreathingDataView extends BaseView { - - @ApiModelProperty(value = "The maximum amount of air available to this entity", required = true) - public int max; - - @ApiModelProperty(value = "The amount of air currently remaining", required = true) - public int remaining; - - - public BreathingDataView(BreathingData value) { - super(value); - - this.max = value.maxAir().get(); - this.remaining = value.remainingAir().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.BreathingData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("BreathingData") +public class BreathingDataView extends BaseView { + + @ApiModelProperty(value = "The maximum amount of air available to this entity", required = true) + public int max; + + @ApiModelProperty(value = "The amount of air currently remaining", required = true) + public int remaining; + + + public BreathingDataView(BreathingData value) { + super(value); + + this.max = value.maxAir().get(); + this.remaining = value.remainingAir().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/BreedableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BreedableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/BreedableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BreedableDataView.java index 1c48f832..f0a89517 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/BreedableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BreedableDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.BreedableData; -import valandur.webapi.serialize.BaseView; - -public class BreedableDataView extends BaseView { - - @JsonValue - public boolean breedable; - - - public BreedableDataView(BreedableData value) { - super(value); - - this.breedable = value.breedable().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.BreedableData; +import valandur.webapi.serialize.BaseView; + +public class BreedableDataView extends BaseView { + + @JsonValue + public boolean breedable; + + + public BreedableDataView(BreedableData value) { + super(value); + + this.breedable = value.breedable().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/BrewingStandDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BrewingStandDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/BrewingStandDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BrewingStandDataView.java index 3c67051a..1341b0c2 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/BrewingStandDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/BrewingStandDataView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.tileentity.BrewingStandData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("BrewingStandData") -public class BrewingStandDataView extends BaseView { - - @ApiModelProperty(value = "The time remaining until brewing is complete", required = true) - public int remainingBrewTime; - - - public BrewingStandDataView(BrewingStandData value) { - super(value); - - this.remainingBrewTime = value.remainingBrewTime().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.tileentity.BrewingStandData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("BrewingStandData") +public class BrewingStandDataView extends BaseView { + + @ApiModelProperty(value = "The time remaining until brewing is complete", required = true) + public int remainingBrewTime; + + + public BrewingStandDataView(BrewingStandData value) { + super(value); + + this.remainingBrewTime = value.remainingBrewTime().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ChargedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ChargedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ChargedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ChargedDataView.java index d386e7dd..be081ec6 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ChargedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ChargedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.ChargedData; -import valandur.webapi.serialize.BaseView; - -public class ChargedDataView extends BaseView { - - @JsonValue - public boolean charged; - - - public ChargedDataView(ChargedData value) { - super(value); - - this.charged = value.charged().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.ChargedData; +import valandur.webapi.serialize.BaseView; + +public class ChargedDataView extends BaseView { + + @JsonValue + public boolean charged; + + + public ChargedDataView(ChargedData value) { + super(value); + + this.charged = value.charged().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ColoredDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ColoredDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ColoredDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ColoredDataView.java index 31c66604..2b622ab0 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ColoredDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ColoredDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.ColoredData; -import org.spongepowered.api.util.Color; -import valandur.webapi.serialize.BaseView; - -public class ColoredDataView extends BaseView { - - @JsonValue - public Color color; - - - public ColoredDataView(ColoredData value) { - super(value); - - this.color = value.color().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.ColoredData; +import org.spongepowered.api.util.Color; +import valandur.webapi.serialize.BaseView; + +public class ColoredDataView extends BaseView { + + @JsonValue + public Color color; + + + public ColoredDataView(ColoredData value) { + super(value); + + this.color = value.color().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/CommandDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CommandDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/CommandDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CommandDataView.java index 38eb1550..dfb1af7c 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/CommandDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CommandDataView.java @@ -1,33 +1,33 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.CommandData; -import org.spongepowered.api.text.Text; -import valandur.webapi.serialize.BaseView; - -@ApiModel("CommandData") -public class CommandDataView extends BaseView { - - @ApiModelProperty(value = "True if the output is tracked, false otherwise", required = true) - public boolean tracksOutput; - - @ApiModelProperty("The last output produced") - public Text lastOutput; - - @ApiModelProperty(value = "The stored command", required = true) - public String storedCommand; - - @ApiModelProperty(value = "The amount of successfull executions", required = true) - public int successCount; - - - public CommandDataView(CommandData value) { - super(value); - - this.tracksOutput = value.doesTrackOutput().get(); - this.lastOutput = value.lastOutput().get().orElse(null); - this.storedCommand = value.storedCommand().get(); - this.successCount = value.successCount().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.CommandData; +import org.spongepowered.api.text.Text; +import valandur.webapi.serialize.BaseView; + +@ApiModel("CommandData") +public class CommandDataView extends BaseView { + + @ApiModelProperty(value = "True if the output is tracked, false otherwise", required = true) + public boolean tracksOutput; + + @ApiModelProperty("The last output produced") + public Text lastOutput; + + @ApiModelProperty(value = "The stored command", required = true) + public String storedCommand; + + @ApiModelProperty(value = "The amount of successfull executions", required = true) + public int successCount; + + + public CommandDataView(CommandData value) { + super(value); + + this.tracksOutput = value.doesTrackOutput().get(); + this.lastOutput = value.lastOutput().get().orElse(null); + this.storedCommand = value.storedCommand().get(); + this.successCount = value.successCount().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ConnectedDirectionDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ConnectedDirectionDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ConnectedDirectionDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ConnectedDirectionDataView.java index c23257ea..bb359f1e 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ConnectedDirectionDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ConnectedDirectionDataView.java @@ -1,22 +1,22 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.ConnectedDirectionData; -import org.spongepowered.api.util.Direction; -import valandur.webapi.serialize.BaseView; - -import java.util.ArrayList; -import java.util.List; - -public class ConnectedDirectionDataView extends BaseView { - - @JsonValue - public List directions; - - - public ConnectedDirectionDataView(ConnectedDirectionData value) { - super(value); - - this.directions = new ArrayList<>(value.connectedDirections().get()); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.ConnectedDirectionData; +import org.spongepowered.api.util.Direction; +import valandur.webapi.serialize.BaseView; + +import java.util.ArrayList; +import java.util.List; + +public class ConnectedDirectionDataView extends BaseView { + + @JsonValue + public List directions; + + + public ConnectedDirectionDataView(ConnectedDirectionData value) { + super(value); + + this.directions = new ArrayList<>(value.connectedDirections().get()); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/CooldownDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CooldownDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/CooldownDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CooldownDataView.java index bcffd547..c70cd76f 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/CooldownDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CooldownDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.tileentity.CooldownData; -import valandur.webapi.serialize.BaseView; - -public class CooldownDataView extends BaseView { - - @JsonValue - public int cooldown; - - - public CooldownDataView(CooldownData value) { - super(value); - - this.cooldown = value.cooldown().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.tileentity.CooldownData; +import valandur.webapi.serialize.BaseView; + +public class CooldownDataView extends BaseView { + + @JsonValue + public int cooldown; + + + public CooldownDataView(CooldownData value) { + super(value); + + this.cooldown = value.cooldown().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/CriticalHitDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CriticalHitDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/CriticalHitDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CriticalHitDataView.java index d7955e20..e8fa9550 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/CriticalHitDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CriticalHitDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.CriticalHitData; -import valandur.webapi.serialize.BaseView; - -public class CriticalHitDataView extends BaseView { - - @JsonValue - public boolean criticalHit; - - - public CriticalHitDataView(CriticalHitData value) { - super(value); - - this.criticalHit = value.criticalHit().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.CriticalHitData; +import valandur.webapi.serialize.BaseView; + +public class CriticalHitDataView extends BaseView { + + @JsonValue + public boolean criticalHit; + + + public CriticalHitDataView(CriticalHitData value) { + super(value); + + this.criticalHit = value.criticalHit().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/CustomNameVisibleDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CustomNameVisibleDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/CustomNameVisibleDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CustomNameVisibleDataView.java index 6f518b48..1019d8e3 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/CustomNameVisibleDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/CustomNameVisibleDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.CustomNameVisibleData; -import valandur.webapi.serialize.BaseView; - -public class CustomNameVisibleDataView extends BaseView { - - @JsonValue - public boolean visible; - - - public CustomNameVisibleDataView(CustomNameVisibleData value) { - super(value); - - this.visible = value.customNameVisible().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.CustomNameVisibleData; +import valandur.webapi.serialize.BaseView; + +public class CustomNameVisibleDataView extends BaseView { + + @JsonValue + public boolean visible; + + + public CustomNameVisibleDataView(CustomNameVisibleData value) { + super(value); + + this.visible = value.customNameVisible().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DamageableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DamageableDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/DamageableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DamageableDataView.java index de3d9eee..56b5c889 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DamageableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DamageableDataView.java @@ -1,25 +1,25 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.DamageableData; -import org.spongepowered.api.entity.EntitySnapshot; -import valandur.webapi.serialize.BaseView; - -@ApiModel("DamageableData") -public class DamageableDataView extends BaseView { - - @ApiModelProperty("The entity which last attacked this entity") - public EntitySnapshot lastAttacker; - - @ApiModelProperty("The amount of damage inflicted by the last attacker") - public Double lastDamage; - - - public DamageableDataView(DamageableData value) { - super(value); - - this.lastAttacker = value.lastAttacker().get().orElse(null); - this.lastDamage = value.lastDamage().get().orElse(null); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.DamageableData; +import org.spongepowered.api.entity.EntitySnapshot; +import valandur.webapi.serialize.BaseView; + +@ApiModel("DamageableData") +public class DamageableDataView extends BaseView { + + @ApiModelProperty("The entity which last attacked this entity") + public EntitySnapshot lastAttacker; + + @ApiModelProperty("The amount of damage inflicted by the last attacker") + public Double lastDamage; + + + public DamageableDataView(DamageableData value) { + super(value); + + this.lastAttacker = value.lastAttacker().get().orElse(null); + this.lastDamage = value.lastDamage().get().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DamagingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DamagingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/DamagingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DamagingDataView.java index 73f9db5e..0715d71c 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DamagingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DamagingDataView.java @@ -1,17 +1,17 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.DamagingData; -import valandur.webapi.serialize.BaseView; - -public class DamagingDataView extends BaseView { - - @JsonValue - public double damage; - - public DamagingDataView(DamagingData value) { - super(value); - - this.damage = value.damage().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.DamagingData; +import valandur.webapi.serialize.BaseView; + +public class DamagingDataView extends BaseView { + + @JsonValue + public double damage; + + public DamagingDataView(DamagingData value) { + super(value); + + this.damage = value.damage().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DecayableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DecayableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/DecayableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DecayableDataView.java index 37052b4c..07d2e389 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DecayableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DecayableDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.DecayableData; -import valandur.webapi.serialize.BaseView; - -public class DecayableDataView extends BaseView { - - @JsonValue - public boolean decayable; - - - public DecayableDataView(DecayableData value) { - super(value); - - this.decayable = value.decayable().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.DecayableData; +import valandur.webapi.serialize.BaseView; + +public class DecayableDataView extends BaseView { + + @JsonValue + public boolean decayable; + + + public DecayableDataView(DecayableData value) { + super(value); + + this.decayable = value.decayable().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DelayableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DelayableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/DelayableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DelayableDataView.java index 607221ea..57b5dc47 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DelayableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DelayableDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.DelayableData; -import valandur.webapi.serialize.BaseView; - -public class DelayableDataView extends BaseView { - - @JsonValue - public int delay; - - - public DelayableDataView(DelayableData value) { - super(value); - - this.delay = value.delay().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.DelayableData; +import valandur.webapi.serialize.BaseView; + +public class DelayableDataView extends BaseView { + + @JsonValue + public int delay; + + + public DelayableDataView(DelayableData value) { + super(value); + + this.delay = value.delay().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DespawnDelayDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DespawnDelayDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/DespawnDelayDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DespawnDelayDataView.java index 96ef931d..2cf322cd 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DespawnDelayDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DespawnDelayDataView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.DespawnDelayData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("DespawnDelayData") -public class DespawnDelayDataView extends BaseView { - - @ApiModelProperty(value = "The amount of time until this entity despawns", required = true) - public int delay; - - @ApiModelProperty(value = "True if this entity never despawns, false otherwise", required = true) - public boolean infinite; - - - public DespawnDelayDataView(DespawnDelayData value) { - super(value); - - this.delay = value.delay().get(); - this.infinite = value.infinite().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.DespawnDelayData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("DespawnDelayData") +public class DespawnDelayDataView extends BaseView { + + @ApiModelProperty(value = "The amount of time until this entity despawns", required = true) + public int delay; + + @ApiModelProperty(value = "True if this entity never despawns, false otherwise", required = true) + public boolean infinite; + + + public DespawnDelayDataView(DespawnDelayData value) { + super(value); + + this.delay = value.delay().get(); + this.infinite = value.infinite().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DirectionalDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DirectionalDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/DirectionalDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DirectionalDataView.java index 89820383..a3c196af 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DirectionalDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DirectionalDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.DirectionalData; -import org.spongepowered.api.util.Direction; -import valandur.webapi.serialize.BaseView; - -public class DirectionalDataView extends BaseView { - - @JsonValue - public Direction direction; - - - public DirectionalDataView(DirectionalData value) { - super(value); - - this.direction = value.direction().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.DirectionalData; +import org.spongepowered.api.util.Direction; +import valandur.webapi.serialize.BaseView; + +public class DirectionalDataView extends BaseView { + + @JsonValue + public Direction direction; + + + public DirectionalDataView(DirectionalData value) { + super(value); + + this.direction = value.direction().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DisarmedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DisarmedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/DisarmedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DisarmedDataView.java index 9796cb7d..ce67b242 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DisarmedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DisarmedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.DisarmedData; -import valandur.webapi.serialize.BaseView; - -public class DisarmedDataView extends BaseView { - - @JsonValue - public boolean disarmed; - - - public DisarmedDataView(DisarmedData value) { - super(value); - - this.disarmed = value.disarmed().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.DisarmedData; +import valandur.webapi.serialize.BaseView; + +public class DisarmedDataView extends BaseView { + + @JsonValue + public boolean disarmed; + + + public DisarmedDataView(DisarmedData value) { + super(value); + + this.disarmed = value.disarmed().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DisplayNameDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DisplayNameDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/DisplayNameDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DisplayNameDataView.java index 5eb7250d..0ac52141 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DisplayNameDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DisplayNameDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.DisplayNameData; -import org.spongepowered.api.text.Text; -import valandur.webapi.serialize.BaseView; - -public class DisplayNameDataView extends BaseView { - - @JsonValue - public Text name; - - - public DisplayNameDataView(DisplayNameData value) { - super(value); - - this.name = value.displayName().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.DisplayNameData; +import org.spongepowered.api.text.Text; +import valandur.webapi.serialize.BaseView; + +public class DisplayNameDataView extends BaseView { + + @JsonValue + public Text name; + + + public DisplayNameDataView(DisplayNameData value) { + super(value); + + this.name = value.displayName().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DropDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DropDataView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/data/DropDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DropDataView.java index 5d8c8d49..23e43a3d 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DropDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DropDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.DropData; -import valandur.webapi.serialize.BaseView; - -public class DropDataView extends BaseView { - - @JsonValue - public boolean drops; - - - public DropDataView(DropData value) { - super(value); - - this.drops = value.willDrop().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.DropData; +import valandur.webapi.serialize.BaseView; + +public class DropDataView extends BaseView { + + @JsonValue + public boolean drops; + + + public DropDataView(DropData value) { + super(value); + + this.drops = value.willDrop().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/DurabilityDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DurabilityDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/DurabilityDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DurabilityDataView.java index a9ab1d55..cdbef02a 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/DurabilityDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/DurabilityDataView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.item.DurabilityData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("DurabilityData") -public class DurabilityDataView extends BaseView { - - @ApiModelProperty(value = "True if this entity is unbreakable, false otherwise", required = true) - public boolean unbreakable; - - @ApiModelProperty(value = "The remaining durability of this entity", required = true) - public int durability; - - - public DurabilityDataView(DurabilityData value) { - super(value); - - this.unbreakable = value.unbreakable().get(); - this.durability = value.durability().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.item.DurabilityData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("DurabilityData") +public class DurabilityDataView extends BaseView { + + @ApiModelProperty(value = "True if this entity is unbreakable, false otherwise", required = true) + public boolean unbreakable; + + @ApiModelProperty(value = "The remaining durability of this entity", required = true) + public int durability; + + + public DurabilityDataView(DurabilityData value) { + super(value); + + this.unbreakable = value.unbreakable().get(); + this.durability = value.durability().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/EndGatewayDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/EndGatewayDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/EndGatewayDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/EndGatewayDataView.java index c45b96bc..a60796b4 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/EndGatewayDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/EndGatewayDataView.java @@ -1,33 +1,33 @@ -package valandur.webapi.serialize.view.data; - -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.tileentity.EndGatewayData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("EndGatewayData") -public class EndGatewayDataView extends BaseView { - - @ApiModelProperty(value = "The age of this gateway", required = true) - public long age; - - @ApiModelProperty(value = "True if this is an exact teleport, false otherwise", required = true) - public boolean exactTeleport; - - @ApiModelProperty(value = "The exit position in the nether", required = true) - public Vector3i exitPosition; - - @ApiModelProperty(value = "The cooldown of the teleport", required = true) - public int teleportCooldown; - - - public EndGatewayDataView(EndGatewayData value) { - super(value); - - this.age = value.age().get(); - this.exactTeleport = value.exactTeleport().get(); - this.exitPosition = value.exitPosition().get(); - this.teleportCooldown = value.teleportCooldown().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.tileentity.EndGatewayData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("EndGatewayData") +public class EndGatewayDataView extends BaseView { + + @ApiModelProperty(value = "The age of this gateway", required = true) + public long age; + + @ApiModelProperty(value = "True if this is an exact teleport, false otherwise", required = true) + public boolean exactTeleport; + + @ApiModelProperty(value = "The exit position in the nether", required = true) + public Vector3i exitPosition; + + @ApiModelProperty(value = "The cooldown of the teleport", required = true) + public int teleportCooldown; + + + public EndGatewayDataView(EndGatewayData value) { + super(value); + + this.age = value.age().get(); + this.exactTeleport = value.exactTeleport().get(); + this.exitPosition = value.exitPosition().get(); + this.teleportCooldown = value.teleportCooldown().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ExpOrbDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExpOrbDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ExpOrbDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExpOrbDataView.java index 483dcc96..b1334807 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ExpOrbDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExpOrbDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.ExpOrbData; -import valandur.webapi.serialize.BaseView; - -public class ExpOrbDataView extends BaseView { - - @JsonValue - public int exp; - - - public ExpOrbDataView(ExpOrbData value) { - super(value); - - this.exp = value.experience().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.ExpOrbData; +import valandur.webapi.serialize.BaseView; + +public class ExpOrbDataView extends BaseView { + + @JsonValue + public int exp; + + + public ExpOrbDataView(ExpOrbData value) { + super(value); + + this.exp = value.experience().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ExperienceHolderDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExperienceHolderDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/ExperienceHolderDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExperienceHolderDataView.java index b44e7764..e3444077 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ExperienceHolderDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExperienceHolderDataView.java @@ -1,28 +1,28 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.ExperienceHolderData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("ExperienceHolderData") -public class ExperienceHolderDataView extends BaseView { - - @ApiModelProperty("The current level of the entity") - public int level; - - @ApiModelProperty("The experience gained since the last level") - public int experience; - - @ApiModelProperty("The total amount of experience collected") - public int totalExperience; - - - public ExperienceHolderDataView(ExperienceHolderData value) { - super(value); - - this.level = value.level().get(); - this.experience = value.experienceSinceLevel().get(); - this.totalExperience = value.totalExperience().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.ExperienceHolderData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("ExperienceHolderData") +public class ExperienceHolderDataView extends BaseView { + + @ApiModelProperty("The current level of the entity") + public int level; + + @ApiModelProperty("The experience gained since the last level") + public int experience; + + @ApiModelProperty("The total amount of experience collected") + public int totalExperience; + + + public ExperienceHolderDataView(ExperienceHolderData value) { + super(value); + + this.level = value.level().get(); + this.experience = value.experienceSinceLevel().get(); + this.totalExperience = value.totalExperience().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ExpirableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExpirableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ExpirableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExpirableDataView.java index 434c7e8d..23431c35 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ExpirableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExpirableDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.ExpirableData; -import valandur.webapi.serialize.BaseView; - -public class ExpirableDataView extends BaseView { - - @JsonValue - public int ticks; - - - public ExpirableDataView(ExpirableData value) { - super(value); - - this.ticks = value.expireTicks().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.ExpirableData; +import valandur.webapi.serialize.BaseView; + +public class ExpirableDataView extends BaseView { + + @JsonValue + public int ticks; + + + public ExpirableDataView(ExpirableData value) { + super(value); + + this.ticks = value.expireTicks().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ExplosionRadiusDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExplosionRadiusDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ExplosionRadiusDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExplosionRadiusDataView.java index 8878bbe4..8a928a34 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ExplosionRadiusDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExplosionRadiusDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.ExplosionRadiusData; -import valandur.webapi.serialize.BaseView; - -public class ExplosionRadiusDataView extends BaseView { - - @JsonValue - public Integer radius; - - - public ExplosionRadiusDataView(ExplosionRadiusData value) { - super(value); - - this.radius = value.explosionRadius().get().orElse(null); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.ExplosionRadiusData; +import valandur.webapi.serialize.BaseView; + +public class ExplosionRadiusDataView extends BaseView { + + @JsonValue + public Integer radius; + + + public ExplosionRadiusDataView(ExplosionRadiusData value) { + super(value); + + this.radius = value.explosionRadius().get().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ExtendedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExtendedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ExtendedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExtendedDataView.java index 2e4790d7..8818bfa1 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ExtendedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ExtendedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.ExtendedData; -import valandur.webapi.serialize.BaseView; - -public class ExtendedDataView extends BaseView { - - @JsonValue - public boolean extended; - - - public ExtendedDataView(ExtendedData value) { - super(value); - - this.extended = value.extended().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.ExtendedData; +import valandur.webapi.serialize.BaseView; + +public class ExtendedDataView extends BaseView { + + @JsonValue + public boolean extended; + + + public ExtendedDataView(ExtendedData value) { + super(value); + + this.extended = value.extended().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FallDistanceDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FallDistanceDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FallDistanceDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FallDistanceDataView.java index 6419c23b..698f63df 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FallDistanceDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FallDistanceDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.FallDistanceData; -import valandur.webapi.serialize.BaseView; - -public class FallDistanceDataView extends BaseView { - - @JsonValue - public float fallDistance; - - - public FallDistanceDataView(FallDistanceData value) { - super(value); - - this.fallDistance = value.fallDistance().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.FallDistanceData; +import valandur.webapi.serialize.BaseView; + +public class FallDistanceDataView extends BaseView { + + @JsonValue + public float fallDistance; + + + public FallDistanceDataView(FallDistanceData value) { + super(value); + + this.fallDistance = value.fallDistance().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FallingBlockDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FallingBlockDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/FallingBlockDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FallingBlockDataView.java index 9c23153f..e87bc11c 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FallingBlockDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FallingBlockDataView.java @@ -1,45 +1,45 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.data.manipulator.mutable.entity.FallingBlockData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("FallingBlockData") -public class FallingBlockDataView extends BaseView { - - @ApiModelProperty(value = "The state of the falling block", required = true) - public BlockState state; - - @ApiModelProperty(value = "True if the block can drop as an item, false otherwise", required = true) - public boolean canDropAsItem; - - @ApiModelProperty(value = "True if the block can hurt entities, false otherwise", required = true) - public boolean canHurtEntities; - - @ApiModelProperty(value = "True if this falling block can be placed as a normal block, false otherwise", required = true) - public boolean canPlaceAsBlock; - - @ApiModelProperty(value = "The amount of damage per block this falling block deals", required = true) - public double fallDamagePerBlock; - - @ApiModelProperty(value = "The amount of time (in ticks) this block has been falling for", required = true) - public int fallTime; - - @ApiModelProperty(value = "The maximum amount of damage this block can deal", required = true) - public double maxFallDamage; - - - public FallingBlockDataView(FallingBlockData value) { - super(value); - - this.state = value.blockState().get(); - this.canDropAsItem = value.canDropAsItem().get(); - this.canHurtEntities = value.canHurtEntities().get(); - this.canPlaceAsBlock = value.canPlaceAsBlock().get(); - this.fallDamagePerBlock = value.fallDamagePerBlock().get(); - this.fallTime = value.fallTime().get(); - this.maxFallDamage = value.maxFallDamage().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.data.manipulator.mutable.entity.FallingBlockData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("FallingBlockData") +public class FallingBlockDataView extends BaseView { + + @ApiModelProperty(value = "The state of the falling block", required = true) + public BlockState state; + + @ApiModelProperty(value = "True if the block can drop as an item, false otherwise", required = true) + public boolean canDropAsItem; + + @ApiModelProperty(value = "True if the block can hurt entities, false otherwise", required = true) + public boolean canHurtEntities; + + @ApiModelProperty(value = "True if this falling block can be placed as a normal block, false otherwise", required = true) + public boolean canPlaceAsBlock; + + @ApiModelProperty(value = "The amount of damage per block this falling block deals", required = true) + public double fallDamagePerBlock; + + @ApiModelProperty(value = "The amount of time (in ticks) this block has been falling for", required = true) + public int fallTime; + + @ApiModelProperty(value = "The maximum amount of damage this block can deal", required = true) + public double maxFallDamage; + + + public FallingBlockDataView(FallingBlockData value) { + super(value); + + this.state = value.blockState().get(); + this.canDropAsItem = value.canDropAsItem().get(); + this.canHurtEntities = value.canHurtEntities().get(); + this.canPlaceAsBlock = value.canPlaceAsBlock().get(); + this.fallDamagePerBlock = value.fallDamagePerBlock().get(); + this.fallTime = value.fallTime().get(); + this.maxFallDamage = value.maxFallDamage().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FilledDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FilledDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FilledDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FilledDataView.java index 0dfc85b3..413b8039 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FilledDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FilledDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.FilledData; -import valandur.webapi.serialize.BaseView; - -public class FilledDataView extends BaseView { - - @JsonValue - public boolean filled; - - - public FilledDataView(FilledData value) { - super(value); - - this.filled = value.filled().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.FilledData; +import valandur.webapi.serialize.BaseView; + +public class FilledDataView extends BaseView { + + @JsonValue + public boolean filled; + + + public FilledDataView(FilledData value) { + super(value); + + this.filled = value.filled().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FireworkRocketDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FireworkRocketDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FireworkRocketDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FireworkRocketDataView.java index 4bfebf86..201289a0 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FireworkRocketDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FireworkRocketDataView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.FireworkRocketData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("FireworkRocketData") -public class FireworkRocketDataView extends BaseView { - - @ApiModelProperty(value = "The flight modifier of this firework rocket", required = true) - public int flightModifier; - - - public FireworkRocketDataView(FireworkRocketData value) { - super(value); - - this.flightModifier = value.flightModifier().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.FireworkRocketData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("FireworkRocketData") +public class FireworkRocketDataView extends BaseView { + + @ApiModelProperty(value = "The flight modifier of this firework rocket", required = true) + public int flightModifier; + + + public FireworkRocketDataView(FireworkRocketData value) { + super(value); + + this.flightModifier = value.flightModifier().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FlammableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlammableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FlammableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlammableDataView.java index 5d7b2d96..7af13553 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FlammableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlammableDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.FlammableData; -import valandur.webapi.serialize.BaseView; - -public class FlammableDataView extends BaseView { - - @JsonValue - public boolean flammable; - - - public FlammableDataView(FlammableData value) { - super(value); - - this.flammable = value.flammable().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.FlammableData; +import valandur.webapi.serialize.BaseView; + +public class FlammableDataView extends BaseView { + + @JsonValue + public boolean flammable; + + + public FlammableDataView(FlammableData value) { + super(value); + + this.flammable = value.flammable().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FluidItemDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FluidItemDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FluidItemDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FluidItemDataView.java index db99bbb1..2706266f 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FluidItemDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FluidItemDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.extra.fluid.FluidStackSnapshot; -import org.spongepowered.api.extra.fluid.data.manipulator.mutable.FluidItemData; -import valandur.webapi.serialize.BaseView; - -public class FluidItemDataView extends BaseView { - - @JsonValue - public FluidStackSnapshot fluid; - - - public FluidItemDataView(FluidItemData value) { - super(value); - - this.fluid = value.fluid().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.extra.fluid.FluidStackSnapshot; +import org.spongepowered.api.extra.fluid.data.manipulator.mutable.FluidItemData; +import valandur.webapi.serialize.BaseView; + +public class FluidItemDataView extends BaseView { + + @JsonValue + public FluidStackSnapshot fluid; + + + public FluidItemDataView(FluidItemData value) { + super(value); + + this.fluid = value.fluid().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FluidLevelDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FluidLevelDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FluidLevelDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FluidLevelDataView.java index 3290207b..36efcc65 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FluidLevelDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FluidLevelDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.FluidLevelData; -import valandur.webapi.serialize.BaseView; - -public class FluidLevelDataView extends BaseView { - - @JsonValue - public int level; - - - public FluidLevelDataView(FluidLevelData value) { - super(value); - - this.level = value.level().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.FluidLevelData; +import valandur.webapi.serialize.BaseView; + +public class FluidLevelDataView extends BaseView { + + @JsonValue + public int level; + + + public FluidLevelDataView(FluidLevelData value) { + super(value); + + this.level = value.level().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FlyingAbilityDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlyingAbilityDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FlyingAbilityDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlyingAbilityDataView.java index 012282c1..3f33535f 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FlyingAbilityDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlyingAbilityDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.FlyingAbilityData; -import valandur.webapi.serialize.BaseView; - -public class FlyingAbilityDataView extends BaseView { - - @JsonValue - public boolean canFly; - - - public FlyingAbilityDataView(FlyingAbilityData value) { - super(value); - - this.canFly = value.canFly().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.FlyingAbilityData; +import valandur.webapi.serialize.BaseView; + +public class FlyingAbilityDataView extends BaseView { + + @JsonValue + public boolean canFly; + + + public FlyingAbilityDataView(FlyingAbilityData value) { + super(value); + + this.canFly = value.canFly().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FlyingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlyingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FlyingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlyingDataView.java index 5f81e1c0..4026c6df 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FlyingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FlyingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.FlyingData; -import valandur.webapi.serialize.BaseView; - -public class FlyingDataView extends BaseView { - - @JsonValue - public boolean flying; - - - public FlyingDataView(FlyingData value) { - super(value); - - this.flying = value.flying().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.FlyingData; +import valandur.webapi.serialize.BaseView; + +public class FlyingDataView extends BaseView { + + @JsonValue + public boolean flying; + + + public FlyingDataView(FlyingData value) { + super(value); + + this.flying = value.flying().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FoodDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FoodDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/FoodDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FoodDataView.java index 5640064f..f507ec80 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FoodDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FoodDataView.java @@ -1,28 +1,28 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.FoodData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("FoodData") -public class FoodDataView extends BaseView { - - @ApiModelProperty(value = "The food level of this entity", required = true) - public int foodLevel; - - @ApiModelProperty(value = "The saturation of this entity", required = true) - public double saturation; - - @ApiModelProperty(value = "The exhaustion of this entity", required = true) - public double exhaustion; - - - public FoodDataView(FoodData value) { - super(value); - - this.foodLevel = value.foodLevel().get(); - this.saturation = value.saturation().get(); - this.exhaustion = value.exhaustion().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.FoodData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("FoodData") +public class FoodDataView extends BaseView { + + @ApiModelProperty(value = "The food level of this entity", required = true) + public int foodLevel; + + @ApiModelProperty(value = "The saturation of this entity", required = true) + public double saturation; + + @ApiModelProperty(value = "The exhaustion of this entity", required = true) + public double exhaustion; + + + public FoodDataView(FoodData value) { + super(value); + + this.foodLevel = value.foodLevel().get(); + this.saturation = value.saturation().get(); + this.exhaustion = value.exhaustion().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FurnaceDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FurnaceDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/FurnaceDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FurnaceDataView.java index 89afaa21..0e8e1b18 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FurnaceDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FurnaceDataView.java @@ -1,32 +1,32 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.tileentity.FurnaceData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("FurnaceData") -public class FurnaceDataView extends BaseView { - - @ApiModelProperty(value = "The maximum amount of time (in ticks) the current fuel item lasts", required = true) - public int maxBurnTime; - - @ApiModelProperty(value = "The total amount of time (in ticks) the stack has to cook for to be done", required = true) - public int maxCookTime; - - @ApiModelProperty(value = "The amount of time (in ticks) that has passed since this fuel item started burning", required = true) - public int passedBurnTime; - - @ApiModelProperty(value = "The amount of time (in ticks) that has passed since the item stack started cooking", required = true) - public int passedCookTime; - - - public FurnaceDataView(FurnaceData value) { - super(value); - - this.maxBurnTime = value.maxBurnTime().get(); - this.maxCookTime = value.maxCookTime().get(); - this.passedBurnTime = value.passedBurnTime().get(); - this.passedCookTime = value.passedCookTime().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.tileentity.FurnaceData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("FurnaceData") +public class FurnaceDataView extends BaseView { + + @ApiModelProperty(value = "The maximum amount of time (in ticks) the current fuel item lasts", required = true) + public int maxBurnTime; + + @ApiModelProperty(value = "The total amount of time (in ticks) the stack has to cook for to be done", required = true) + public int maxCookTime; + + @ApiModelProperty(value = "The amount of time (in ticks) that has passed since this fuel item started burning", required = true) + public int passedBurnTime; + + @ApiModelProperty(value = "The amount of time (in ticks) that has passed since the item stack started cooking", required = true) + public int passedCookTime; + + + public FurnaceDataView(FurnaceData value) { + super(value); + + this.maxBurnTime = value.maxBurnTime().get(); + this.maxCookTime = value.maxCookTime().get(); + this.passedBurnTime = value.passedBurnTime().get(); + this.passedCookTime = value.passedCookTime().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/FuseDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FuseDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/FuseDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FuseDataView.java index ea8e5036..8d732ee4 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/FuseDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/FuseDataView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.FuseData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("FuseData") -public class FuseDataView extends BaseView { - - @ApiModelProperty(value = "The total amount of time (in ticks) the fuse burns for", required = true) - public int fuseDuration; - - @ApiModelProperty(value = "The amount of ticks remaining on this fuse", required = true) - public int ticksRemaining; - - - public FuseDataView(FuseData value) { - super(value); - - this.fuseDuration = value.fuseDuration().get(); - this.ticksRemaining = value.ticksRemaining().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.FuseData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("FuseData") +public class FuseDataView extends BaseView { + + @ApiModelProperty(value = "The total amount of time (in ticks) the fuse burns for", required = true) + public int fuseDuration; + + @ApiModelProperty(value = "The amount of ticks remaining on this fuse", required = true) + public int ticksRemaining; + + + public FuseDataView(FuseData value) { + super(value); + + this.fuseDuration = value.fuseDuration().get(); + this.ticksRemaining = value.ticksRemaining().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/GenerationDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GenerationDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/GenerationDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GenerationDataView.java index 5419087c..b3017b0f 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/GenerationDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GenerationDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.item.GenerationData; -import valandur.webapi.serialize.BaseView; - -public class GenerationDataView extends BaseView { - - @JsonValue - public int generation; - - - public GenerationDataView(GenerationData value) { - super(value); - - this.generation = value.generation().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.item.GenerationData; +import valandur.webapi.serialize.BaseView; + +public class GenerationDataView extends BaseView { + + @JsonValue + public int generation; + + + public GenerationDataView(GenerationData value) { + super(value); + + this.generation = value.generation().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/GlowingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GlowingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/GlowingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GlowingDataView.java index 39841f69..270f4aae 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/GlowingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GlowingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.GlowingData; -import valandur.webapi.serialize.BaseView; - -public class GlowingDataView extends BaseView { - - @JsonValue - public boolean glowing; - - - public GlowingDataView(GlowingData value) { - super(value); - - this.glowing = value.glowing().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.GlowingData; +import valandur.webapi.serialize.BaseView; + +public class GlowingDataView extends BaseView { + + @JsonValue + public boolean glowing; + + + public GlowingDataView(GlowingData value) { + super(value); + + this.glowing = value.glowing().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/GriefingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GriefingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/GriefingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GriefingDataView.java index 70513033..27890006 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/GriefingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GriefingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.GriefingData; -import valandur.webapi.serialize.BaseView; - -public class GriefingDataView extends BaseView { - - @JsonValue - public boolean grief; - - - public GriefingDataView(GriefingData value) { - super(value); - - this.grief = value.canGrief().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.GriefingData; +import valandur.webapi.serialize.BaseView; + +public class GriefingDataView extends BaseView { + + @JsonValue + public boolean grief; + + + public GriefingDataView(GriefingData value) { + super(value); + + this.grief = value.canGrief().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/GrowthDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GrowthDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/GrowthDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GrowthDataView.java index 657a5dd5..96979519 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/GrowthDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/GrowthDataView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.block.GrowthData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("GrowthData") -public class GrowthDataView extends BaseView { - - @ApiModelProperty(value = "The current growth stage of this entity", required = true) - public int stage; - - - public GrowthDataView(GrowthData value) { - super(value); - - this.stage = value.growthStage().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.block.GrowthData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("GrowthData") +public class GrowthDataView extends BaseView { + + @ApiModelProperty(value = "The current growth stage of this entity", required = true) + public int stage; + + + public GrowthDataView(GrowthData value) { + super(value); + + this.stage = value.growthStage().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/HealthDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HealthDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/HealthDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HealthDataView.java index c5818fdb..87fd675b 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/HealthDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HealthDataView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.HealthData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("HealthData") -public class HealthDataView extends BaseView { - - @ApiModelProperty(value = "The current health of the entity", required = true) - public double current; - - @ApiModelProperty(value = "The maximum health of the entity", required = true) - public double max; - - - public HealthDataView(HealthData value) { - super(value); - - this.current = value.health().get(); - this.max = value.maxHealth().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.HealthData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("HealthData") +public class HealthDataView extends BaseView { + + @ApiModelProperty(value = "The current health of the entity", required = true) + public double current; + + @ApiModelProperty(value = "The maximum health of the entity", required = true) + public double max; + + + public HealthDataView(HealthData value) { + super(value); + + this.current = value.health().get(); + this.max = value.maxHealth().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/HideDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java index 6310a6a4..3e1b0c27 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HideDataView.java @@ -1,40 +1,40 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.item.HideData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("HideData") -public class HideDataView extends BaseView { - - @ApiModelProperty("Gets the 'attributes hidden' state of the item stack") - public boolean hideAttributes; - - @ApiModelProperty("Gets the 'can destory hidden' state of the item stack") - public boolean hideCanDestroy; - - @ApiModelProperty("Gets the 'can place hidden' state of the item stack") - public boolean hideCanPlace; - - @ApiModelProperty("Gets the 'enchantments hidden' state of the item stack") - public boolean hideEnchantments; - - @ApiModelProperty("Gets the 'miscellaneous hidden' state of the item stack") - public boolean hideMiscellaneous; - - @ApiModelProperty("Gets the 'unbreakable hidden' state of the item stack") - public boolean hideUnbreakable; - - - public HideDataView(HideData value) { - super(value); - - this.hideAttributes = value.hideAttributes().get(); - this.hideCanDestroy = value.hideCanDestroy().get(); - this.hideCanPlace = value.hideCanPlace().get(); - this.hideEnchantments = value.hideEnchantments().get(); - this.hideMiscellaneous = value.hideMiscellaneous().get(); - this.hideUnbreakable = value.hideUnbreakable().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.item.HideData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("HideData") +public class HideDataView extends BaseView { + + @ApiModelProperty("Gets the 'attributes hidden' state of the item stack") + public boolean hideAttributes; + + @ApiModelProperty("Gets the 'can destory hidden' state of the item stack") + public boolean hideCanDestroy; + + @ApiModelProperty("Gets the 'can place hidden' state of the item stack") + public boolean hideCanPlace; + + @ApiModelProperty("Gets the 'enchantments hidden' state of the item stack") + public boolean hideEnchantments; + + @ApiModelProperty("Gets the 'miscellaneous hidden' state of the item stack") + public boolean hideMiscellaneous; + + @ApiModelProperty("Gets the 'unbreakable hidden' state of the item stack") + public boolean hideUnbreakable; + + + public HideDataView(HideData value) { + super(value); + + this.hideAttributes = value.hideAttributes().get(); + this.hideCanDestroy = value.hideCanDestroy().get(); + this.hideCanPlace = value.hideCanPlace().get(); + this.hideEnchantments = value.hideEnchantments().get(); + this.hideMiscellaneous = value.hideMiscellaneous().get(); + this.hideUnbreakable = value.hideUnbreakable().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/HorseDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HorseDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/HorseDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HorseDataView.java index 1b6da047..b72e847b 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/HorseDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/HorseDataView.java @@ -1,26 +1,26 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.HorseData; -import org.spongepowered.api.data.type.HorseColor; -import org.spongepowered.api.data.type.HorseStyle; -import valandur.webapi.serialize.BaseView; - -@ApiModel("HorseData") -public class HorseDataView extends BaseView { - - @ApiModelProperty(value = "The color of the horse", required = true) - public HorseColor color; - - @ApiModelProperty(value = "The style of the horse", required = true) - public HorseStyle style; - - - public HorseDataView(HorseData value) { - super(value); - - this.color = value.color().get(); - this.style = value.style().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.HorseData; +import org.spongepowered.api.data.type.HorseColor; +import org.spongepowered.api.data.type.HorseStyle; +import valandur.webapi.serialize.BaseView; + +@ApiModel("HorseData") +public class HorseDataView extends BaseView { + + @ApiModelProperty(value = "The color of the horse", required = true) + public HorseColor color; + + @ApiModelProperty(value = "The style of the horse", required = true) + public HorseStyle style; + + + public HorseDataView(HorseData value) { + super(value); + + this.color = value.color().get(); + this.style = value.style().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/IgniteableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/IgniteableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/IgniteableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/IgniteableDataView.java index e53b378f..227ddf60 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/IgniteableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/IgniteableDataView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.IgniteableData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("IgniteableData") -public class IgniteableDataView extends BaseView { - - @ApiModelProperty(value = "The delay of the fire", required = true) - public int fireDelay; - - @ApiModelProperty(value = "The amount of ticks the fire will burn for", required = true) - public int fireTicks; - - - public IgniteableDataView(IgniteableData value) { - super(value); - - this.fireDelay = value.fireDelay().get(); - this.fireTicks = value.fireTicks().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.IgniteableData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("IgniteableData") +public class IgniteableDataView extends BaseView { + + @ApiModelProperty(value = "The delay of the fire", required = true) + public int fireDelay; + + @ApiModelProperty(value = "The amount of ticks the fire will burn for", required = true) + public int fireTicks; + + + public IgniteableDataView(IgniteableData value) { + super(value); + + this.fireDelay = value.fireDelay().get(); + this.fireTicks = value.fireTicks().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/InWallDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InWallDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/InWallDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InWallDataView.java index 9b3f89d8..2212c3df 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/InWallDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InWallDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.InWallData; -import valandur.webapi.serialize.BaseView; - -public class InWallDataView extends BaseView { - - @JsonValue - public boolean inWall; - - - public InWallDataView(InWallData value) { - super(value); - - this.inWall = value.inWall().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.InWallData; +import valandur.webapi.serialize.BaseView; + +public class InWallDataView extends BaseView { + + @JsonValue + public boolean inWall; + + + public InWallDataView(InWallData value) { + super(value); + + this.inWall = value.inWall().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/InventoryItemDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InventoryItemDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/InventoryItemDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InventoryItemDataView.java index 793a750a..c96afe3f 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/InventoryItemDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InventoryItemDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.item.InventoryItemData; -import org.spongepowered.api.item.inventory.Inventory; -import valandur.webapi.serialize.BaseView; - -public class InventoryItemDataView extends BaseView { - - @JsonValue - public Inventory inventory; - - - public InventoryItemDataView(InventoryItemData value) { - super(value); - - this.inventory = value.getInventory(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.item.InventoryItemData; +import org.spongepowered.api.item.inventory.Inventory; +import valandur.webapi.serialize.BaseView; + +public class InventoryItemDataView extends BaseView { + + @JsonValue + public Inventory inventory; + + + public InventoryItemDataView(InventoryItemData value) { + super(value); + + this.inventory = value.getInventory(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/InvisibilityDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InvisibilityDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/InvisibilityDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InvisibilityDataView.java index a4d984d8..df715a32 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/InvisibilityDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InvisibilityDataView.java @@ -1,32 +1,32 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.InvisibilityData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("InvisibilityData") -public class InvisibilityDataView extends BaseView { - - @ApiModelProperty(value = "True if this entity ignores collisions, false otherwise", required = true) - public boolean ignoreCollision; - - @ApiModelProperty(value = "True if this entity is invisible, false otherwise", required = true) - public boolean invisible; - - @ApiModelProperty(value = "True if this entity is not targetable, false otherwise", required = true) - public boolean untargetable; - - @ApiModelProperty(value = "True if this entity is vanished, false otherwise", required = true) - public boolean vanish; - - - public InvisibilityDataView(InvisibilityData value) { - super(value); - - this.ignoreCollision = value.ignoresCollisionDetection().get(); - this.invisible = value.invisible().get(); - this.untargetable = value.untargetable().get(); - this.vanish = value.vanish().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.InvisibilityData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("InvisibilityData") +public class InvisibilityDataView extends BaseView { + + @ApiModelProperty(value = "True if this entity ignores collisions, false otherwise", required = true) + public boolean ignoreCollision; + + @ApiModelProperty(value = "True if this entity is invisible, false otherwise", required = true) + public boolean invisible; + + @ApiModelProperty(value = "True if this entity is not targetable, false otherwise", required = true) + public boolean untargetable; + + @ApiModelProperty(value = "True if this entity is vanished, false otherwise", required = true) + public boolean vanish; + + + public InvisibilityDataView(InvisibilityData value) { + super(value); + + this.ignoreCollision = value.ignoresCollisionDetection().get(); + this.invisible = value.invisible().get(); + this.untargetable = value.untargetable().get(); + this.vanish = value.vanish().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/InvulnerabilityDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InvulnerabilityDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/InvulnerabilityDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InvulnerabilityDataView.java index 7b0541af..f1440746 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/InvulnerabilityDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/InvulnerabilityDataView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.InvulnerabilityData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("InvulnerabilityData") -public class InvulnerabilityDataView extends BaseView { - - @ApiModelProperty(value = "The amount of ticks this entity will remain invulnerable for", required = true) - public int ticks; - - - public InvulnerabilityDataView(InvulnerabilityData value) { - super(value); - - this.ticks = value.invulnerableTicks().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.InvulnerabilityData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("InvulnerabilityData") +public class InvulnerabilityDataView extends BaseView { + + @ApiModelProperty(value = "The amount of ticks this entity will remain invulnerable for", required = true) + public int ticks; + + + public InvulnerabilityDataView(InvulnerabilityData value) { + super(value); + + this.ticks = value.invulnerableTicks().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/JoinDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/JoinDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/JoinDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/JoinDataView.java index 43362e85..6f7e9e02 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/JoinDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/JoinDataView.java @@ -1,26 +1,26 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.JoinData; -import valandur.webapi.serialize.BaseView; - -import java.time.Instant; - -@ApiModel("JoinData") -public class JoinDataView extends BaseView { - - @ApiModelProperty(value = "The first time this entity joined the server", required = true) - public Instant first; - - @ApiModelProperty(value = "The most recent time this entity joined the server", required = true) - public Instant last; - - - public JoinDataView(JoinData value) { - super(value); - - this.first = value.firstPlayed().get(); - this.last = value.lastPlayed().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.JoinData; +import valandur.webapi.serialize.BaseView; + +import java.time.Instant; + +@ApiModel("JoinData") +public class JoinDataView extends BaseView { + + @ApiModelProperty(value = "The first time this entity joined the server", required = true) + public Instant first; + + @ApiModelProperty(value = "The most recent time this entity joined the server", required = true) + public Instant last; + + + public JoinDataView(JoinData value) { + super(value); + + this.first = value.firstPlayed().get(); + this.last = value.lastPlayed().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/KnockbackDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/KnockbackDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/KnockbackDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/KnockbackDataView.java index ca23378f..e15d4509 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/KnockbackDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/KnockbackDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.KnockbackData; -import valandur.webapi.serialize.BaseView; - -public class KnockbackDataView extends BaseView { - - @JsonValue - public int knockback; - - - public KnockbackDataView(KnockbackData value) { - super(value); - - this.knockback = value.knockbackStrength().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.KnockbackData; +import valandur.webapi.serialize.BaseView; + +public class KnockbackDataView extends BaseView { + + @JsonValue + public int knockback; + + + public KnockbackDataView(KnockbackData value) { + super(value); + + this.knockback = value.knockbackStrength().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/LayeredDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LayeredDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/LayeredDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LayeredDataView.java index a5e443e9..c61c671f 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/LayeredDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LayeredDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.LayeredData; -import valandur.webapi.serialize.BaseView; - -public class LayeredDataView extends BaseView { - - @JsonValue - public int layer; - - - public LayeredDataView(LayeredData value) { - super(value); - - this.layer = value.layer().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.LayeredData; +import valandur.webapi.serialize.BaseView; + +public class LayeredDataView extends BaseView { + + @JsonValue + public int layer; + + + public LayeredDataView(LayeredData value) { + super(value); + + this.layer = value.layer().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/LeashDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LeashDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/LeashDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LeashDataView.java index 510ba1f7..4d0e1565 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/LeashDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LeashDataView.java @@ -1,21 +1,21 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.LeashData; -import valandur.webapi.cache.entity.CachedEntity; -import valandur.webapi.serialize.BaseView; - -@ApiModel("LeashData") -public class LeashDataView extends BaseView { - - @ApiModelProperty(value = "The holder of this entity's leash", required = true) - public CachedEntity holder; - - - public LeashDataView(LeashData value) { - super(value); - - this.holder = new CachedEntity(value.leashHolder().get()); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.LeashData; +import valandur.webapi.cache.entity.CachedEntity; +import valandur.webapi.serialize.BaseView; + +@ApiModel("LeashData") +public class LeashDataView extends BaseView { + + @ApiModelProperty(value = "The holder of this entity's leash", required = true) + public CachedEntity holder; + + + public LeashDataView(LeashData value) { + super(value); + + this.holder = new CachedEntity(value.leashHolder().get()); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ListDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ListDataView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/data/ListDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ListDataView.java index 71b8e74a..13e0622b 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ListDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ListDataView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.ListData; -import valandur.webapi.serialize.BaseView; - -import java.util.List; - -public class ListDataView extends BaseView { - - @JsonValue - public List list; - - - public ListDataView(ListData value) { - super(value); - - this.list = value.asList(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.ListData; +import valandur.webapi.serialize.BaseView; + +import java.util.List; + +public class ListDataView extends BaseView { + + @JsonValue + public List list; + + + public ListDataView(ListData value) { + super(value); + + this.list = value.asList(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/LockableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LockableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/LockableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LockableDataView.java index c5b0ec53..aebaa98b 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/LockableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/LockableDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.tileentity.LockableData; -import valandur.webapi.serialize.BaseView; - -public class LockableDataView extends BaseView { - - @JsonValue - public String lock; - - - public LockableDataView(LockableData value) { - super(value); - - this.lock = value.lockToken().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.tileentity.LockableData; +import valandur.webapi.serialize.BaseView; + +public class LockableDataView extends BaseView { + + @JsonValue + public String lock; + + + public LockableDataView(LockableData value) { + super(value); + + this.lock = value.lockToken().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/MappedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MappedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/MappedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MappedDataView.java index 12b203c4..3698b473 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/MappedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MappedDataView.java @@ -1,29 +1,29 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.CatalogType; -import org.spongepowered.api.data.manipulator.mutable.MappedData; -import valandur.webapi.serialize.BaseView; - -import java.util.HashMap; -import java.util.Map; - -public class MappedDataView extends BaseView { - - @JsonValue - public Map map = new HashMap<>(); - - - public MappedDataView(MappedData value) { - super(value); - - Map data = value.asMap(); - for (Map.Entry entry : data.entrySet()) { - String key = entry.getKey().toString(); - if (entry.getKey() instanceof CatalogType) { - key = ((CatalogType)entry.getKey()).getId(); - } - map.put(key, entry.getValue()); - } - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.CatalogType; +import org.spongepowered.api.data.manipulator.mutable.MappedData; +import valandur.webapi.serialize.BaseView; + +import java.util.HashMap; +import java.util.Map; + +public class MappedDataView extends BaseView { + + @JsonValue + public Map map = new HashMap<>(); + + + public MappedDataView(MappedData value) { + super(value); + + Map data = value.asMap(); + for (Map.Entry entry : data.entrySet()) { + String key = entry.getKey().toString(); + if (entry.getKey() instanceof CatalogType) { + key = ((CatalogType)entry.getKey()).getId(); + } + map.put(key, entry.getValue()); + } + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/MinecartBlockDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MinecartBlockDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/MinecartBlockDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MinecartBlockDataView.java index 7090dee8..f956335c 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/MinecartBlockDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MinecartBlockDataView.java @@ -1,25 +1,25 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.data.manipulator.mutable.entity.MinecartBlockData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("MinecartBlockData") -public class MinecartBlockDataView extends BaseView { - - @ApiModelProperty(value = "The current state of the block", required = true) - public BlockState state; - - @ApiModelProperty(value = "The offset of the block", required = true) - public int offset; - - - public MinecartBlockDataView(MinecartBlockData value) { - super(value); - - this.state = value.block().get(); - this.offset = value.offset().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.block.BlockState; +import org.spongepowered.api.data.manipulator.mutable.entity.MinecartBlockData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("MinecartBlockData") +public class MinecartBlockDataView extends BaseView { + + @ApiModelProperty(value = "The current state of the block", required = true) + public BlockState state; + + @ApiModelProperty(value = "The offset of the block", required = true) + public int offset; + + + public MinecartBlockDataView(MinecartBlockData value) { + super(value); + + this.state = value.block().get(); + this.offset = value.offset().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/MobSpawnerDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MobSpawnerDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/MobSpawnerDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MobSpawnerDataView.java index a6ff20cd..1d29c083 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/MobSpawnerDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MobSpawnerDataView.java @@ -1,54 +1,54 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.MobSpawnerData; -import org.spongepowered.api.entity.EntityArchetype; -import org.spongepowered.api.util.weighted.WeightedTable; -import valandur.webapi.serialize.BaseView; - -@ApiModel("MobSpawnerData") -public class MobSpawnerDataView extends BaseView { - - @ApiModelProperty(value = "The maximum number of nearby entities for another mob to spawn", required = true) - public short maximumNearbyEntities; - - @ApiModelProperty(value = "The maximum delay between two consecutive spawns", required = true) - public short maximumSpawnDelay; - - @ApiModelProperty(value = "The minimum delay between two consecutive spawns", required = true) - public short minimumSpawnDelay; - - @ApiModelProperty(value = "The next entity type that will be spawned by this spawner", required = true) - public EntityArchetype nextEntityToSpawn; - - @ApiModelProperty(value = "A weighted table of probability for each entity type to spawn", required = true) - public WeightedTable possibleEntitiesToSpawn; - - @ApiModelProperty(value = "The remaining time until the next spawn attempt", required = true) - public short remainingDelay; - - @ApiModelProperty(value = "The block range within there must be a player to trigger the spawn", required = true) - public short requiredPlayerRange; - - @ApiModelProperty(value = "The amount of entities that will spawn in one attempt", required = true) - public short spawnCount; - - @ApiModelProperty(value = "The range from the spawner within which the entities will spawn", required = true) - public short spawnRange; - - - public MobSpawnerDataView(MobSpawnerData value) { - super(value); - - this.maximumNearbyEntities = value.maximumNearbyEntities().get(); - this.maximumSpawnDelay = value.maximumSpawnDelay().get(); - this.minimumSpawnDelay = value.minimumSpawnDelay().get(); - this.nextEntityToSpawn = value.nextEntityToSpawn().get().get(); - this.possibleEntitiesToSpawn = value.possibleEntitiesToSpawn().getAll(); - this.remainingDelay = value.remainingDelay().get(); - this.requiredPlayerRange = value.requiredPlayerRange().get(); - this.spawnCount = value.spawnCount().get(); - this.spawnRange = value.spawnRange().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.MobSpawnerData; +import org.spongepowered.api.entity.EntityArchetype; +import org.spongepowered.api.util.weighted.WeightedTable; +import valandur.webapi.serialize.BaseView; + +@ApiModel("MobSpawnerData") +public class MobSpawnerDataView extends BaseView { + + @ApiModelProperty(value = "The maximum number of nearby entities for another mob to spawn", required = true) + public short maximumNearbyEntities; + + @ApiModelProperty(value = "The maximum delay between two consecutive spawns", required = true) + public short maximumSpawnDelay; + + @ApiModelProperty(value = "The minimum delay between two consecutive spawns", required = true) + public short minimumSpawnDelay; + + @ApiModelProperty(value = "The next entity type that will be spawned by this spawner", required = true) + public EntityArchetype nextEntityToSpawn; + + @ApiModelProperty(value = "A weighted table of probability for each entity type to spawn", required = true) + public WeightedTable possibleEntitiesToSpawn; + + @ApiModelProperty(value = "The remaining time until the next spawn attempt", required = true) + public short remainingDelay; + + @ApiModelProperty(value = "The block range within there must be a player to trigger the spawn", required = true) + public short requiredPlayerRange; + + @ApiModelProperty(value = "The amount of entities that will spawn in one attempt", required = true) + public short spawnCount; + + @ApiModelProperty(value = "The range from the spawner within which the entities will spawn", required = true) + public short spawnRange; + + + public MobSpawnerDataView(MobSpawnerData value) { + super(value); + + this.maximumNearbyEntities = value.maximumNearbyEntities().get(); + this.maximumSpawnDelay = value.maximumSpawnDelay().get(); + this.minimumSpawnDelay = value.minimumSpawnDelay().get(); + this.nextEntityToSpawn = value.nextEntityToSpawn().get().get(); + this.possibleEntitiesToSpawn = value.possibleEntitiesToSpawn().getAll(); + this.remainingDelay = value.remainingDelay().get(); + this.requiredPlayerRange = value.requiredPlayerRange().get(); + this.spawnCount = value.spawnCount().get(); + this.spawnRange = value.spawnRange().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/MoistureDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MoistureDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/MoistureDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MoistureDataView.java index 54721052..217bb361 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/MoistureDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/MoistureDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.MoistureData; -import valandur.webapi.serialize.BaseView; - -public class MoistureDataView extends BaseView { - - @JsonValue - public int moisture; - - - public MoistureDataView(MoistureData value) { - super(value); - - this.moisture = value.moisture().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.MoistureData; +import valandur.webapi.serialize.BaseView; + +public class MoistureDataView extends BaseView { + + @JsonValue + public int moisture; + + + public MoistureDataView(MoistureData value) { + super(value); + + this.moisture = value.moisture().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/NoteDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/NoteDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/NoteDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/NoteDataView.java index 3558d670..dc9b0b98 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/NoteDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/NoteDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.tileentity.NoteData; -import org.spongepowered.api.data.type.NotePitch; -import valandur.webapi.serialize.BaseView; - -public class NoteDataView extends BaseView { - - @JsonValue - public NotePitch note; - - - public NoteDataView(NoteData value) { - super(value); - - this.note = value.note().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.tileentity.NoteData; +import org.spongepowered.api.data.type.NotePitch; +import valandur.webapi.serialize.BaseView; + +public class NoteDataView extends BaseView { + + @JsonValue + public NotePitch note; + + + public NoteDataView(NoteData value) { + super(value); + + this.note = value.note().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/OccupiedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/OccupiedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/OccupiedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/OccupiedDataView.java index 5d6cc6be..350348ed 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/OccupiedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/OccupiedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.OccupiedData; -import valandur.webapi.serialize.BaseView; - -public class OccupiedDataView extends BaseView { - - @JsonValue - public boolean occupied; - - - public OccupiedDataView(OccupiedData value) { - super(value); - - this.occupied = value.occupied().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.OccupiedData; +import valandur.webapi.serialize.BaseView; + +public class OccupiedDataView extends BaseView { + + @JsonValue + public boolean occupied; + + + public OccupiedDataView(OccupiedData value) { + super(value); + + this.occupied = value.occupied().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/OpenDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/OpenDataView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/data/OpenDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/OpenDataView.java index a2547abb..02b27ca6 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/OpenDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/OpenDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.OpenData; -import valandur.webapi.serialize.BaseView; - -public class OpenDataView extends BaseView { - - @JsonValue - public boolean open; - - - public OpenDataView(OpenData value) { - super(value); - - this.open = value.open().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.OpenData; +import valandur.webapi.serialize.BaseView; + +public class OpenDataView extends BaseView { + + @JsonValue + public boolean open; + + + public OpenDataView(OpenData value) { + super(value); + + this.open = value.open().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/PersistingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PersistingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/PersistingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PersistingDataView.java index e5516135..f1c2908e 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/PersistingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PersistingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.PersistingData; -import valandur.webapi.serialize.BaseView; - -public class PersistingDataView extends BaseView { - - @JsonValue - public boolean persists; - - - public PersistingDataView(PersistingData value) { - super(value); - - this.persists = value.persists().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.PersistingData; +import valandur.webapi.serialize.BaseView; + +public class PersistingDataView extends BaseView { + + @JsonValue + public boolean persists; + + + public PersistingDataView(PersistingData value) { + super(value); + + this.persists = value.persists().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/PickupDelayDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PickupDelayDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/PickupDelayDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PickupDelayDataView.java index 1a1d368f..aa2451cc 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/PickupDelayDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PickupDelayDataView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.PickupDelayData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("PickupDelayData") -public class PickupDelayDataView extends BaseView { - - @ApiModelProperty(value = "The delay that entities must wait to pick up this entity", required = true) - public int delay; - - @ApiModelProperty(value = "True if other entities can never pick up this entity, false otherwise", required = true) - public boolean infinite; - - - public PickupDelayDataView(PickupDelayData value) { - super(value); - - this.delay = value.delay().get(); - this.infinite = value.infinite().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.PickupDelayData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("PickupDelayData") +public class PickupDelayDataView extends BaseView { + + @ApiModelProperty(value = "The delay that entities must wait to pick up this entity", required = true) + public int delay; + + @ApiModelProperty(value = "True if other entities can never pick up this entity, false otherwise", required = true) + public boolean infinite; + + + public PickupDelayDataView(PickupDelayData value) { + super(value); + + this.delay = value.delay().get(); + this.infinite = value.infinite().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/PigSaddleDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PigSaddleDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/PigSaddleDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PigSaddleDataView.java index cbd01dcd..d3a5b66f 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/PigSaddleDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PigSaddleDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.PigSaddleData; -import valandur.webapi.serialize.BaseView; - -public class PigSaddleDataView extends BaseView { - - @JsonValue - public boolean saddle; - - - public PigSaddleDataView(PigSaddleData value) { - super(value); - - this.saddle = value.saddle().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.PigSaddleData; +import valandur.webapi.serialize.BaseView; + +public class PigSaddleDataView extends BaseView { + + @JsonValue + public boolean saddle; + + + public PigSaddleDataView(PigSaddleData value) { + super(value); + + this.saddle = value.saddle().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/PlaceableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlaceableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/PlaceableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlaceableDataView.java index 204e3226..81b8db2b 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/PlaceableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlaceableDataView.java @@ -1,21 +1,21 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.data.manipulator.mutable.item.PlaceableData; -import valandur.webapi.serialize.BaseView; - -import java.util.Set; - -public class PlaceableDataView extends BaseView { - - @JsonValue - public Set types; - - - public PlaceableDataView(PlaceableData value) { - super(value); - - this.types = value.placeable().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.block.BlockType; +import org.spongepowered.api.data.manipulator.mutable.item.PlaceableData; +import valandur.webapi.serialize.BaseView; + +import java.util.Set; + +public class PlaceableDataView extends BaseView { + + @JsonValue + public Set types; + + + public PlaceableDataView(PlaceableData value) { + super(value); + + this.types = value.placeable().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/PlayerCreatedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlayerCreatedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/PlayerCreatedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlayerCreatedDataView.java index 3be70055..fb9732d9 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/PlayerCreatedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlayerCreatedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.PlayerCreatedData; -import valandur.webapi.serialize.BaseView; - -public class PlayerCreatedDataView extends BaseView { - - @JsonValue - public boolean created; - - - public PlayerCreatedDataView(PlayerCreatedData value) { - super(value); - - this.created = value.playerCreated().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.PlayerCreatedData; +import valandur.webapi.serialize.BaseView; + +public class PlayerCreatedDataView extends BaseView { + + @JsonValue + public boolean created; + + + public PlayerCreatedDataView(PlayerCreatedData value) { + super(value); + + this.created = value.playerCreated().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/PlayingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlayingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/PlayingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlayingDataView.java index 387406ac..99f61972 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/PlayingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PlayingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.PlayingData; -import valandur.webapi.serialize.BaseView; - -public class PlayingDataView extends BaseView { - - @JsonValue - public boolean playing; - - - public PlayingDataView(PlayingData value) { - super(value); - - this.playing = value.playing().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.PlayingData; +import valandur.webapi.serialize.BaseView; + +public class PlayingDataView extends BaseView { + + @JsonValue + public boolean playing; + + + public PlayingDataView(PlayingData value) { + super(value); + + this.playing = value.playing().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/PoweredDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PoweredDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/PoweredDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PoweredDataView.java index cd0ec072..4ed8a3de 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/PoweredDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PoweredDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.PoweredData; -import valandur.webapi.serialize.BaseView; - -public class PoweredDataView extends BaseView { - - @JsonValue - public boolean powered; - - - public PoweredDataView(PoweredData value) { - super(value); - - this.powered = value.powered().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.PoweredData; +import valandur.webapi.serialize.BaseView; + +public class PoweredDataView extends BaseView { + + @JsonValue + public boolean powered; + + + public PoweredDataView(PoweredData value) { + super(value); + + this.powered = value.powered().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/RedstonePoweredDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RedstonePoweredDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/RedstonePoweredDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RedstonePoweredDataView.java index 5a823c16..d62931a5 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/RedstonePoweredDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RedstonePoweredDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.RedstonePoweredData; -import valandur.webapi.serialize.BaseView; - -public class RedstonePoweredDataView extends BaseView { - - @JsonValue - public int power; - - - public RedstonePoweredDataView(RedstonePoweredData value) { - super(value); - - this.power = value.power().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.RedstonePoweredData; +import valandur.webapi.serialize.BaseView; + +public class RedstonePoweredDataView extends BaseView { + + @JsonValue + public int power; + + + public RedstonePoweredDataView(RedstonePoweredData value) { + super(value); + + this.power = value.power().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/RepresentedItemDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RepresentedItemDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/RepresentedItemDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RepresentedItemDataView.java index e9dc47f6..18c619ea 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/RepresentedItemDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RepresentedItemDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.RepresentedItemData; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import valandur.webapi.serialize.BaseView; - -public class RepresentedItemDataView extends BaseView { - - @JsonValue - public ItemStackSnapshot item; - - - public RepresentedItemDataView(RepresentedItemData value) { - super(value); - - this.item = value.item().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.RepresentedItemData; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import valandur.webapi.serialize.BaseView; + +public class RepresentedItemDataView extends BaseView { + + @JsonValue + public ItemStackSnapshot item; + + + public RepresentedItemDataView(RepresentedItemData value) { + super(value); + + this.item = value.item().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/RepresentedPlayerDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RepresentedPlayerDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/RepresentedPlayerDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RepresentedPlayerDataView.java index 51f4f786..2f5d3a29 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/RepresentedPlayerDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/RepresentedPlayerDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.RepresentedPlayerData; -import valandur.webapi.serialize.BaseView; - -public class RepresentedPlayerDataView extends BaseView { - - @JsonValue - public String owner; - - - public RepresentedPlayerDataView(RepresentedPlayerData value) { - super(value); - - this.owner = value.owner().get().getName().orElse(null); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.RepresentedPlayerData; +import valandur.webapi.serialize.BaseView; + +public class RepresentedPlayerDataView extends BaseView { + + @JsonValue + public String owner; + + + public RepresentedPlayerDataView(RepresentedPlayerData value) { + super(value); + + this.owner = value.owner().get().getName().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ScreamingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ScreamingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ScreamingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ScreamingDataView.java index 8db293df..4b027472 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ScreamingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ScreamingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.ScreamingData; -import valandur.webapi.serialize.BaseView; - -public class ScreamingDataView extends BaseView { - - @JsonValue - public boolean screaming; - - - public ScreamingDataView(ScreamingData value) { - super(value); - - this.screaming = value.screaming().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.ScreamingData; +import valandur.webapi.serialize.BaseView; + +public class ScreamingDataView extends BaseView { + + @JsonValue + public boolean screaming; + + + public ScreamingDataView(ScreamingData value) { + super(value); + + this.screaming = value.screaming().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SeamlessDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SeamlessDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SeamlessDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SeamlessDataView.java index 7dcc479d..411b8a99 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SeamlessDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SeamlessDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.SeamlessData; -import valandur.webapi.serialize.BaseView; - -public class SeamlessDataView extends BaseView { - - @JsonValue - public boolean seamless; - - - public SeamlessDataView(SeamlessData value) { - super(value); - - this.seamless = value.seamless().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.SeamlessData; +import valandur.webapi.serialize.BaseView; + +public class SeamlessDataView extends BaseView { + + @JsonValue + public boolean seamless; + + + public SeamlessDataView(SeamlessData value) { + super(value); + + this.seamless = value.seamless().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ShatteringDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ShatteringDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ShatteringDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ShatteringDataView.java index 1e31c67c..9f509347 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ShatteringDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ShatteringDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.ShatteringData; -import valandur.webapi.serialize.BaseView; - -public class ShatteringDataView extends BaseView { - - @JsonValue - public boolean shatters; - - - public ShatteringDataView(ShatteringData value) { - super(value); - - this.shatters = value.willShatter().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.ShatteringData; +import valandur.webapi.serialize.BaseView; + +public class ShatteringDataView extends BaseView { + + @JsonValue + public boolean shatters; + + + public ShatteringDataView(ShatteringData value) { + super(value); + + this.shatters = value.willShatter().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/ShearedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ShearedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/ShearedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ShearedDataView.java index 2a1a3d34..aa213970 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/ShearedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/ShearedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.ShearedData; -import valandur.webapi.serialize.BaseView; - -public class ShearedDataView extends BaseView { - - @JsonValue - public boolean sheared; - - - public ShearedDataView(ShearedData value) { - super(value); - - this.sheared = value.sheared().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.ShearedData; +import valandur.webapi.serialize.BaseView; + +public class ShearedDataView extends BaseView { + + @JsonValue + public boolean sheared; + + + public ShearedDataView(ShearedData value) { + super(value); + + this.sheared = value.sheared().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SilentDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SilentDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SilentDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SilentDataView.java index 070fe755..3d01bb9d 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SilentDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SilentDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.SilentData; -import valandur.webapi.serialize.BaseView; - -public class SilentDataView extends BaseView { - - @JsonValue - public boolean silent; - - - public SilentDataView(SilentData value) { - super(value); - - this.silent = value.silent().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.SilentData; +import valandur.webapi.serialize.BaseView; + +public class SilentDataView extends BaseView { + + @JsonValue + public boolean silent; + + + public SilentDataView(SilentData value) { + super(value); + + this.silent = value.silent().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SittingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SittingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SittingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SittingDataView.java index 0b0c76a6..3951074e 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SittingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SittingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.SittingData; -import valandur.webapi.serialize.BaseView; - -public class SittingDataView extends BaseView { - - @JsonValue - public boolean sitting; - - - public SittingDataView(SittingData value) { - super(value); - - this.sitting = value.sitting().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.SittingData; +import valandur.webapi.serialize.BaseView; + +public class SittingDataView extends BaseView { + + @JsonValue + public boolean sitting; + + + public SittingDataView(SittingData value) { + super(value); + + this.sitting = value.sitting().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SkinDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SkinDataView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/data/SkinDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SkinDataView.java index af43eaa5..2331c694 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SkinDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SkinDataView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.SkinData; -import valandur.webapi.serialize.BaseView; - -import java.util.UUID; - -public class SkinDataView extends BaseView { - - @JsonValue - public UUID uuid; - - - public SkinDataView(SkinData value) { - super(value); - - this.uuid = value.skinUniqueId().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.SkinData; +import valandur.webapi.serialize.BaseView; + +import java.util.UUID; + +public class SkinDataView extends BaseView { + + @JsonValue + public UUID uuid; + + + public SkinDataView(SkinData value) { + super(value); + + this.uuid = value.skinUniqueId().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SleepingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SleepingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SleepingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SleepingDataView.java index e8d74840..31914c63 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SleepingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SleepingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.SleepingData; -import valandur.webapi.serialize.BaseView; - -public class SleepingDataView extends BaseView { - - @JsonValue - public boolean sleeping; - - - public SleepingDataView(SleepingData value) { - super(value); - - this.sleeping = value.sleeping().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.SleepingData; +import valandur.webapi.serialize.BaseView; + +public class SleepingDataView extends BaseView { + + @JsonValue + public boolean sleeping; + + + public SleepingDataView(SleepingData value) { + super(value); + + this.sleeping = value.sleeping().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SlimeDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SlimeDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SlimeDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SlimeDataView.java index 548b9481..a8b801c1 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SlimeDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SlimeDataView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.SlimeData; -import valandur.webapi.serialize.BaseView; - -@ApiModel("SlimeData") -public class SlimeDataView extends BaseView { - - @ApiModelProperty(value = "The size of the slime entity", required = true) - public int size; - - - public SlimeDataView(SlimeData value) { - super(value); - - this.size = value.size().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.SlimeData; +import valandur.webapi.serialize.BaseView; + +@ApiModel("SlimeData") +public class SlimeDataView extends BaseView { + + @ApiModelProperty(value = "The size of the slime entity", required = true) + public int size; + + + public SlimeDataView(SlimeData value) { + super(value); + + this.size = value.size().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SneakingDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SneakingDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SneakingDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SneakingDataView.java index df4bd627..04b4c6ee 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SneakingDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SneakingDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.SneakingData; -import valandur.webapi.serialize.BaseView; - -public class SneakingDataView extends BaseView { - - @JsonValue - public boolean sneaking; - - - public SneakingDataView(SneakingData value) { - super(value); - - this.sneaking = value.sneaking().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.SneakingData; +import valandur.webapi.serialize.BaseView; + +public class SneakingDataView extends BaseView { + + @JsonValue + public boolean sneaking; + + + public SneakingDataView(SneakingData value) { + super(value); + + this.sneaking = value.sneaking().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SnowedDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SnowedDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SnowedDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SnowedDataView.java index ae527556..2329427b 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SnowedDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SnowedDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.block.SnowedData; -import valandur.webapi.serialize.BaseView; - -public class SnowedDataView extends BaseView { - - @JsonValue - public boolean snow; - - - public SnowedDataView(SnowedData value) { - super(value); - - this.snow = value.hasSnow().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.block.SnowedData; +import valandur.webapi.serialize.BaseView; + +public class SnowedDataView extends BaseView { + + @JsonValue + public boolean snow; + + + public SnowedDataView(SnowedData value) { + super(value); + + this.snow = value.hasSnow().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/SprintDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SprintDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/SprintDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SprintDataView.java index beefdfd4..49a5a660 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/SprintDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/SprintDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.SprintData; -import valandur.webapi.serialize.BaseView; - -public class SprintDataView extends BaseView { - - @JsonValue - public boolean spriting; - - - public SprintDataView(SprintData value) { - super(value); - - this.spriting = value.sprinting().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.SprintData; +import valandur.webapi.serialize.BaseView; + +public class SprintDataView extends BaseView { + + @JsonValue + public boolean spriting; + + + public SprintDataView(SprintData value) { + super(value); + + this.spriting = value.sprinting().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/StatisticDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StatisticDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/StatisticDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StatisticDataView.java index 26626851..570c6871 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/StatisticDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StatisticDataView.java @@ -1,34 +1,34 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.StatisticData; -import org.spongepowered.api.statistic.Statistic; -import valandur.webapi.serialize.BaseView; - -import java.util.List; -import java.util.stream.Collectors; - -public class StatisticDataView extends BaseView { - - @JsonValue - public List getStatistics() { - return value.getMapValues().stream() - .map(mv -> new Stat(mv.getKey(), mv.getValue())) - .collect(Collectors.toList()); - } - - public StatisticDataView(StatisticData value) { - super(value); - } - - - public static class Stat { - public Statistic stat; - public Long value; - - public Stat(Statistic stat, Long value) { - this.stat = stat; - this.value = value; - } - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.StatisticData; +import org.spongepowered.api.statistic.Statistic; +import valandur.webapi.serialize.BaseView; + +import java.util.List; +import java.util.stream.Collectors; + +public class StatisticDataView extends BaseView { + + @JsonValue + public List getStatistics() { + return value.getMapValues().stream() + .map(mv -> new Stat(mv.getKey(), mv.getValue())) + .collect(Collectors.toList()); + } + + public StatisticDataView(StatisticData value) { + super(value); + } + + + public static class Stat { + public Statistic stat; + public Long value; + + public Stat(Statistic stat, Long value) { + this.stat = stat; + this.value = value; + } + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/StructureDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StructureDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/StructureDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StructureDataView.java index 90a02a98..7986a9fc 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/StructureDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StructureDataView.java @@ -1,58 +1,58 @@ -package valandur.webapi.serialize.view.data; - -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.tileentity.StructureData; -import org.spongepowered.api.data.type.StructureMode; -import valandur.webapi.serialize.BaseView; - -@ApiModel("StructureData") -public class StructureDataView extends BaseView { - - @ApiModelProperty(value = "The author of this structure", required = true) - public String author; - - @ApiModelProperty(value = "True if entities are not part of this structure, false otherwise", required = true) - public boolean ignoreEntities; - - @ApiModelProperty(value = "The integrity of the structure", required = true) - public float integrity; - - @ApiModelProperty(value = "The mode of the structure", required = true) - public StructureMode mode; - - @ApiModelProperty(value = "The position of the structure", required = true) - public Vector3i position; - - @ApiModelProperty(value = "True if the structure is powered, false otherwise", required = true) - public boolean powered; - - @ApiModelProperty(value = "The seed of this structure", required = true) - public long seed; - - @ApiModelProperty(value = "True if the air blocks for this structure are shown, false otherwise", required = true) - public boolean showAir; - - @ApiModelProperty(value = "True if the bounding box for this structure is shown, false otherwise", required = true) - public boolean showBoundingBox; - - @ApiModelProperty(value = "The size of this structure", required = true) - public Vector3i size; - - - public StructureDataView(StructureData value) { - super(value); - - this.author = value.author().get(); - this.ignoreEntities = value.ignoreEntities().get(); - this.integrity = value.integrity().get(); - this.mode = value.mode().get(); - this.position = value.position().get(); - this.powered = value.powered().get(); - this.seed = value.seed().get(); - this.showAir = value.showAir().get(); - this.showBoundingBox = value.showBoundingBox().get(); - this.size = value.size().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.tileentity.StructureData; +import org.spongepowered.api.data.type.StructureMode; +import valandur.webapi.serialize.BaseView; + +@ApiModel("StructureData") +public class StructureDataView extends BaseView { + + @ApiModelProperty(value = "The author of this structure", required = true) + public String author; + + @ApiModelProperty(value = "True if entities are not part of this structure, false otherwise", required = true) + public boolean ignoreEntities; + + @ApiModelProperty(value = "The integrity of the structure", required = true) + public float integrity; + + @ApiModelProperty(value = "The mode of the structure", required = true) + public StructureMode mode; + + @ApiModelProperty(value = "The position of the structure", required = true) + public Vector3i position; + + @ApiModelProperty(value = "True if the structure is powered, false otherwise", required = true) + public boolean powered; + + @ApiModelProperty(value = "The seed of this structure", required = true) + public long seed; + + @ApiModelProperty(value = "True if the air blocks for this structure are shown, false otherwise", required = true) + public boolean showAir; + + @ApiModelProperty(value = "True if the bounding box for this structure is shown, false otherwise", required = true) + public boolean showBoundingBox; + + @ApiModelProperty(value = "The size of this structure", required = true) + public Vector3i size; + + + public StructureDataView(StructureData value) { + super(value); + + this.author = value.author().get(); + this.ignoreEntities = value.ignoreEntities().get(); + this.integrity = value.integrity().get(); + this.mode = value.mode().get(); + this.position = value.position().get(); + this.powered = value.powered().get(); + this.seed = value.seed().get(); + this.showAir = value.showAir().get(); + this.showBoundingBox = value.showBoundingBox().get(); + this.size = value.size().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/StuckArrowsDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StuckArrowsDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/StuckArrowsDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StuckArrowsDataView.java index b4584658..51241821 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/StuckArrowsDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/StuckArrowsDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.entity.StuckArrowsData; -import valandur.webapi.serialize.BaseView; - -public class StuckArrowsDataView extends BaseView { - - @JsonValue - public int stuckArrows; - - - public StuckArrowsDataView(StuckArrowsData value) { - super(value); - - this.stuckArrows = value.stuckArrows().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.entity.StuckArrowsData; +import valandur.webapi.serialize.BaseView; + +public class StuckArrowsDataView extends BaseView { + + @JsonValue + public int stuckArrows; + + + public StuckArrowsDataView(StuckArrowsData value) { + super(value); + + this.stuckArrows = value.stuckArrows().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/TameableDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/TameableDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/TameableDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/TameableDataView.java index 917c2401..054c7a3a 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/TameableDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/TameableDataView.java @@ -1,26 +1,26 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.TameableData; -import valandur.webapi.serialize.BaseView; - -import java.util.UUID; - -@ApiModel("TameableData") -public class TameableDataView extends BaseView { - - @ApiModelProperty(value = "True if this entity is tamed, false otherwise", required = true) - public boolean tamed; - - @ApiModelProperty("The UUID of the entity which tamed this entity") - public UUID owner; - - - public TameableDataView(TameableData value) { - super(value); - - this.tamed = value.owner().exists(); - this.owner = value.owner().get().orElse(null); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.TameableData; +import valandur.webapi.serialize.BaseView; + +import java.util.UUID; + +@ApiModel("TameableData") +public class TameableDataView extends BaseView { + + @ApiModelProperty(value = "True if this entity is tamed, false otherwise", required = true) + public boolean tamed; + + @ApiModelProperty("The UUID of the entity which tamed this entity") + public UUID owner; + + + public TameableDataView(TameableData value) { + super(value); + + this.tamed = value.owner().exists(); + this.owner = value.owner().get().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/TargetedLocationDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/TargetedLocationDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/TargetedLocationDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/TargetedLocationDataView.java index 76a43d0b..a373de84 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/TargetedLocationDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/TargetedLocationDataView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import com.flowpowered.math.vector.Vector3d; -import org.spongepowered.api.data.manipulator.mutable.TargetedLocationData; -import valandur.webapi.serialize.BaseView; - -public class TargetedLocationDataView extends BaseView { - - @JsonValue - public Vector3d target; - - - public TargetedLocationDataView(TargetedLocationData value) { - super(value); - - this.target = value.target().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import com.flowpowered.math.vector.Vector3d; +import org.spongepowered.api.data.manipulator.mutable.TargetedLocationData; +import valandur.webapi.serialize.BaseView; + +public class TargetedLocationDataView extends BaseView { + + @JsonValue + public Vector3d target; + + + public TargetedLocationDataView(TargetedLocationData value) { + super(value); + + this.target = value.target().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/VariantDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/VariantDataView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/data/VariantDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/VariantDataView.java index cbd01c38..4c5b4a43 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/VariantDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/VariantDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.VariantData; -import valandur.webapi.serialize.BaseView; - -public class VariantDataView extends BaseView { - - @JsonValue - public Object type; - - - public VariantDataView(VariantData value) { - super(value); - - this.type = value.type().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.VariantData; +import valandur.webapi.serialize.BaseView; + +public class VariantDataView extends BaseView { + + @JsonValue + public Object type; + + + public VariantDataView(VariantData value) { + super(value); + + this.type = value.type().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/VehicleDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/VehicleDataView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/data/VehicleDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/VehicleDataView.java index 095fc54e..714c08ad 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/VehicleDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/VehicleDataView.java @@ -1,25 +1,25 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.entity.VehicleData; -import org.spongepowered.api.entity.EntitySnapshot; -import valandur.webapi.serialize.BaseView; - -@ApiModel("VehicleData") -public class VehicleDataView extends BaseView { - - @ApiModelProperty(value = "The base vehicle entity", required = true) - public EntitySnapshot baseVehicle; - - @ApiModelProperty(value = "The vehicle entity itself", required = true) - public EntitySnapshot vehicle; - - - public VehicleDataView(VehicleData value) { - super(value); - - this.baseVehicle = value.baseVehicle().get(); - this.vehicle = value.vehicle().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.entity.VehicleData; +import org.spongepowered.api.entity.EntitySnapshot; +import valandur.webapi.serialize.BaseView; + +@ApiModel("VehicleData") +public class VehicleDataView extends BaseView { + + @ApiModelProperty(value = "The base vehicle entity", required = true) + public EntitySnapshot baseVehicle; + + @ApiModelProperty(value = "The vehicle entity itself", required = true) + public EntitySnapshot vehicle; + + + public VehicleDataView(VehicleData value) { + super(value); + + this.baseVehicle = value.baseVehicle().get(); + this.vehicle = value.vehicle().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/WetDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/WetDataView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/data/WetDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/WetDataView.java index 46991983..6bee1d97 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/WetDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/WetDataView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.data; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.data.manipulator.mutable.WetData; -import valandur.webapi.serialize.BaseView; - -public class WetDataView extends BaseView { - - @JsonValue - public boolean wet; - - - public WetDataView(WetData value) { - super(value); - - this.wet = value.wet().get(); - } -} +package valandur.webapi.serialize.view.data; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.data.manipulator.mutable.WetData; +import valandur.webapi.serialize.BaseView; + +public class WetDataView extends BaseView { + + @JsonValue + public boolean wet; + + + public WetDataView(WetData value) { + super(value); + + this.wet = value.wet().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/data/WireAttachmentDataView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/WireAttachmentDataView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/data/WireAttachmentDataView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/WireAttachmentDataView.java index 8f2bd718..212cb8ad 100644 --- a/src/main/java/valandur/webapi/serialize/view/data/WireAttachmentDataView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/WireAttachmentDataView.java @@ -1,33 +1,33 @@ -package valandur.webapi.serialize.view.data; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.manipulator.mutable.block.WireAttachmentData; -import org.spongepowered.api.data.type.WireAttachmentType; -import valandur.webapi.serialize.BaseView; - -@ApiModel("WireAttachmentData") -public class WireAttachmentDataView extends BaseView { - - @ApiModelProperty(value = "The type of wire attachment to the east of this entity", required = true) - public WireAttachmentType east; - - @ApiModelProperty(value = "The type of wire attachment to the north of this entity", required = true) - public WireAttachmentType north; - - @ApiModelProperty(value = "The type of wire attachment to the south of this entity", required = true) - public WireAttachmentType south; - - @ApiModelProperty(value = "The type of wire attachment to the west of this entity", required = true) - public WireAttachmentType west; - - - public WireAttachmentDataView(WireAttachmentData value) { - super(value); - - this.east = value.wireAttachmentEast().get(); - this.north = value.wireAttachmentNorth().get(); - this.south = value.wireAttachmentSouth().get(); - this.west = value.wireAttachmentWest().get(); - } -} +package valandur.webapi.serialize.view.data; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.manipulator.mutable.block.WireAttachmentData; +import org.spongepowered.api.data.type.WireAttachmentType; +import valandur.webapi.serialize.BaseView; + +@ApiModel("WireAttachmentData") +public class WireAttachmentDataView extends BaseView { + + @ApiModelProperty(value = "The type of wire attachment to the east of this entity", required = true) + public WireAttachmentType east; + + @ApiModelProperty(value = "The type of wire attachment to the north of this entity", required = true) + public WireAttachmentType north; + + @ApiModelProperty(value = "The type of wire attachment to the south of this entity", required = true) + public WireAttachmentType south; + + @ApiModelProperty(value = "The type of wire attachment to the west of this entity", required = true) + public WireAttachmentType west; + + + public WireAttachmentDataView(WireAttachmentData value) { + super(value); + + this.east = value.wireAttachmentEast().get(); + this.north = value.wireAttachmentNorth().get(); + this.south = value.wireAttachmentSouth().get(); + this.west = value.wireAttachmentWest().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/economy/AccountView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/economy/AccountView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/economy/AccountView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/economy/AccountView.java index b18af8a0..fa10293a 100644 --- a/src/main/java/valandur/webapi/serialize/view/economy/AccountView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/economy/AccountView.java @@ -1,36 +1,36 @@ -package valandur.webapi.serialize.view.economy; - -import io.swagger.annotations.ApiModel; -import org.spongepowered.api.service.economy.account.Account; -import org.spongepowered.api.text.Text; -import valandur.webapi.serialize.BaseView; - -import java.math.BigDecimal; -import java.util.Map; -import java.util.stream.Collectors; - -@ApiModel("Account") -public class AccountView extends BaseView { - - public String getId() { - return value.getIdentifier(); - } - - public String getFriendlyId() { - return value.getFriendlyIdentifier().orElse(null); - } - - public Text getDisplayName() { - return value.getDisplayName(); - } - - public Map getBalances() { - return value.getBalances().entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey().getId(), Map.Entry::getValue)); - } - - - public AccountView(Account value) { - super(value); - } -} +package valandur.webapi.serialize.view.economy; + +import io.swagger.annotations.ApiModel; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.text.Text; +import valandur.webapi.serialize.BaseView; + +import java.math.BigDecimal; +import java.util.Map; +import java.util.stream.Collectors; + +@ApiModel("Account") +public class AccountView extends BaseView { + + public String getId() { + return value.getIdentifier(); + } + + public String getFriendlyId() { + return value.getFriendlyIdentifier().orElse(null); + } + + public Text getDisplayName() { + return value.getDisplayName(); + } + + public Map getBalances() { + return value.getBalances().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey().getId(), Map.Entry::getValue)); + } + + + public AccountView(Account value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/economy/CurrencyView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/economy/CurrencyView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/economy/CurrencyView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/economy/CurrencyView.java index e621758a..aa23d037 100644 --- a/src/main/java/valandur/webapi/serialize/view/economy/CurrencyView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/economy/CurrencyView.java @@ -1,39 +1,39 @@ -package valandur.webapi.serialize.view.economy; - -import io.swagger.annotations.ApiModel; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.text.Text; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Currency") -public class CurrencyView extends BaseView { - - public String getId() { - return value.getId(); - } - - public String getName() { - return value.getName(); - } - - public Text getDisplayName() { - return value.getDisplayName(); - } - - public Text getPluralDisplayName() { - return value.getPluralDisplayName(); - } - - public Text getSymbol() { - return value.getSymbol(); - } - - public Integer getDefaultFractionDigits() { - return value.getDefaultFractionDigits(); - } - - - public CurrencyView(Currency value) { - super(value); - } -} +package valandur.webapi.serialize.view.economy; + +import io.swagger.annotations.ApiModel; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.text.Text; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Currency") +public class CurrencyView extends BaseView { + + public String getId() { + return value.getId(); + } + + public String getName() { + return value.getName(); + } + + public Text getDisplayName() { + return value.getDisplayName(); + } + + public Text getPluralDisplayName() { + return value.getPluralDisplayName(); + } + + public Text getSymbol() { + return value.getSymbol(); + } + + public Integer getDefaultFractionDigits() { + return value.getDefaultFractionDigits(); + } + + + public CurrencyView(Currency value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/entity/CareerView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/CareerView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/entity/CareerView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/CareerView.java index d209e0f4..0660cd9a 100644 --- a/src/main/java/valandur/webapi/serialize/view/entity/CareerView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/CareerView.java @@ -1,29 +1,29 @@ -package valandur.webapi.serialize.view.entity; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.type.Career; -import org.spongepowered.api.data.type.Profession; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Career") -public class CareerView extends BaseView { - - @ApiModelProperty(value = "The unique id of the career", required = true) - public String id; - - @ApiModelProperty(value = "The name of the career", required = true) - public String name; - - @ApiModelProperty(value = "The profession within the career", required = true) - public Profession profession; - - - public CareerView(Career value) { - super(value); - - this.id = value.getId(); - this.name = value.getTranslation().get(); - this.profession = value.getProfession(); - } -} +package valandur.webapi.serialize.view.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.type.Career; +import org.spongepowered.api.data.type.Profession; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Career") +public class CareerView extends BaseView { + + @ApiModelProperty(value = "The unique id of the career", required = true) + public String id; + + @ApiModelProperty(value = "The name of the career", required = true) + public String name; + + @ApiModelProperty(value = "The profession within the career", required = true) + public Profession profession; + + + public CareerView(Career value) { + super(value); + + this.id = value.getId(); + this.name = value.getTranslation().get(); + this.profession = value.getProfession(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/entity/EntityArchetypeView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/EntityArchetypeView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/entity/EntityArchetypeView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/EntityArchetypeView.java index cd826f54..2f3b9688 100644 --- a/src/main/java/valandur/webapi/serialize/view/entity/EntityArchetypeView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/EntityArchetypeView.java @@ -1,21 +1,21 @@ -package valandur.webapi.serialize.view.entity; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.entity.EntityArchetype; -import org.spongepowered.api.entity.EntityType; -import valandur.webapi.serialize.BaseView; - -@ApiModel("EntityArchtype") -public class EntityArchetypeView extends BaseView { - - @ApiModelProperty(value = "The entity type represented by this archtype", required = true) - public EntityType type; - - - public EntityArchetypeView(EntityArchetype value) { - super(value); - - this.type = value.getType(); - } -} +package valandur.webapi.serialize.view.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.entity.EntityArchetype; +import org.spongepowered.api.entity.EntityType; +import valandur.webapi.serialize.BaseView; + +@ApiModel("EntityArchtype") +public class EntityArchetypeView extends BaseView { + + @ApiModelProperty(value = "The entity type represented by this archtype", required = true) + public EntityType type; + + + public EntityArchetypeView(EntityArchetype value) { + super(value); + + this.type = value.getType(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/entity/EntitySnapshotView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/EntitySnapshotView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/entity/EntitySnapshotView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/EntitySnapshotView.java index dbfd470f..91b2baaa 100644 --- a/src/main/java/valandur/webapi/serialize/view/entity/EntitySnapshotView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/EntitySnapshotView.java @@ -1,33 +1,33 @@ -package valandur.webapi.serialize.view.entity; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.entity.EntitySnapshot; -import org.spongepowered.api.entity.EntityType; -import org.spongepowered.api.entity.Transform; -import org.spongepowered.api.world.World; -import valandur.webapi.serialize.BaseView; - -import java.util.UUID; - -@ApiModel("EntitySnapshot") -public class EntitySnapshotView extends BaseView { - - @ApiModelProperty("The uuid of the entity") - public UUID uuid; - - @ApiModelProperty("The type of the entity") - public EntityType type; - - @ApiModelProperty("The transform of the entity") - public Transform transform; - - - public EntitySnapshotView(EntitySnapshot value) { - super(value); - - this.uuid = value.getUniqueId().orElse(null); - this.type = value.getType(); - this.transform = value.getTransform().orElse(null); - } -} +package valandur.webapi.serialize.view.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.entity.EntitySnapshot; +import org.spongepowered.api.entity.EntityType; +import org.spongepowered.api.entity.Transform; +import org.spongepowered.api.world.World; +import valandur.webapi.serialize.BaseView; + +import java.util.UUID; + +@ApiModel("EntitySnapshot") +public class EntitySnapshotView extends BaseView { + + @ApiModelProperty("The uuid of the entity") + public UUID uuid; + + @ApiModelProperty("The type of the entity") + public EntityType type; + + @ApiModelProperty("The transform of the entity") + public Transform transform; + + + public EntitySnapshotView(EntitySnapshot value) { + super(value); + + this.uuid = value.getUniqueId().orElse(null); + this.type = value.getType(); + this.transform = value.getTransform().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/entity/TradeOfferView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/TradeOfferView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/entity/TradeOfferView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/TradeOfferView.java index f78cdf36..6792f7c3 100644 --- a/src/main/java/valandur/webapi/serialize/view/entity/TradeOfferView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/entity/TradeOfferView.java @@ -1,45 +1,45 @@ -package valandur.webapi.serialize.view.entity; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import org.spongepowered.api.item.merchant.TradeOffer; -import valandur.webapi.serialize.BaseView; - -@ApiModel("TradeOffer") -public class TradeOfferView extends BaseView { - - @ApiModelProperty(value = "True if this offer is expired, false otherwise", required = true) - public boolean expired; - - @ApiModelProperty(value = "True if this trade grants experience when completed, false otherwise", required = true) - public boolean grantsExp; - - @ApiModelProperty(value = "The amount of times this trade has been used", required = true) - public int uses; - - @ApiModelProperty(value = "The maximum amount of times that this trade can be used", required = true) - public int maxUses; - - @ApiModelProperty(value = "The first item that is required for the trade", required = true) - public ItemStackSnapshot firstBuyingItem; - - @ApiModelProperty("The second item that is required for the trade") - public ItemStackSnapshot secondBuyingItem; - - @ApiModelProperty(value = "The item that is received when trading", required = true) - public ItemStackSnapshot sellingItem; - - - public TradeOfferView(TradeOffer value) { - super(value); - - this.expired = value.hasExpired(); - this.grantsExp = value.doesGrantExperience(); - this.uses = value.getUses(); - this.maxUses = value.getUses(); - this.firstBuyingItem = value.getFirstBuyingItem(); - this.secondBuyingItem = value.getSecondBuyingItem().orElse(null); - this.sellingItem = value.getSellingItem(); - } -} +package valandur.webapi.serialize.view.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import org.spongepowered.api.item.merchant.TradeOffer; +import valandur.webapi.serialize.BaseView; + +@ApiModel("TradeOffer") +public class TradeOfferView extends BaseView { + + @ApiModelProperty(value = "True if this offer is expired, false otherwise", required = true) + public boolean expired; + + @ApiModelProperty(value = "True if this trade grants experience when completed, false otherwise", required = true) + public boolean grantsExp; + + @ApiModelProperty(value = "The amount of times this trade has been used", required = true) + public int uses; + + @ApiModelProperty(value = "The maximum amount of times that this trade can be used", required = true) + public int maxUses; + + @ApiModelProperty(value = "The first item that is required for the trade", required = true) + public ItemStackSnapshot firstBuyingItem; + + @ApiModelProperty("The second item that is required for the trade") + public ItemStackSnapshot secondBuyingItem; + + @ApiModelProperty(value = "The item that is received when trading", required = true) + public ItemStackSnapshot sellingItem; + + + public TradeOfferView(TradeOffer value) { + super(value); + + this.expired = value.hasExpired(); + this.grantsExp = value.doesGrantExperience(); + this.uses = value.getUses(); + this.maxUses = value.getUses(); + this.firstBuyingItem = value.getFirstBuyingItem(); + this.secondBuyingItem = value.getSecondBuyingItem().orElse(null); + this.sellingItem = value.getSellingItem(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/event/DamageSourceView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/event/DamageSourceView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/event/DamageSourceView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/event/DamageSourceView.java index 7f8d56e5..f6a129e5 100644 --- a/src/main/java/valandur/webapi/serialize/view/event/DamageSourceView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/event/DamageSourceView.java @@ -1,45 +1,45 @@ -package valandur.webapi.serialize.view.event; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.event.cause.entity.damage.DamageType; -import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; -import valandur.webapi.serialize.BaseView; - -@ApiModel("DamageSource") -public class DamageSourceView extends BaseView { - - @ApiModelProperty(value = "True if this damage source can affect players in creative, false otherwise", required = true) - public boolean affectsCreative; - - @ApiModelProperty(value = "True if the damage value done by this source is absolute, false otherwise", required = true) - public boolean absolute; - - @ApiModelProperty(value = "True if the damage done by this source disregards armour, false otherwise", required = true) - public boolean bypassingArmour; - - @ApiModelProperty(value = "True if this source produces explosive damage, false otherwise", required = true) - public boolean explosive; - - @ApiModelProperty(value = "True if this source produces magic damage, false otherwise", required = true) - public boolean magic; - - @ApiModelProperty(value = "True if the damage of this source is scaled by the difficulty, false otherwise", required = true) - public boolean scaledByDifficulty; - - @ApiModelProperty(value = "The damage type inflicted by this damage source", required = true) - public DamageType damageType; - - - public DamageSourceView(DamageSource value) { - super(value); - - this.affectsCreative = value.doesAffectCreative(); - this.absolute = value.isAbsolute(); - this.bypassingArmour = value.isBypassingArmor(); - this.explosive = value.isExplosive(); - this.magic = value.isMagic(); - this.scaledByDifficulty = value.isScaledByDifficulty(); - this.damageType = value.getType(); - } -} +package valandur.webapi.serialize.view.event; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.event.cause.entity.damage.DamageType; +import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; +import valandur.webapi.serialize.BaseView; + +@ApiModel("DamageSource") +public class DamageSourceView extends BaseView { + + @ApiModelProperty(value = "True if this damage source can affect players in creative, false otherwise", required = true) + public boolean affectsCreative; + + @ApiModelProperty(value = "True if the damage value done by this source is absolute, false otherwise", required = true) + public boolean absolute; + + @ApiModelProperty(value = "True if the damage done by this source disregards armour, false otherwise", required = true) + public boolean bypassingArmour; + + @ApiModelProperty(value = "True if this source produces explosive damage, false otherwise", required = true) + public boolean explosive; + + @ApiModelProperty(value = "True if this source produces magic damage, false otherwise", required = true) + public boolean magic; + + @ApiModelProperty(value = "True if the damage of this source is scaled by the difficulty, false otherwise", required = true) + public boolean scaledByDifficulty; + + @ApiModelProperty(value = "The damage type inflicted by this damage source", required = true) + public DamageType damageType; + + + public DamageSourceView(DamageSource value) { + super(value); + + this.affectsCreative = value.doesAffectCreative(); + this.absolute = value.isAbsolute(); + this.bypassingArmour = value.isBypassingArmor(); + this.explosive = value.isExplosive(); + this.magic = value.isMagic(); + this.scaledByDifficulty = value.isScaledByDifficulty(); + this.damageType = value.getType(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/event/EventView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/event/EventView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/event/EventView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/event/EventView.java index 38160e0e..41df57fa 100644 --- a/src/main/java/valandur/webapi/serialize/view/event/EventView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/event/EventView.java @@ -1,117 +1,117 @@ -package valandur.webapi.serialize.view.event; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.event.Event; -import org.spongepowered.api.event.advancement.AdvancementEvent; -import org.spongepowered.api.event.block.TargetBlockEvent; -import org.spongepowered.api.event.command.SendCommandEvent; -import org.spongepowered.api.event.entity.TargetEntityEvent; -import org.spongepowered.api.event.entity.living.humanoid.HandInteractEvent; -import org.spongepowered.api.event.entity.living.humanoid.player.KickPlayerEvent; -import org.spongepowered.api.event.entity.living.humanoid.player.TargetPlayerEvent; -import org.spongepowered.api.event.item.inventory.InteractInventoryEvent; -import org.spongepowered.api.event.message.MessageChannelEvent; -import org.spongepowered.api.event.user.BanUserEvent; -import org.spongepowered.api.event.user.TargetUserEvent; -import org.spongepowered.api.event.world.ExplosionEvent; -import org.spongepowered.api.event.world.GenerateChunkEvent; -import org.spongepowered.api.event.world.TargetWorldEvent; -import valandur.webapi.block.BlockOperationEvent; -import valandur.webapi.cache.command.CachedCommandResult; -import valandur.webapi.serialize.BaseView; - -import java.util.HashMap; -import java.util.Map; - -@ApiModel("Event") -public class EventView extends BaseView { - - @JsonProperty(value = "class") - @ApiModelProperty(value = "The class of event", required = true) - public String clazz; - - private Map data = new HashMap<>(); - @JsonAnyGetter - public Map getData() { - return data; - } - - - public EventView(Event value) { - super(value); - - this.clazz = value.getClass().getName(); - - if (value instanceof TargetEntityEvent) { - data.put("target", ((TargetEntityEvent)value).getTargetEntity()); - } else if (value instanceof TargetPlayerEvent) { - // TODO: Not sure if we really need this clause... - data.put("target", ((TargetPlayerEvent)value).getTargetEntity()); - } else if (value instanceof TargetUserEvent) { - data.put("target", ((TargetUserEvent)value).getTargetUser()); - } - - if (value instanceof MessageChannelEvent) { - MessageChannelEvent event = (MessageChannelEvent)value; - data.put("message", event.getMessage()); - data.put("receivers", event.getChannel().orElse(event.getOriginalChannel()).getMembers()); - } - - if (value instanceof SendCommandEvent) { - SendCommandEvent event = (SendCommandEvent)value; - data.put("command", event.getCommand()); - data.put("arguments", event.getArguments()); - data.put("result", new CachedCommandResult(event.getResult())); - } - - if (value instanceof KickPlayerEvent) { - data.put("message", ((KickPlayerEvent)value).getMessage()); - } - - if (value instanceof BanUserEvent) { - data.put("ban", ((BanUserEvent)value).getBan()); - } - - if (value instanceof AdvancementEvent) { - data.put("advancement", ((AdvancementEvent)value).getAdvancement()); - } - /*if (value instanceof GrantAchievementEvent) { - data.put("achievement", ((GrantAchievementEvent)value).getAchievement()); - }*/ - - if (value instanceof InteractInventoryEvent) { - data.put("inventory", ((InteractInventoryEvent)value).getTargetInventory()); - } - - if (value instanceof BlockOperationEvent) { - data.put("operation", ((BlockOperationEvent)value).getBlockOperation()); - } - - if (value instanceof GenerateChunkEvent) { - data.put("chunk", ((GenerateChunkEvent)value).getTargetChunk()); - } - - if (value instanceof ExplosionEvent) { - data.put("explosion", ((ExplosionEvent)value).getExplosion()); - } - - if (value instanceof TargetWorldEvent) { - data.put("world", ((TargetWorldEvent)value).getTargetWorld()); - } - - if (value instanceof TargetBlockEvent) { - data.put("block", ((TargetBlockEvent)value).getTargetBlock()); - } - - if (value instanceof HandInteractEvent) { - data.put("hand", ((HandInteractEvent)value).getHandType()); - } - - try { - data.put("cause", value.getCause()); - } catch (AbstractMethodError ignored) {} - } -} +package valandur.webapi.serialize.view.event; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.event.Event; +import org.spongepowered.api.event.advancement.AdvancementEvent; +import org.spongepowered.api.event.block.TargetBlockEvent; +import org.spongepowered.api.event.command.SendCommandEvent; +import org.spongepowered.api.event.entity.TargetEntityEvent; +import org.spongepowered.api.event.entity.living.humanoid.HandInteractEvent; +import org.spongepowered.api.event.entity.living.humanoid.player.KickPlayerEvent; +import org.spongepowered.api.event.entity.living.humanoid.player.TargetPlayerEvent; +import org.spongepowered.api.event.item.inventory.InteractInventoryEvent; +import org.spongepowered.api.event.message.MessageChannelEvent; +import org.spongepowered.api.event.user.BanUserEvent; +import org.spongepowered.api.event.user.TargetUserEvent; +import org.spongepowered.api.event.world.ExplosionEvent; +import org.spongepowered.api.event.world.GenerateChunkEvent; +import org.spongepowered.api.event.world.TargetWorldEvent; +import valandur.webapi.block.BlockOperationEvent; +import valandur.webapi.cache.command.CachedCommandResult; +import valandur.webapi.serialize.BaseView; + +import java.util.HashMap; +import java.util.Map; + +@ApiModel("Event") +public class EventView extends BaseView { + + @JsonProperty(value = "class") + @ApiModelProperty(value = "The class of event", required = true) + public String clazz; + + private Map data = new HashMap<>(); + @JsonAnyGetter + public Map getData() { + return data; + } + + + public EventView(Event value) { + super(value); + + this.clazz = value.getClass().getName(); + + if (value instanceof TargetEntityEvent) { + data.put("target", ((TargetEntityEvent)value).getTargetEntity()); + } else if (value instanceof TargetPlayerEvent) { + // TODO: Not sure if we really need this clause... + data.put("target", ((TargetPlayerEvent)value).getTargetEntity()); + } else if (value instanceof TargetUserEvent) { + data.put("target", ((TargetUserEvent)value).getTargetUser()); + } + + if (value instanceof MessageChannelEvent) { + MessageChannelEvent event = (MessageChannelEvent)value; + data.put("message", event.getMessage()); + data.put("receivers", event.getChannel().orElse(event.getOriginalChannel()).getMembers()); + } + + if (value instanceof SendCommandEvent) { + SendCommandEvent event = (SendCommandEvent)value; + data.put("command", event.getCommand()); + data.put("arguments", event.getArguments()); + data.put("result", new CachedCommandResult(event.getResult())); + } + + if (value instanceof KickPlayerEvent) { + data.put("message", ((KickPlayerEvent)value).getMessage()); + } + + if (value instanceof BanUserEvent) { + data.put("ban", ((BanUserEvent)value).getBan()); + } + + if (value instanceof AdvancementEvent) { + data.put("advancement", ((AdvancementEvent)value).getAdvancement()); + } + /*if (value instanceof GrantAchievementEvent) { + data.put("achievement", ((GrantAchievementEvent)value).getAchievement()); + }*/ + + if (value instanceof InteractInventoryEvent) { + data.put("inventory", ((InteractInventoryEvent)value).getTargetInventory()); + } + + if (value instanceof BlockOperationEvent) { + data.put("operation", ((BlockOperationEvent)value).getBlockOperation()); + } + + if (value instanceof GenerateChunkEvent) { + data.put("chunk", ((GenerateChunkEvent)value).getTargetChunk()); + } + + if (value instanceof ExplosionEvent) { + data.put("explosion", ((ExplosionEvent)value).getExplosion()); + } + + if (value instanceof TargetWorldEvent) { + data.put("world", ((TargetWorldEvent)value).getTargetWorld()); + } + + if (value instanceof TargetBlockEvent) { + data.put("block", ((TargetBlockEvent)value).getTargetBlock()); + } + + if (value instanceof HandInteractEvent) { + data.put("hand", ((HandInteractEvent)value).getHandType()); + } + + try { + data.put("cause", value.getCause()); + } catch (AbstractMethodError ignored) {} + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackSnapshotView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackSnapshotView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/fluid/FluidStackSnapshotView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackSnapshotView.java index aa47d25c..314e4e42 100644 --- a/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackSnapshotView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackSnapshotView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.fluid; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.extra.fluid.FluidStack; -import org.spongepowered.api.extra.fluid.FluidStackSnapshot; -import valandur.webapi.serialize.BaseView; - -public class FluidStackSnapshotView extends BaseView { - - @JsonValue - public FluidStack fluid; - - - public FluidStackSnapshotView(FluidStackSnapshot value) { - super(value); - - this.fluid = value.createStack(); - } -} +package valandur.webapi.serialize.view.fluid; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.extra.fluid.FluidStack; +import org.spongepowered.api.extra.fluid.FluidStackSnapshot; +import valandur.webapi.serialize.BaseView; + +public class FluidStackSnapshotView extends BaseView { + + @JsonValue + public FluidStack fluid; + + + public FluidStackSnapshotView(FluidStackSnapshot value) { + super(value); + + this.fluid = value.createStack(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/fluid/FluidStackView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackView.java index d427828f..b6f0b338 100644 --- a/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/fluid/FluidStackView.java @@ -1,71 +1,71 @@ -package valandur.webapi.serialize.view.fluid; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.Property; -import org.spongepowered.api.data.manipulator.DataManipulator; -import org.spongepowered.api.extra.fluid.FluidStack; -import org.spongepowered.api.extra.fluid.FluidType; -import valandur.webapi.WebAPI; -import valandur.webapi.serialize.BaseView; -import valandur.webapi.serialize.JsonDetails; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -@ApiModel("FluidStack") -public class FluidStackView extends BaseView { - - @ApiModelProperty(value = "The type of fluid contained within this stack", required = true) - public FluidType getType() { - return value.getFluid(); - } - - @ApiModelProperty(value = "The amount of fluid in this stack", required = true) - public int getVolume() { - return value.getVolume(); - } - - @JsonDetails - @JsonAnyGetter - @ApiModelProperty("Additional item data attached to this FluidStack") - public Map getData() { - HashMap data = new HashMap<>(); - - // Add properties - Map>, String> props = WebAPI.getSerializeService().getSupportedProperties(); - for (Property property : value.getApplicableProperties()) { - String key = props.get(property.getClass()); - if (key == null) { - continue; - } - data.put(key, property.getValue()); - } - - // Add data - Map>> supData = WebAPI.getSerializeService().getSupportedData(); - for (Map.Entry>> entry : supData.entrySet()) { - try { - if (!value.supports(entry.getValue())) - continue; - - Optional m = value.get(entry.getValue()); - - if (!m.isPresent()) - continue; - - data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); - } catch (IllegalArgumentException | IllegalStateException ignored) { - } - } - - return data; - } - - - public FluidStackView(FluidStack value) { - super(value); - } -} +package valandur.webapi.serialize.view.fluid; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.Property; +import org.spongepowered.api.data.manipulator.DataManipulator; +import org.spongepowered.api.extra.fluid.FluidStack; +import org.spongepowered.api.extra.fluid.FluidType; +import valandur.webapi.WebAPI; +import valandur.webapi.serialize.BaseView; +import valandur.webapi.serialize.JsonDetails; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +@ApiModel("FluidStack") +public class FluidStackView extends BaseView { + + @ApiModelProperty(value = "The type of fluid contained within this stack", required = true) + public FluidType getType() { + return value.getFluid(); + } + + @ApiModelProperty(value = "The amount of fluid in this stack", required = true) + public int getVolume() { + return value.getVolume(); + } + + @JsonDetails + @JsonAnyGetter + @ApiModelProperty("Additional item data attached to this FluidStack") + public Map getData() { + HashMap data = new HashMap<>(); + + // Add properties + Map>, String> props = WebAPI.getSerializeService().getSupportedProperties(); + for (Property property : value.getApplicableProperties()) { + String key = props.get(property.getClass()); + if (key == null) { + continue; + } + data.put(key, property.getValue()); + } + + // Add data + Map>> supData = WebAPI.getSerializeService().getSupportedData(); + for (Map.Entry>> entry : supData.entrySet()) { + try { + if (!value.supports(entry.getValue())) + continue; + + Optional m = value.get(entry.getValue()); + + if (!m.isPresent()) + continue; + + data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); + } catch (IllegalArgumentException | IllegalStateException ignored) { + } + } + + return data; + } + + + public FluidStackView(FluidStack value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/item/EnchantmentView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/EnchantmentView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/item/EnchantmentView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/EnchantmentView.java index 842267ef..078cbe0c 100644 --- a/src/main/java/valandur/webapi/serialize/view/item/EnchantmentView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/EnchantmentView.java @@ -1,30 +1,30 @@ -package valandur.webapi.serialize.view.item; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.item.enchantment.Enchantment; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Enchantment") -public class EnchantmentView extends BaseView { - - @ApiModelProperty("The unique id of the enchantment type") - public String getId() { - return value.getType().getId(); - } - - @ApiModelProperty("The name of the enchantment type") - public String getName() { - return value.getType().getTranslation().get(); - } - - @ApiModelProperty("The level of the enchantment") - public int getLevel() { - return value.getLevel(); - } - - - public EnchantmentView(Enchantment value) { - super(value); - } -} +package valandur.webapi.serialize.view.item; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.item.enchantment.Enchantment; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Enchantment") +public class EnchantmentView extends BaseView { + + @ApiModelProperty("The unique id of the enchantment type") + public String getId() { + return value.getType().getId(); + } + + @ApiModelProperty("The name of the enchantment type") + public String getName() { + return value.getType().getTranslation().get(); + } + + @ApiModelProperty("The level of the enchantment") + public int getLevel() { + return value.getLevel(); + } + + + public EnchantmentView(Enchantment value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/item/FireworkEffectView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/FireworkEffectView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/item/FireworkEffectView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/FireworkEffectView.java index fc6475d3..d09d9e80 100644 --- a/src/main/java/valandur/webapi/serialize/view/item/FireworkEffectView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/FireworkEffectView.java @@ -1,40 +1,40 @@ -package valandur.webapi.serialize.view.item; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.item.FireworkEffect; -import org.spongepowered.api.item.FireworkShape; -import org.spongepowered.api.util.Color; -import valandur.webapi.serialize.BaseView; - -import java.util.List; - -@ApiModel("FireworkEffect") -public class FireworkEffectView extends BaseView { - - @ApiModelProperty(value = "The shape of the firework", required = true) - public FireworkShape shape; - - @ApiModelProperty(value = "True if the firework flickers, false otherwise", required = true) - public boolean flickers; - - @ApiModelProperty(value = "The colors that make up this firework", required = true) - public List colors; - - @ApiModelProperty(value = "The fade colors that this firework has", required = true) - public List fadeColors; - - @ApiModelProperty(value = "True if this firework has a trail, false otherwise", required = true) - public boolean trail; - - - public FireworkEffectView(FireworkEffect value) { - super(value); - - this.shape = value.getShape(); - this.flickers = value.flickers(); - this.colors = value.getColors(); - this.fadeColors = value.getFadeColors(); - this.trail = value.hasTrail(); - } -} +package valandur.webapi.serialize.view.item; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.item.FireworkEffect; +import org.spongepowered.api.item.FireworkShape; +import org.spongepowered.api.util.Color; +import valandur.webapi.serialize.BaseView; + +import java.util.List; + +@ApiModel("FireworkEffect") +public class FireworkEffectView extends BaseView { + + @ApiModelProperty(value = "The shape of the firework", required = true) + public FireworkShape shape; + + @ApiModelProperty(value = "True if the firework flickers, false otherwise", required = true) + public boolean flickers; + + @ApiModelProperty(value = "The colors that make up this firework", required = true) + public List colors; + + @ApiModelProperty(value = "The fade colors that this firework has", required = true) + public List fadeColors; + + @ApiModelProperty(value = "True if this firework has a trail, false otherwise", required = true) + public boolean trail; + + + public FireworkEffectView(FireworkEffect value) { + super(value); + + this.shape = value.getShape(); + this.flickers = value.flickers(); + this.colors = value.getColors(); + this.fadeColors = value.getFadeColors(); + this.trail = value.hasTrail(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/item/ItemStackSnapshotView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/ItemStackSnapshotView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/item/ItemStackSnapshotView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/ItemStackSnapshotView.java index 8375b829..79ccd17c 100644 --- a/src/main/java/valandur/webapi/serialize/view/item/ItemStackSnapshotView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/ItemStackSnapshotView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.item; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.item.inventory.ItemStackSnapshot; -import valandur.webapi.serialize.BaseView; - -public class ItemStackSnapshotView extends BaseView { - - @JsonValue - public ItemStack stack; - - - public ItemStackSnapshotView(ItemStackSnapshot value) { - super(value); - - this.stack = value.createStack(); - } -} +package valandur.webapi.serialize.view.item; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.item.inventory.ItemStack; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import valandur.webapi.serialize.BaseView; + +public class ItemStackSnapshotView extends BaseView { + + @JsonValue + public ItemStack stack; + + + public ItemStackSnapshotView(ItemStackSnapshot value) { + super(value); + + this.stack = value.createStack(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/item/ItemStackView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/ItemStackView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/item/ItemStackView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/ItemStackView.java index a5ddb3c6..c7b14acc 100644 --- a/src/main/java/valandur/webapi/serialize/view/item/ItemStackView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/ItemStackView.java @@ -1,71 +1,71 @@ -package valandur.webapi.serialize.view.item; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.Property; -import org.spongepowered.api.data.manipulator.DataManipulator; -import org.spongepowered.api.item.ItemType; -import org.spongepowered.api.item.inventory.ItemStack; -import valandur.webapi.WebAPI; -import valandur.webapi.serialize.BaseView; -import valandur.webapi.serialize.JsonDetails; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -@ApiModel("ItemStack") -public class ItemStackView extends BaseView { - - @ApiModelProperty(value = "The type of this item", required = true) - public ItemType getType() { - return value.getType(); - } - - @ApiModelProperty(value = "The quantity of items in this stack", required = true) - public int getQuantity() { - return value.getQuantity(); - } - - @JsonDetails - @JsonAnyGetter - @ApiModelProperty("Additional item data attached to this ItemStack") - public Map getData() { - HashMap data = new HashMap<>(); - - // Add properties - Map>, String> props = WebAPI.getSerializeService().getSupportedProperties(); - for (Property property : value.getApplicableProperties()) { - String key = props.get(property.getClass()); - if (key == null) { - continue; - } - data.put(key, property.getValue()); - } - - // Add data - for (Map.Entry>> entry : - WebAPI.getSerializeService().getSupportedData().entrySet()) { - try { - if (!value.supports(entry.getValue())) - continue; - - Optional m = value.get(entry.getValue()); - - if (!m.isPresent()) - continue; - - data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); - } catch (IllegalArgumentException | IllegalStateException ignored) { - } - } - - return data; - } - - - public ItemStackView(ItemStack value) { - super(value); - } -} +package valandur.webapi.serialize.view.item; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.Property; +import org.spongepowered.api.data.manipulator.DataManipulator; +import org.spongepowered.api.item.ItemType; +import org.spongepowered.api.item.inventory.ItemStack; +import valandur.webapi.WebAPI; +import valandur.webapi.serialize.BaseView; +import valandur.webapi.serialize.JsonDetails; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +@ApiModel("ItemStack") +public class ItemStackView extends BaseView { + + @ApiModelProperty(value = "The type of this item", required = true) + public ItemType getType() { + return value.getType(); + } + + @ApiModelProperty(value = "The quantity of items in this stack", required = true) + public int getQuantity() { + return value.getQuantity(); + } + + @JsonDetails + @JsonAnyGetter + @ApiModelProperty("Additional item data attached to this ItemStack") + public Map getData() { + HashMap data = new HashMap<>(); + + // Add properties + Map>, String> props = WebAPI.getSerializeService().getSupportedProperties(); + for (Property property : value.getApplicableProperties()) { + String key = props.get(property.getClass()); + if (key == null) { + continue; + } + data.put(key, property.getValue()); + } + + // Add data + for (Map.Entry>> entry : + WebAPI.getSerializeService().getSupportedData().entrySet()) { + try { + if (!value.supports(entry.getValue())) + continue; + + Optional m = value.get(entry.getValue()); + + if (!m.isPresent()) + continue; + + data.put(entry.getKey(), ((DataManipulator) m.get()).copy()); + } catch (IllegalArgumentException | IllegalStateException ignored) { + } + } + + return data; + } + + + public ItemStackView(ItemStack value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/item/PotionEffectView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/PotionEffectView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/item/PotionEffectView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/PotionEffectView.java index e6ed6dfd..21d9a8c4 100644 --- a/src/main/java/valandur/webapi/serialize/view/item/PotionEffectView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/item/PotionEffectView.java @@ -1,29 +1,29 @@ -package valandur.webapi.serialize.view.item; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.effect.potion.PotionEffect; -import org.spongepowered.api.effect.potion.PotionEffectType; -import valandur.webapi.serialize.BaseView; - -@ApiModel("PotionEffect") -public class PotionEffectView extends BaseView { - - @ApiModelProperty(value = "The type of effect this potion represents", required = true) - public PotionEffectType type; - - @ApiModelProperty(value = "The aplifier of this potion (I, II, III, IV, V, ...)", required = true) - public int amplifier; - - @ApiModelProperty(value = "The duration this potion lasts for", required = true) - public int duration; - - - public PotionEffectView(PotionEffect value) { - super(value); - - this.type = value.getType(); - this.amplifier = value.getAmplifier(); - this.duration = value.getDuration(); - } -} +package valandur.webapi.serialize.view.item; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.effect.potion.PotionEffect; +import org.spongepowered.api.effect.potion.PotionEffectType; +import valandur.webapi.serialize.BaseView; + +@ApiModel("PotionEffect") +public class PotionEffectView extends BaseView { + + @ApiModelProperty(value = "The type of effect this potion represents", required = true) + public PotionEffectType type; + + @ApiModelProperty(value = "The aplifier of this potion (I, II, III, IV, V, ...)", required = true) + public int amplifier; + + @ApiModelProperty(value = "The duration this potion lasts for", required = true) + public int duration; + + + public PotionEffectView(PotionEffect value) { + super(value); + + this.type = value.getType(); + this.amplifier = value.getAmplifier(); + this.duration = value.getDuration(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/ColorView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/ColorView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/misc/ColorView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/ColorView.java index 8c3bd665..aa716915 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/ColorView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/ColorView.java @@ -1,28 +1,28 @@ -package valandur.webapi.serialize.view.misc; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.util.Color; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Color") -public class ColorView extends BaseView { - - @ApiModelProperty(value = "The red value of the color", required = true) - public int r; - - @ApiModelProperty(value = "The green value of the color", required = true) - public int g; - - @ApiModelProperty(value = "The blue value of the color", required = true) - public int b; - - - public ColorView(Color value) { - super(value); - - this.r = value.getRed(); - this.g = value.getGreen(); - this.b = value.getBlue(); - } -} +package valandur.webapi.serialize.view.misc; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.util.Color; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Color") +public class ColorView extends BaseView { + + @ApiModelProperty(value = "The red value of the color", required = true) + public int r; + + @ApiModelProperty(value = "The green value of the color", required = true) + public int g; + + @ApiModelProperty(value = "The blue value of the color", required = true) + public int b; + + + public ColorView(Color value) { + super(value); + + this.r = value.getRed(); + this.g = value.getGreen(); + this.b = value.getBlue(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/CommandSourceView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/CommandSourceView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/misc/CommandSourceView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/CommandSourceView.java index aa676623..828d4adc 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/CommandSourceView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/CommandSourceView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.misc; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.command.CommandSource; -import valandur.webapi.serialize.BaseView; - -@ApiModel("CommandSource") -public class CommandSourceView extends BaseView { - - @ApiModelProperty(value = "The unique id of this command source", required = true) - public String id; - - @ApiModelProperty(value = "The name of this command source", required = true) - public String name; - - - public CommandSourceView(CommandSource value) { - super(value); - - this.id = value.getIdentifier(); - this.name = value.getName(); - } -} +package valandur.webapi.serialize.view.misc; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.command.CommandSource; +import valandur.webapi.serialize.BaseView; + +@ApiModel("CommandSource") +public class CommandSourceView extends BaseView { + + @ApiModelProperty(value = "The unique id of this command source", required = true) + public String id; + + @ApiModelProperty(value = "The name of this command source", required = true) + public String name; + + + public CommandSourceView(CommandSource value) { + super(value); + + this.id = value.getIdentifier(); + this.name = value.getName(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/DyeColorView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/DyeColorView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/misc/DyeColorView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/DyeColorView.java index 9881f2f6..b9fdbbc8 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/DyeColorView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/DyeColorView.java @@ -1,29 +1,29 @@ -package valandur.webapi.serialize.view.misc; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.type.DyeColor; -import org.spongepowered.api.util.Color; -import valandur.webapi.serialize.BaseView; - -@ApiModel("DyeColor") -public class DyeColorView extends BaseView { - - @ApiModelProperty(value = "The unique id of this dye color", required = true) - public String id; - - @ApiModelProperty(value = "The name of this dye color", required = true) - public String name; - - @ApiModelProperty(value = "The color represented by this dye color", required = true) - public Color color; - - - public DyeColorView(DyeColor value) { - super(value); - - this.id = value.getId(); - this.name = value.getTranslation().get(); - this.color = value.getColor(); - } -} +package valandur.webapi.serialize.view.misc; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.type.DyeColor; +import org.spongepowered.api.util.Color; +import valandur.webapi.serialize.BaseView; + +@ApiModel("DyeColor") +public class DyeColorView extends BaseView { + + @ApiModelProperty(value = "The unique id of this dye color", required = true) + public String id; + + @ApiModelProperty(value = "The name of this dye color", required = true) + public String name; + + @ApiModelProperty(value = "The color represented by this dye color", required = true) + public Color color; + + + public DyeColorView(DyeColor value) { + super(value); + + this.id = value.getId(); + this.name = value.getTranslation().get(); + this.color = value.getColor(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/ExplosionView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/ExplosionView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/misc/ExplosionView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/ExplosionView.java index c42bdf6e..ed649fa9 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/ExplosionView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/ExplosionView.java @@ -1,36 +1,36 @@ -package valandur.webapi.serialize.view.misc; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.world.explosion.Explosion; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Explosion") -public class ExplosionView extends BaseView { - - @ApiModelProperty(value = "True if this explosion causes fires, false otherwise", required = true) - public boolean causeFire; - - @ApiModelProperty(value = "The radius of this explosion", required = true) - public float radius; - - @ApiModelProperty(value = "True if this explosion breaks blocks, false otherwise", required = true) - public boolean breakBlocks; - - @ApiModelProperty(value = "True if this explosion damages entities, false otherwise", required = true) - public boolean damageEntities; - - @ApiModelProperty(value = "True if a smoke animation is played for this explosion, false otherwise", required = true) - public boolean playSmoke; - - - public ExplosionView(Explosion value) { - super(value); - - this.causeFire = value.canCauseFire(); - this.radius = value.getRadius(); - this.breakBlocks = value.shouldBreakBlocks(); - this.damageEntities = value.shouldDamageEntities(); - this.playSmoke = value.shouldPlaySmoke(); - } -} +package valandur.webapi.serialize.view.misc; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.world.explosion.Explosion; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Explosion") +public class ExplosionView extends BaseView { + + @ApiModelProperty(value = "True if this explosion causes fires, false otherwise", required = true) + public boolean causeFire; + + @ApiModelProperty(value = "The radius of this explosion", required = true) + public float radius; + + @ApiModelProperty(value = "True if this explosion breaks blocks, false otherwise", required = true) + public boolean breakBlocks; + + @ApiModelProperty(value = "True if this explosion damages entities, false otherwise", required = true) + public boolean damageEntities; + + @ApiModelProperty(value = "True if a smoke animation is played for this explosion, false otherwise", required = true) + public boolean playSmoke; + + + public ExplosionView(Explosion value) { + super(value); + + this.causeFire = value.canCauseFire(); + this.radius = value.getRadius(); + this.breakBlocks = value.shouldBreakBlocks(); + this.damageEntities = value.shouldDamageEntities(); + this.playSmoke = value.shouldPlaySmoke(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/InstantView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/InstantView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/misc/InstantView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/InstantView.java index 388fc9c9..72f7cbe0 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/InstantView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/InstantView.java @@ -1,19 +1,19 @@ -package valandur.webapi.serialize.view.misc; - -import com.fasterxml.jackson.annotation.JsonValue; -import valandur.webapi.serialize.BaseView; - -import java.time.Instant; - -public class InstantView extends BaseView { - - @JsonValue - public Long instant; - - - public InstantView(Instant value) { - super(value); - - this.instant = value.getEpochSecond(); - } -} +package valandur.webapi.serialize.view.misc; + +import com.fasterxml.jackson.annotation.JsonValue; +import valandur.webapi.serialize.BaseView; + +import java.time.Instant; + +public class InstantView extends BaseView { + + @JsonValue + public Long instant; + + + public InstantView(Instant value) { + super(value); + + this.instant = value.getEpochSecond(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/LocalDateView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/LocalDateView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/misc/LocalDateView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/LocalDateView.java index 54122cbd..5aa25f56 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/LocalDateView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/LocalDateView.java @@ -1,31 +1,31 @@ -package valandur.webapi.serialize.view.misc; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.serialize.BaseView; - -import java.time.LocalDate; - -@ApiModel("LocalDate") -public class LocalDateView extends BaseView { - - @ApiModelProperty("The day of the month (1-31)") - public int getDay() { - return value.getDayOfMonth(); - } - - @ApiModelProperty("The month in the year (1-12)") - public int getMonth() { - return value.getMonthValue(); - } - - @ApiModelProperty("The year") - public int getYear() { - return value.getYear(); - } - - - public LocalDateView(LocalDate value) { - super(value); - } -} +package valandur.webapi.serialize.view.misc; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.serialize.BaseView; + +import java.time.LocalDate; + +@ApiModel("LocalDate") +public class LocalDateView extends BaseView { + + @ApiModelProperty("The day of the month (1-31)") + public int getDay() { + return value.getDayOfMonth(); + } + + @ApiModelProperty("The month in the year (1-12)") + public int getMonth() { + return value.getMonthValue(); + } + + @ApiModelProperty("The year") + public int getYear() { + return value.getYear(); + } + + + public LocalDateView(LocalDate value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/RandomObjectTableView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/RandomObjectTableView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/misc/RandomObjectTableView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/RandomObjectTableView.java index 4c57846b..de6c1585 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/RandomObjectTableView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/RandomObjectTableView.java @@ -1,40 +1,40 @@ -package valandur.webapi.serialize.view.misc; - -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import org.spongepowered.api.util.weighted.NestedTableEntry; -import org.spongepowered.api.util.weighted.RandomObjectTable; -import org.spongepowered.api.util.weighted.TableEntry; -import org.spongepowered.api.util.weighted.WeightedObject; -import valandur.webapi.serialize.BaseView; - -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -@ApiModel("RandomObjectTable") -public class RandomObjectTableView extends BaseView { - - @JsonValue - public Map entries; - - - public RandomObjectTableView(RandomObjectTable value) { - super(value); - - entries = new HashMap<>(); - for (TableEntry entry : value.getEntries()) { - if (entry instanceof NestedTableEntry) { - try { - // Get the property with reflection because it's not exposed for some reason - Field field = NestedTableEntry.class.getDeclaredField("table"); - field.setAccessible(true); - Object tbl = field.get(entry); - entries.put(entry.getWeight(), tbl); - } catch (IllegalAccessException | NoSuchFieldException ignored) { } - } else if (entry instanceof WeightedObject) { - entries.put(entry.getWeight(), ((WeightedObject)entry).get()); - } - } - } -} +package valandur.webapi.serialize.view.misc; + +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import org.spongepowered.api.util.weighted.NestedTableEntry; +import org.spongepowered.api.util.weighted.RandomObjectTable; +import org.spongepowered.api.util.weighted.TableEntry; +import org.spongepowered.api.util.weighted.WeightedObject; +import valandur.webapi.serialize.BaseView; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +@ApiModel("RandomObjectTable") +public class RandomObjectTableView extends BaseView { + + @JsonValue + public Map entries; + + + public RandomObjectTableView(RandomObjectTable value) { + super(value); + + entries = new HashMap<>(); + for (TableEntry entry : value.getEntries()) { + if (entry instanceof NestedTableEntry) { + try { + // Get the property with reflection because it's not exposed for some reason + Field field = NestedTableEntry.class.getDeclaredField("table"); + field.setAccessible(true); + Object tbl = field.get(entry); + entries.put(entry.getWeight(), tbl); + } catch (IllegalAccessException | NoSuchFieldException ignored) { } + } else if (entry instanceof WeightedObject) { + entries.put(entry.getWeight(), ((WeightedObject)entry).get()); + } + } + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/StatisticView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/StatisticView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/misc/StatisticView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/StatisticView.java index 916824e6..d4c348fe 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/StatisticView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/StatisticView.java @@ -1,18 +1,18 @@ -package valandur.webapi.serialize.view.misc; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.statistic.Statistic; -import valandur.webapi.serialize.BaseView; - -public class StatisticView extends BaseView { - - @JsonValue - public String stat; - - - public StatisticView(Statistic value) { - super(value); - - this.stat = value.getId(); - } -} +package valandur.webapi.serialize.view.misc; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.statistic.Statistic; +import valandur.webapi.serialize.BaseView; + +public class StatisticView extends BaseView { + + @JsonValue + public String stat; + + + public StatisticView(Statistic value) { + super(value); + + this.stat = value.getId(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/TextView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/TextView.java similarity index 95% rename from src/main/java/valandur/webapi/serialize/view/misc/TextView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/TextView.java index 36f76c75..4dd4529a 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/TextView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/TextView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.misc; - -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import org.spongepowered.api.text.Text; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Text") -public class TextView extends BaseView { - - @JsonValue - public String text; - - - public TextView(Text value) { - super(value); - - this.text = value.toPlain(); - } -} +package valandur.webapi.serialize.view.misc; + +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import org.spongepowered.api.text.Text; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Text") +public class TextView extends BaseView { + + @JsonValue + public String text; + + + public TextView(Text value) { + super(value); + + this.text = value.toPlain(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/Vector3dView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/Vector3dView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/misc/Vector3dView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/Vector3dView.java index abcc175b..009acb97 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/Vector3dView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/Vector3dView.java @@ -1,28 +1,28 @@ -package valandur.webapi.serialize.view.misc; - -import com.flowpowered.math.vector.Vector3d; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Vector3d") -public class Vector3dView extends BaseView { - - @ApiModelProperty(value = "The x-coordinate", required = true) - public double x; - - @ApiModelProperty(value = "The y-coordinate", required = true) - public double y; - - @ApiModelProperty(value = "The z-coordinate", required = true) - public double z; - - - public Vector3dView(Vector3d value) { - super(value); - - this.x = value.getX(); - this.y = value.getY(); - this.z = value.getZ(); - } -} +package valandur.webapi.serialize.view.misc; + +import com.flowpowered.math.vector.Vector3d; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Vector3d") +public class Vector3dView extends BaseView { + + @ApiModelProperty(value = "The x-coordinate", required = true) + public double x; + + @ApiModelProperty(value = "The y-coordinate", required = true) + public double y; + + @ApiModelProperty(value = "The z-coordinate", required = true) + public double z; + + + public Vector3dView(Vector3d value) { + super(value); + + this.x = value.getX(); + this.y = value.getY(); + this.z = value.getZ(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/misc/Vector3iView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/Vector3iView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/misc/Vector3iView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/Vector3iView.java index ff4ea08c..f5b427e3 100644 --- a/src/main/java/valandur/webapi/serialize/view/misc/Vector3iView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/misc/Vector3iView.java @@ -1,28 +1,28 @@ -package valandur.webapi.serialize.view.misc; - -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import valandur.webapi.serialize.BaseView; - -@ApiModel("Vector3i") -public class Vector3iView extends BaseView { - - @ApiModelProperty(value = "The x-coordinate", required = true) - public int x; - - @ApiModelProperty(value = "The y-coordinate", required = true) - public int y; - - @ApiModelProperty(value = "The z-coordinate", required = true) - public int z; - - - public Vector3iView(Vector3i value) { - super(value); - - this.x = value.getX(); - this.y = value.getY(); - this.z = value.getZ(); - } -} +package valandur.webapi.serialize.view.misc; + +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import valandur.webapi.serialize.BaseView; + +@ApiModel("Vector3i") +public class Vector3iView extends BaseView { + + @ApiModelProperty(value = "The x-coordinate", required = true) + public int x; + + @ApiModelProperty(value = "The y-coordinate", required = true) + public int y; + + @ApiModelProperty(value = "The z-coordinate", required = true) + public int z; + + + public Vector3iView(Vector3i value) { + super(value); + + this.x = value.getX(); + this.y = value.getY(); + this.z = value.getZ(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/permission/SubjectCollectionView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/permission/SubjectCollectionView.java similarity index 97% rename from src/main/java/valandur/webapi/serialize/view/permission/SubjectCollectionView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/permission/SubjectCollectionView.java index f8346cad..b344e4b9 100644 --- a/src/main/java/valandur/webapi/serialize/view/permission/SubjectCollectionView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/permission/SubjectCollectionView.java @@ -1,25 +1,25 @@ -package valandur.webapi.serialize.view.permission; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.service.permission.SubjectCollection; -import valandur.webapi.serialize.BaseView; - -@ApiModel("SubjectCollection") -public class SubjectCollectionView extends BaseView { - - @ApiModelProperty(value = "The unique id of this subject collection", required = true) - public String getId() { - return value.getIdentifier(); - } - - @ApiModelProperty(value = "The amount of subjects currently loaded from this collection", required = true) - public Integer getLoadedSubjectCount() { - return value.getLoadedSubjects().size(); - } - - - public SubjectCollectionView(SubjectCollection value) { - super(value); - } -} +package valandur.webapi.serialize.view.permission; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.service.permission.SubjectCollection; +import valandur.webapi.serialize.BaseView; + +@ApiModel("SubjectCollection") +public class SubjectCollectionView extends BaseView { + + @ApiModelProperty(value = "The unique id of this subject collection", required = true) + public String getId() { + return value.getIdentifier(); + } + + @ApiModelProperty(value = "The amount of subjects currently loaded from this collection", required = true) + public Integer getLoadedSubjectCount() { + return value.getLoadedSubjects().size(); + } + + + public SubjectCollectionView(SubjectCollection value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/permission/SubjectView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/permission/SubjectView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/permission/SubjectView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/permission/SubjectView.java index 150eecdd..82f54da2 100644 --- a/src/main/java/valandur/webapi/serialize/view/permission/SubjectView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/permission/SubjectView.java @@ -1,38 +1,38 @@ -package valandur.webapi.serialize.view.permission; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.service.permission.Subject; -import valandur.webapi.serialize.BaseView; -import valandur.webapi.serialize.JsonDetails; - -import java.util.HashMap; -import java.util.Map; - -@ApiModel("Subject") -public class SubjectView extends BaseView { - - @ApiModelProperty(value = "The unique id of this subject", required = true) - public String getId() { - return value.getIdentifier(); - } - - @ApiModelProperty("The friendly id of this subject (often a 'name'") - public String getFriendlyId() { - return value.getFriendlyIdentifier().orElse(null); - } - - @JsonDetails - @ApiModelProperty(value = "The permissions that are assigned to this subject") - public Map getPermissions() { - Map res = new HashMap<>(); - for (Map map : value.getSubjectData().getAllPermissions().values()) { - res.putAll(map); - } - return res; - } - - public SubjectView(Subject value) { - super(value); - } -} +package valandur.webapi.serialize.view.permission; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.service.permission.Subject; +import valandur.webapi.serialize.BaseView; +import valandur.webapi.serialize.JsonDetails; + +import java.util.HashMap; +import java.util.Map; + +@ApiModel("Subject") +public class SubjectView extends BaseView { + + @ApiModelProperty(value = "The unique id of this subject", required = true) + public String getId() { + return value.getIdentifier(); + } + + @ApiModelProperty("The friendly id of this subject (often a 'name'") + public String getFriendlyId() { + return value.getFriendlyIdentifier().orElse(null); + } + + @JsonDetails + @ApiModelProperty(value = "The permissions that are assigned to this subject") + public Map getPermissions() { + Map res = new HashMap<>(); + for (Map map : value.getSubjectData().getAllPermissions().values()) { + res.putAll(map); + } + return res; + } + + public SubjectView(Subject value) { + super(value); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/player/AchievementView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/AchievementView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/player/AchievementView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/AchievementView.java index 093002bf..85ccf4bd 100644 --- a/src/main/java/valandur/webapi/serialize/view/player/AchievementView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/AchievementView.java @@ -1,22 +1,22 @@ -/*package valandur.webapi.serialize.view.player; - -import org.spongepowered.api.statistic.achievement.Achievement; -import valandur.webapi.api.serialize.BaseView; - -public class AchievementView extends BaseView { - - public String id; - public String name; - public String description; - - - public AchievementView(Achievement value) { - super(value); - - this.id = value.getId(); - this.name = value.getName(); - this.description = value.getDescription().get(); - } -} - +/*package valandur.webapi.serialize.view.player; + +import org.spongepowered.api.statistic.achievement.Achievement; +import valandur.webapi.api.serialize.BaseView; + +public class AchievementView extends BaseView { + + public String id; + public String name; + public String description; + + + public AchievementView(Achievement value) { + super(value); + + this.id = value.getId(); + this.name = value.getName(); + this.description = value.getDescription().get(); + } +} + */ \ No newline at end of file diff --git a/src/main/java/valandur/webapi/serialize/view/player/BanView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/BanView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/player/BanView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/BanView.java index a4669abb..31433d44 100644 --- a/src/main/java/valandur/webapi/serialize/view/player/BanView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/BanView.java @@ -1,40 +1,40 @@ -package valandur.webapi.serialize.view.player; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.util.ban.Ban; -import valandur.webapi.serialize.BaseView; - -import java.time.Instant; - -@ApiModel("Ban") -public class BanView extends BaseView { - - @ApiModelProperty(value = "The moment when this ban was created", required = true) - public Instant createdOn; - - @ApiModelProperty("The date when this ban expires") - public Instant expiresOn; - - @ApiModelProperty("The reason why the player was banned") - public Text reason; - - @ApiModelProperty("The source that issued the ban") - public Text banSource; - - @ApiModelProperty("The command source associated with the ban") - public CommandSource commandSource; - - - public BanView(Ban value) { - super(value); - - this.createdOn = value.getCreationDate(); - this.expiresOn = value.getExpirationDate().orElse(null); - this.reason = value.getReason().orElse(null); - this.banSource = value.getBanSource().orElse(null); - this.commandSource = value.getBanCommandSource().orElse(null); - } -} +package valandur.webapi.serialize.view.player; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.util.ban.Ban; +import valandur.webapi.serialize.BaseView; + +import java.time.Instant; + +@ApiModel("Ban") +public class BanView extends BaseView { + + @ApiModelProperty(value = "The moment when this ban was created", required = true) + public Instant createdOn; + + @ApiModelProperty("The date when this ban expires") + public Instant expiresOn; + + @ApiModelProperty("The reason why the player was banned") + public Text reason; + + @ApiModelProperty("The source that issued the ban") + public Text banSource; + + @ApiModelProperty("The command source associated with the ban") + public CommandSource commandSource; + + + public BanView(Ban value) { + super(value); + + this.createdOn = value.getCreationDate(); + this.expiresOn = value.getExpirationDate().orElse(null); + this.reason = value.getReason().orElse(null); + this.banSource = value.getBanSource().orElse(null); + this.commandSource = value.getBanCommandSource().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/player/GameModeView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/GameModeView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/player/GameModeView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/GameModeView.java index d1d09de9..22526952 100644 --- a/src/main/java/valandur/webapi/serialize/view/player/GameModeView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/GameModeView.java @@ -1,24 +1,24 @@ -package valandur.webapi.serialize.view.player; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.entity.living.player.gamemode.GameMode; -import valandur.webapi.serialize.BaseView; - -@ApiModel("GameMode") -public class GameModeView extends BaseView { - - @ApiModelProperty(value = "The unique id of the game mode", required = true) - public String id; - - @ApiModelProperty(value = "The name of the game mode", required = true) - public String name; - - - public GameModeView(GameMode value) { - super(value); - - this.id = value.getId(); - this.name = value.getTranslation().get(); - } -} +package valandur.webapi.serialize.view.player; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.entity.living.player.gamemode.GameMode; +import valandur.webapi.serialize.BaseView; + +@ApiModel("GameMode") +public class GameModeView extends BaseView { + + @ApiModelProperty(value = "The unique id of the game mode", required = true) + public String id; + + @ApiModelProperty(value = "The name of the game mode", required = true) + public String name; + + + public GameModeView(GameMode value) { + super(value); + + this.id = value.getId(); + this.name = value.getTranslation().get(); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/player/GameProfileView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/GameProfileView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/player/GameProfileView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/GameProfileView.java index 93204b4b..ad447887 100644 --- a/src/main/java/valandur/webapi/serialize/view/player/GameProfileView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/GameProfileView.java @@ -1,26 +1,26 @@ -package valandur.webapi.serialize.view.player; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.profile.GameProfile; -import valandur.webapi.serialize.BaseView; - -import java.util.UUID; - -@ApiModel("GameProfile") -public class GameProfileView extends BaseView { - - @ApiModelProperty(value = "The UUID of the game profile", required = true) - public UUID uuid; - - @ApiModelProperty(value = "The name of the player this game profile belongs to", required = true) - public String name; - - - public GameProfileView(GameProfile value) { - super(value); - - this.uuid = value.getUniqueId(); - this.name = value.getName().orElse(null); - } -} +package valandur.webapi.serialize.view.player; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.profile.GameProfile; +import valandur.webapi.serialize.BaseView; + +import java.util.UUID; + +@ApiModel("GameProfile") +public class GameProfileView extends BaseView { + + @ApiModelProperty(value = "The UUID of the game profile", required = true) + public UUID uuid; + + @ApiModelProperty(value = "The name of the player this game profile belongs to", required = true) + public String name; + + + public GameProfileView(GameProfile value) { + super(value); + + this.uuid = value.getUniqueId(); + this.name = value.getName().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/player/RespawnLocationView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/RespawnLocationView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/player/RespawnLocationView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/RespawnLocationView.java index d38eb827..e7f676bf 100644 --- a/src/main/java/valandur/webapi/serialize/view/player/RespawnLocationView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/player/RespawnLocationView.java @@ -1,20 +1,20 @@ -package valandur.webapi.serialize.view.player; - -import com.fasterxml.jackson.annotation.JsonValue; -import org.spongepowered.api.util.RespawnLocation; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; -import valandur.webapi.serialize.BaseView; - -public class RespawnLocationView extends BaseView { - - @JsonValue - public Location loc; - - - public RespawnLocationView(RespawnLocation value) { - super(value); - - loc = value.asLocation().orElse(null); - } -} +package valandur.webapi.serialize.view.player; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.spongepowered.api.util.RespawnLocation; +import org.spongepowered.api.world.Location; +import org.spongepowered.api.world.World; +import valandur.webapi.serialize.BaseView; + +public class RespawnLocationView extends BaseView { + + @JsonValue + public Location loc; + + + public RespawnLocationView(RespawnLocation value) { + super(value); + + loc = value.asLocation().orElse(null); + } +} diff --git a/src/main/java/valandur/webapi/serialize/view/tileentity/PatternLayerView.java b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/tileentity/PatternLayerView.java similarity index 96% rename from src/main/java/valandur/webapi/serialize/view/tileentity/PatternLayerView.java rename to webapi-sponge/src/main/java/valandur/webapi/serialize/view/tileentity/PatternLayerView.java index 27dfcfe1..02945585 100644 --- a/src/main/java/valandur/webapi/serialize/view/tileentity/PatternLayerView.java +++ b/webapi-sponge/src/main/java/valandur/webapi/serialize/view/tileentity/PatternLayerView.java @@ -1,26 +1,26 @@ -package valandur.webapi.serialize.view.tileentity; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.spongepowered.api.data.meta.PatternLayer; -import org.spongepowered.api.data.type.BannerPatternShape; -import org.spongepowered.api.data.type.DyeColor; -import valandur.webapi.serialize.BaseView; - -@ApiModel("PatternLayer") -public class PatternLayerView extends BaseView { - - @ApiModelProperty(value = "The base shape of this pattern", required = true) - public BannerPatternShape shape; - - @ApiModelProperty(value = "The color of the pattern", required = true) - public DyeColor color; - - - public PatternLayerView(PatternLayer value) { - super(value); - - this.shape = value.getShape(); - this.color = value.getColor(); - } -} +package valandur.webapi.serialize.view.tileentity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.spongepowered.api.data.meta.PatternLayer; +import org.spongepowered.api.data.type.BannerPatternShape; +import org.spongepowered.api.data.type.DyeColor; +import valandur.webapi.serialize.BaseView; + +@ApiModel("PatternLayer") +public class PatternLayerView extends BaseView { + + @ApiModelProperty(value = "The base shape of this pattern", required = true) + public BannerPatternShape shape; + + @ApiModelProperty(value = "The color of the pattern", required = true) + public DyeColor color; + + + public PatternLayerView(PatternLayer value) { + super(value); + + this.shape = value.getShape(); + this.color = value.getColor(); + } +} diff --git a/src/main/java/valandur/webapi/server/ServerProperty.java b/webapi-sponge/src/main/java/valandur/webapi/server/ServerProperty.java similarity index 96% rename from src/main/java/valandur/webapi/server/ServerProperty.java rename to webapi-sponge/src/main/java/valandur/webapi/server/ServerProperty.java index ed69091e..278b234c 100644 --- a/src/main/java/valandur/webapi/server/ServerProperty.java +++ b/webapi-sponge/src/main/java/valandur/webapi/server/ServerProperty.java @@ -1,26 +1,26 @@ -package valandur.webapi.server; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel("ServerProperty") -public class ServerProperty { - - private String key; - @ApiModelProperty(value = "The key of the server property", required = true) - public String getKey() { - return key; - } - - private String value; - @ApiModelProperty(value = "The value of the server property", required = true) - public String getValue() { - return value; - } - - - public ServerProperty(String key, String value) { - this.key = key; - this.value = value; - } -} +package valandur.webapi.server; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel("ServerProperty") +public class ServerProperty { + + private String key; + @ApiModelProperty(value = "The key of the server property", required = true) + public String getKey() { + return key; + } + + private String value; + @ApiModelProperty(value = "The value of the server property", required = true) + public String getValue() { + return value; + } + + + public ServerProperty(String key, String value) { + this.key = key; + this.value = value; + } +} diff --git a/src/main/java/valandur/webapi/server/ServerService.java b/webapi-sponge/src/main/java/valandur/webapi/server/ServerService.java similarity index 97% rename from src/main/java/valandur/webapi/server/ServerService.java rename to webapi-sponge/src/main/java/valandur/webapi/server/ServerService.java index 7c2e3f61..549aadf2 100644 --- a/src/main/java/valandur/webapi/server/ServerService.java +++ b/webapi-sponge/src/main/java/valandur/webapi/server/ServerService.java @@ -1,191 +1,191 @@ -package valandur.webapi.server; - -import com.sun.management.OperatingSystemMXBean; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.scheduler.Task; -import valandur.webapi.WebAPI; -import valandur.webapi.config.BaseConfig; -import valandur.webapi.config.ServerConfig; - -import java.io.File; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; - -/** - * This service provides information about the minecraft server. - */ -public class ServerService { - - private final static String configFileName = "server.conf"; - - // Record every 5 seconds. (17280 entries = 24 hours, 4320 entries = 6 hours) - private static int STATS_INTERVAL = 5; - private static int MAX_STATS_ENTRIES = 4320; - - private OperatingSystemMXBean systemMXBean; - private Map properties = new ConcurrentHashMap<>(); - private Map newProperties = new ConcurrentHashMap<>(); - - private Queue> averageTps = new ConcurrentLinkedQueue<>(); - private Queue> onlinePlayers = new ConcurrentLinkedQueue<>(); - private Queue> cpuLoad = new ConcurrentLinkedQueue<>(); - private Queue> memoryLoad = new ConcurrentLinkedQueue<>(); - private Queue> diskUsage = new ConcurrentLinkedQueue<>(); - - private Task statTask; - - - public void init() { - properties.clear(); - newProperties.clear(); - - Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); - ServerConfig config = BaseConfig.load(configPath, new ServerConfig()); - - STATS_INTERVAL = config.statsInterval; - MAX_STATS_ENTRIES = config.maxStats; - - try { - List lines = Files.readAllLines(Paths.get("./server.properties")); - for (String line : lines) { - String[] splits = line.split("="); - String key = splits[0].trim(); - if (key.startsWith("#")) { - continue; - } - - properties.put(key, new ServerProperty(key, splits.length > 1 ? splits[1].trim() : "")); - } - } catch (IOException e) { - e.printStackTrace(); - WebAPI.sentryCapture(e); - } - - newProperties.putAll(properties); - - if (statTask != null) { - statTask.cancel(); - } - - systemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); - - statTask = Task.builder().execute(this::recordStats) - .async() - .delay(STATS_INTERVAL, TimeUnit.SECONDS) - .interval(STATS_INTERVAL, TimeUnit.SECONDS) - .name("Web-API - Server stats") - .submit(WebAPI.getInstance()); - } - - private void recordStats() { - long total = 0; - long free = 0; - File[] roots = File.listRoots(); - for (File root : roots) { - total += root.getTotalSpace(); - free += root.getFreeSpace(); - } - - long maxMem = Runtime.getRuntime().maxMemory(); - long usedMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); - - // Stuff accessing sponge needs to be run on the server main thread - WebAPI.runOnMain(() -> { - averageTps.add(new ServerStat<>(Sponge.getServer().getTicksPerSecond())); - onlinePlayers.add(new ServerStat<>(Sponge.getServer().getOnlinePlayers().size())); - }); - cpuLoad.add(new ServerStat<>(systemMXBean.getProcessCpuLoad())); - memoryLoad.add(new ServerStat<>(usedMem / (double)maxMem)); - diskUsage.add(new ServerStat<>((total - free) / (double)total)); - - while (averageTps.size() > MAX_STATS_ENTRIES) - averageTps.poll(); - while (onlinePlayers.size() > MAX_STATS_ENTRIES) - onlinePlayers.poll(); - while (cpuLoad.size() > MAX_STATS_ENTRIES) - cpuLoad.poll(); - while (memoryLoad.size() > MAX_STATS_ENTRIES) - memoryLoad.poll(); - while (diskUsage.size() > MAX_STATS_ENTRIES) - diskUsage.poll(); - } - - /** - * Gets the number of data entries currently recorded. - * @return The number of data entries that are available. - */ - public int getNumEntries() { - return Math.min(averageTps.size(), Math.min(onlinePlayers.size(), Math.min(cpuLoad.size(), - Math.min(memoryLoad.size(), diskUsage.size())))); - } - - /** - * Gets a history of the average TPS of the minecraft server. - * @return A list containing measurements of the TPS. - */ - public List> getAverageTps() { - return new ArrayList<>(averageTps); - } - - /** - * Gets a history of the amount of players that were online on the minecraft server. - * @return A list containing measurements of the amount of players online. - */ - public List> getOnlinePlayers() { - return new ArrayList<>(onlinePlayers); - } - - /** - * Gets a history of the average load of the cpu. - * @return A list containing the measurements of the average load of the cpu. - */ - public List> getCpuLoad() { - return new ArrayList<>(cpuLoad); - } - - /** - * Gets a history of the average memory load. - * @return A list containing the measurements of the average memory load. - */ - public List> getMemoryLoad() { - return new ArrayList<>(memoryLoad); - } - - /** - * Gets a history of the average disk usage. - * @return A list containing measurements of the average disk usage. - */ - public List> getDiskUsage() { - return new ArrayList<>(diskUsage); - } - - public Collection getProperties() { - return newProperties.values(); - } - public void setProperty(String key, String value) { - newProperties.put(key, new ServerProperty(key, value)); - } - public void saveProperties() throws IOException { - Path path = Paths.get("./server.properties"); - Path backupPath = Paths.get("./server.properties.bck"); - if (!Files.exists(backupPath)) { - Files.copy(path, backupPath); - } - - StringBuilder text = new StringBuilder("#Minecraft server properties\n"); - text.append("#Modified by Web-API\n"); - text.append("#").append((new Date()).toString()).append("\n"); - for (ServerProperty prop : newProperties.values()) { - text.append(prop.getKey()).append("=").append(prop.getValue()).append("\n"); - } - Files.write(path, text.toString().getBytes(Charset.forName("utf-8"))); - } -} +package valandur.webapi.server; + +import com.sun.management.OperatingSystemMXBean; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.scheduler.Task; +import valandur.webapi.WebAPI; +import valandur.webapi.config.BaseConfig; +import valandur.webapi.config.ServerConfig; + +import java.io.File; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; + +/** + * This service provides information about the minecraft server. + */ +public class ServerService { + + private final static String configFileName = "server.conf"; + + // Record every 5 seconds. (17280 entries = 24 hours, 4320 entries = 6 hours) + private static int STATS_INTERVAL = 5; + private static int MAX_STATS_ENTRIES = 4320; + + private OperatingSystemMXBean systemMXBean; + private Map properties = new ConcurrentHashMap<>(); + private Map newProperties = new ConcurrentHashMap<>(); + + private Queue> averageTps = new ConcurrentLinkedQueue<>(); + private Queue> onlinePlayers = new ConcurrentLinkedQueue<>(); + private Queue> cpuLoad = new ConcurrentLinkedQueue<>(); + private Queue> memoryLoad = new ConcurrentLinkedQueue<>(); + private Queue> diskUsage = new ConcurrentLinkedQueue<>(); + + private Task statTask; + + + public void init() { + properties.clear(); + newProperties.clear(); + + Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); + ServerConfig config = BaseConfig.load(configPath, new ServerConfig()); + + STATS_INTERVAL = config.statsInterval; + MAX_STATS_ENTRIES = config.maxStats; + + try { + List lines = Files.readAllLines(Paths.get("./server.properties")); + for (String line : lines) { + String[] splits = line.split("="); + String key = splits[0].trim(); + if (key.startsWith("#")) { + continue; + } + + properties.put(key, new ServerProperty(key, splits.length > 1 ? splits[1].trim() : "")); + } + } catch (IOException e) { + e.printStackTrace(); + WebAPI.sentryCapture(e); + } + + newProperties.putAll(properties); + + if (statTask != null) { + statTask.cancel(); + } + + systemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); + + statTask = Task.builder().execute(this::recordStats) + .async() + .delay(STATS_INTERVAL, TimeUnit.SECONDS) + .interval(STATS_INTERVAL, TimeUnit.SECONDS) + .name("Web-API - Server stats") + .submit(WebAPI.getInstance()); + } + + private void recordStats() { + long total = 0; + long free = 0; + File[] roots = File.listRoots(); + for (File root : roots) { + total += root.getTotalSpace(); + free += root.getFreeSpace(); + } + + long maxMem = Runtime.getRuntime().maxMemory(); + long usedMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); + + // Stuff accessing sponge needs to be run on the server main thread + WebAPI.runOnMain(() -> { + averageTps.add(new ServerStat<>(Sponge.getServer().getTicksPerSecond())); + onlinePlayers.add(new ServerStat<>(Sponge.getServer().getOnlinePlayers().size())); + }); + cpuLoad.add(new ServerStat<>(systemMXBean.getProcessCpuLoad())); + memoryLoad.add(new ServerStat<>(usedMem / (double)maxMem)); + diskUsage.add(new ServerStat<>((total - free) / (double)total)); + + while (averageTps.size() > MAX_STATS_ENTRIES) + averageTps.poll(); + while (onlinePlayers.size() > MAX_STATS_ENTRIES) + onlinePlayers.poll(); + while (cpuLoad.size() > MAX_STATS_ENTRIES) + cpuLoad.poll(); + while (memoryLoad.size() > MAX_STATS_ENTRIES) + memoryLoad.poll(); + while (diskUsage.size() > MAX_STATS_ENTRIES) + diskUsage.poll(); + } + + /** + * Gets the number of data entries currently recorded. + * @return The number of data entries that are available. + */ + public int getNumEntries() { + return Math.min(averageTps.size(), Math.min(onlinePlayers.size(), Math.min(cpuLoad.size(), + Math.min(memoryLoad.size(), diskUsage.size())))); + } + + /** + * Gets a history of the average TPS of the minecraft server. + * @return A list containing measurements of the TPS. + */ + public List> getAverageTps() { + return new ArrayList<>(averageTps); + } + + /** + * Gets a history of the amount of players that were online on the minecraft server. + * @return A list containing measurements of the amount of players online. + */ + public List> getOnlinePlayers() { + return new ArrayList<>(onlinePlayers); + } + + /** + * Gets a history of the average load of the cpu. + * @return A list containing the measurements of the average load of the cpu. + */ + public List> getCpuLoad() { + return new ArrayList<>(cpuLoad); + } + + /** + * Gets a history of the average memory load. + * @return A list containing the measurements of the average memory load. + */ + public List> getMemoryLoad() { + return new ArrayList<>(memoryLoad); + } + + /** + * Gets a history of the average disk usage. + * @return A list containing measurements of the average disk usage. + */ + public List> getDiskUsage() { + return new ArrayList<>(diskUsage); + } + + public Collection getProperties() { + return newProperties.values(); + } + public void setProperty(String key, String value) { + newProperties.put(key, new ServerProperty(key, value)); + } + public void saveProperties() throws IOException { + Path path = Paths.get("./server.properties"); + Path backupPath = Paths.get("./server.properties.bck"); + if (!Files.exists(backupPath)) { + Files.copy(path, backupPath); + } + + StringBuilder text = new StringBuilder("#Minecraft server properties\n"); + text.append("#Modified by Web-API\n"); + text.append("#").append((new Date()).toString()).append("\n"); + for (ServerProperty prop : newProperties.values()) { + text.append(prop.getKey()).append("=").append(prop.getValue()).append("\n"); + } + Files.write(path, text.toString().getBytes(Charset.forName("utf-8"))); + } +} diff --git a/src/main/java/valandur/webapi/server/ServerStat.java b/webapi-sponge/src/main/java/valandur/webapi/server/ServerStat.java similarity index 96% rename from src/main/java/valandur/webapi/server/ServerStat.java rename to webapi-sponge/src/main/java/valandur/webapi/server/ServerStat.java index f8c11a37..d322687a 100644 --- a/src/main/java/valandur/webapi/server/ServerStat.java +++ b/webapi-sponge/src/main/java/valandur/webapi/server/ServerStat.java @@ -1,28 +1,28 @@ -package valandur.webapi.server; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import java.time.Instant; - -@ApiModel(value = "ServerStat") -public class ServerStat { - - private Instant timestamp; - @ApiModelProperty(value = "The epoch timestamp (in seconds) when the statistic was recorded", dataType = "long", required = true) - public Instant getTimestamp() { - return timestamp; - } - - private V value; - @ApiModelProperty(value = "The value that was recorded", dataType = "number", required = true) - public V getValue() { - return value; - } - - - public ServerStat(V value) { - this.timestamp = Instant.now(); - this.value = value; - } -} +package valandur.webapi.server; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.time.Instant; + +@ApiModel(value = "ServerStat") +public class ServerStat { + + private Instant timestamp; + @ApiModelProperty(value = "The epoch timestamp (in seconds) when the statistic was recorded", dataType = "long", required = true) + public Instant getTimestamp() { + return timestamp; + } + + private V value; + @ApiModelProperty(value = "The value that was recorded", dataType = "number", required = true) + public V getValue() { + return value; + } + + + public ServerStat(V value) { + this.timestamp = Instant.now(); + this.value = value; + } +} diff --git a/src/main/java/valandur/webapi/servlet/BlockServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/BlockServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/BlockServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/BlockServlet.java diff --git a/src/main/java/valandur/webapi/servlet/ChunkServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/ChunkServlet.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/ChunkServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/ChunkServlet.java index ff237734..9c1b9866 100644 --- a/src/main/java/valandur/webapi/servlet/ChunkServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/ChunkServlet.java @@ -1,101 +1,101 @@ -package valandur.webapi.servlet; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import org.spongepowered.api.world.Chunk; -import org.spongepowered.api.world.World; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.world.CachedChunk; -import valandur.webapi.cache.world.CachedWorld; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.ExplicitDetails; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -@Path("chunk") -@Api(tags = { "Chunk" }, value = "Get and force load certain chunks of a world") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class ChunkServlet extends BaseServlet { - - @GET - @ExplicitDetails - @Path("/{world}") - @Permission("list") - @ApiOperation( - value = "List chunks", - notes = "Gets a list of all the loaded chunks for the specified world.") - public List listChunks( - @PathParam("world") @ApiParam("The uuid of the for which to get all chunks") CachedWorld world) { - return WebAPI.runOnMain(() -> { - Optional optWorld = world.getLive(); - if (!optWorld.isPresent()) - throw new InternalServerErrorException("Could not get live world"); - - World live = optWorld.get(); - List chunks = new ArrayList<>(); - - Iterable iterable = live.getLoadedChunks(); - iterable.forEach(c -> chunks.add(new CachedChunk(c))); - - return chunks; - }); - } - - @GET - @Path("/{world}/{x}/{z}") - @Permission("one") - @ApiOperation( - value = "Get a chunk", - notes = "Get detailed information about a chunk") - public CachedChunk getChunkAt( - @PathParam("world") @ApiParam("The uuid of the world in which to get the chunk") CachedWorld world, - @PathParam("x") @ApiParam("The x-coordinate of the chunk (in chunk coordinates)") int x, - @PathParam("z") @ApiParam("The z-coordinate of the chunk (in chunk coordinates)") int z) { - return WebAPI.runOnMain(() -> { - Optional optLive = world.getLive(); - if (!optLive.isPresent()) - throw new InternalServerErrorException("Could not get live world"); - - World live = optLive.get(); - Optional chunk = live.loadChunk(x, 0, z, false); - return chunk.map(CachedChunk::new).orElse(null); - }); - } - - @POST - @Path("/{world}/{x}/{z}") - @Permission("create") - @ApiOperation( - value = "Load & Generate a chunk", - response = CachedChunk.class, - notes = "Forces a chunk to be loaded into memory, and created if it does not exist.") - public Response createChunkAt( - @PathParam("world") @ApiParam("The uuid of the world in which to create the chunk") CachedWorld world, - @PathParam("x") @ApiParam("The x-coordinate of the chunk (in chunk coordinates)") int x, - @PathParam("z") @ApiParam("The z-coordinate of the chunk (in chunk coordinates)") int z) - throws URISyntaxException { - CachedChunk chunk = WebAPI.runOnMain(() -> { - Optional optLive = world.getLive(); - if (!optLive.isPresent()) - throw new InternalServerErrorException("Could not get live world"); - - World live = optLive.get(); - Optional optChunk = live.loadChunk(x, 0, z, true); - if (!optChunk.isPresent()) - throw new InternalServerErrorException("Could not load live chunk"); - return new CachedChunk(optChunk.get()); - }); - - return Response.created(new URI(null, null, chunk.getLink(), null)).entity(chunk).build(); - } -} +package valandur.webapi.servlet; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.spongepowered.api.world.Chunk; +import org.spongepowered.api.world.World; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.world.CachedChunk; +import valandur.webapi.cache.world.CachedWorld; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.ExplicitDetails; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Path("chunk") +@Api(tags = { "Chunk" }, value = "Get and force load certain chunks of a world") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class ChunkServlet extends BaseServlet { + + @GET + @ExplicitDetails + @Path("/{world}") + @Permission("list") + @ApiOperation( + value = "List chunks", + notes = "Gets a list of all the loaded chunks for the specified world.") + public List listChunks( + @PathParam("world") @ApiParam("The uuid of the for which to get all chunks") CachedWorld world) { + return WebAPI.runOnMain(() -> { + Optional optWorld = world.getLive(); + if (!optWorld.isPresent()) + throw new InternalServerErrorException("Could not get live world"); + + World live = optWorld.get(); + List chunks = new ArrayList<>(); + + Iterable iterable = live.getLoadedChunks(); + iterable.forEach(c -> chunks.add(new CachedChunk(c))); + + return chunks; + }); + } + + @GET + @Path("/{world}/{x}/{z}") + @Permission("one") + @ApiOperation( + value = "Get a chunk", + notes = "Get detailed information about a chunk") + public CachedChunk getChunkAt( + @PathParam("world") @ApiParam("The uuid of the world in which to get the chunk") CachedWorld world, + @PathParam("x") @ApiParam("The x-coordinate of the chunk (in chunk coordinates)") int x, + @PathParam("z") @ApiParam("The z-coordinate of the chunk (in chunk coordinates)") int z) { + return WebAPI.runOnMain(() -> { + Optional optLive = world.getLive(); + if (!optLive.isPresent()) + throw new InternalServerErrorException("Could not get live world"); + + World live = optLive.get(); + Optional chunk = live.loadChunk(x, 0, z, false); + return chunk.map(CachedChunk::new).orElse(null); + }); + } + + @POST + @Path("/{world}/{x}/{z}") + @Permission("create") + @ApiOperation( + value = "Load & Generate a chunk", + response = CachedChunk.class, + notes = "Forces a chunk to be loaded into memory, and created if it does not exist.") + public Response createChunkAt( + @PathParam("world") @ApiParam("The uuid of the world in which to create the chunk") CachedWorld world, + @PathParam("x") @ApiParam("The x-coordinate of the chunk (in chunk coordinates)") int x, + @PathParam("z") @ApiParam("The z-coordinate of the chunk (in chunk coordinates)") int z) + throws URISyntaxException { + CachedChunk chunk = WebAPI.runOnMain(() -> { + Optional optLive = world.getLive(); + if (!optLive.isPresent()) + throw new InternalServerErrorException("Could not get live world"); + + World live = optLive.get(); + Optional optChunk = live.loadChunk(x, 0, z, true); + if (!optChunk.isPresent()) + throw new InternalServerErrorException("Could not load live chunk"); + return new CachedChunk(optChunk.get()); + }); + + return Response.created(new URI(null, null, chunk.getLink(), null)).entity(chunk).build(); + } +} diff --git a/src/main/java/valandur/webapi/servlet/CmdServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/CmdServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/CmdServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/CmdServlet.java diff --git a/src/main/java/valandur/webapi/servlet/EconomyServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/EconomyServlet.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/EconomyServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/EconomyServlet.java index 499adf95..25ef730f 100644 --- a/src/main/java/valandur/webapi/servlet/EconomyServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/EconomyServlet.java @@ -1,60 +1,60 @@ -package valandur.webapi.servlet; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.Account; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import java.util.Collection; -import java.util.Optional; - -@Path("economy") -@Api(tags = { "Economy" }, value = "Manage the economy on your server") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class EconomyServlet extends BaseServlet { - - @GET - @Path("/currency") - @Permission({ "currency", "list" }) - @ApiOperation( - value = "List currencies", - notes = "Lists all the currencies that the current economy supports.") - public Collection getCurrencies() { - EconomyService srv = getEconomyService(); - return srv.getCurrencies(); - } - - @GET - @Path("/account/{id}") - @Permission({ "account", "one" }) - @ApiOperation( - value = "List currencies", - notes = "Lists all the currencies that the current economy supports.") - public Account getAccount(@PathParam("id") String id) { - EconomyService srv = getEconomyService(); - if (!srv.hasAccount(id)) - throw new NotFoundException("Could not find account with id " + id); - - Optional optAcc = srv.getOrCreateAccount(id); - if (!optAcc.isPresent()) - throw new InternalServerErrorException("Could not get account " + id); - - return optAcc.get(); - } - - - - private EconomyService getEconomyService() { - Optional optSrv = Sponge.getServiceManager().provide(EconomyService.class); - if (!optSrv.isPresent()) - throw new NotFoundException("Economy service was not found"); - return optSrv.get(); - } -} +package valandur.webapi.servlet; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.EconomyService; +import org.spongepowered.api.service.economy.account.Account; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.Collection; +import java.util.Optional; + +@Path("economy") +@Api(tags = { "Economy" }, value = "Manage the economy on your server") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class EconomyServlet extends BaseServlet { + + @GET + @Path("/currency") + @Permission({ "currency", "list" }) + @ApiOperation( + value = "List currencies", + notes = "Lists all the currencies that the current economy supports.") + public Collection getCurrencies() { + EconomyService srv = getEconomyService(); + return srv.getCurrencies(); + } + + @GET + @Path("/account/{id}") + @Permission({ "account", "one" }) + @ApiOperation( + value = "List currencies", + notes = "Lists all the currencies that the current economy supports.") + public Account getAccount(@PathParam("id") String id) { + EconomyService srv = getEconomyService(); + if (!srv.hasAccount(id)) + throw new NotFoundException("Could not find account with id " + id); + + Optional optAcc = srv.getOrCreateAccount(id); + if (!optAcc.isPresent()) + throw new InternalServerErrorException("Could not get account " + id); + + return optAcc.get(); + } + + + + private EconomyService getEconomyService() { + Optional optSrv = Sponge.getServiceManager().provide(EconomyService.class); + if (!optSrv.isPresent()) + throw new NotFoundException("Economy service was not found"); + return optSrv.get(); + } +} diff --git a/src/main/java/valandur/webapi/servlet/EntityServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/EntityServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/EntityServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/EntityServlet.java diff --git a/src/main/java/valandur/webapi/servlet/HistoryServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/HistoryServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/HistoryServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/HistoryServlet.java diff --git a/src/main/java/valandur/webapi/servlet/InfoServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/InfoServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/InfoServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/InfoServlet.java diff --git a/src/main/java/valandur/webapi/servlet/InteractiveMessageServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/InteractiveMessageServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/InteractiveMessageServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/InteractiveMessageServlet.java diff --git a/src/main/java/valandur/webapi/servlet/MapServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/MapServlet.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/MapServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/MapServlet.java index be9b7d24..19435668 100644 --- a/src/main/java/valandur/webapi/servlet/MapServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/MapServlet.java @@ -1,121 +1,121 @@ -package valandur.webapi.servlet; - -import com.flowpowered.math.vector.Vector3i; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import valandur.webapi.WebAPI; -import valandur.webapi.cache.world.CachedWorld; -import valandur.webapi.config.BaseConfig; -import valandur.webapi.config.MapConfig; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.imageio.ImageIO; -import javax.inject.Singleton; -import javax.ws.rs.*; -import javax.ws.rs.core.CacheControl; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.StreamingOutput; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -@Singleton -@Path("map") -@Api(tags = { "Map" }, value = "Get maps of the biomes for each world on the server") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class MapServlet extends BaseServlet { - - private static final String configFileName = "map.conf"; - - private static int TILE_SIZE = 512; - private static int HALF_TILE_SIZE = TILE_SIZE / 2; - private Map biomeColorMap = new ConcurrentHashMap<>(); - - - public MapServlet() { - biomeColorMap.clear(); - - java.nio.file.Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); - MapConfig config = BaseConfig.load(configPath, new MapConfig()); - - config.save(); // Save in case we don't have the default values yet - biomeColorMap.putAll(config.biomeColors); - } - - @GET - @Path("/{world}/{x}/{z}") - @Permission("map") - @Produces("image/png") - @ApiOperation( - value = "Get a map tile", - notes = "Returns an image representing the biomes of the blocks within the specified tile") - public Response getMap( - @PathParam("world") @ApiParam("The world to get the map tile from") CachedWorld world, - @PathParam("x") @ApiParam("The x-coordinate of the tile (is multiplied by the TILE_SIZE)") int x, - @PathParam("z") @ApiParam("The z-coordinate of the tile (is multiplied by the TILE_SIZE)") int z) { - int bX = TILE_SIZE * x; - int bZ = TILE_SIZE * z; - Vector3i min = new Vector3i(bX - HALF_TILE_SIZE, 0, bZ - HALF_TILE_SIZE); - Vector3i max = new Vector3i(bX + HALF_TILE_SIZE, 0, bZ + HALF_TILE_SIZE); - - String fileName = "tile-x" + x + "z" + z + ".png"; - java.nio.file.Path filePath = Paths.get("webapi/cache/" + world.getUUID() + "/" + fileName); - if (!filePath.getParent().toFile().exists()) - filePath.getParent().toFile().mkdirs(); - - CacheControl cc = new CacheControl(); - cc.setMaxAge(31536000); - - if (Files.exists(filePath)) { - return Response.ok((StreamingOutput) output -> { - BufferedImage img = ImageIO.read(filePath.toFile()); - ImageIO.write(img, "PNG", output); - }).cacheControl(cc).build(); - } - - String[][] biomes = blockService.getBiomes(world, min, max); - BufferedImage img = new BufferedImage(TILE_SIZE, TILE_SIZE, BufferedImage.TYPE_INT_ARGB); - Graphics2D g2 = img.createGraphics(); - - for (int i = 0; i < biomes.length; i++) { - for (int j = 0; j < biomes[i].length; j++) { - String biome = biomes[i][j]; - String hexColor = biomeColorMap.get(biome); - - if (hexColor == null) - hexColor = biomeColorMap.get(biome.replace("mutated_", "")); - - if (hexColor == null) { - WebAPI.getLogger().info("No color for biome: " + biome + ". You can set one in the map.conf file"); - - hexColor = "FFFFFF"; - biomeColorMap.put(biome, hexColor); - } - - g2.setColor(Color.decode("#" + hexColor)); - g2.fillRect(i * 4, img.getHeight() - j * 4, 4, 4); - } - } - - g2.dispose(); - - try { - ImageIO.write(img, "PNG", new File(filePath.toString())); - } catch (IOException e) { - throw new InternalServerErrorException("Could not save tile image"); - } - - return Response.ok((StreamingOutput) output -> { - ImageIO.write(img, "PNG", output); - }).cacheControl(cc).build(); - } -} +package valandur.webapi.servlet; + +import com.flowpowered.math.vector.Vector3i; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import valandur.webapi.WebAPI; +import valandur.webapi.cache.world.CachedWorld; +import valandur.webapi.config.BaseConfig; +import valandur.webapi.config.MapConfig; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.imageio.ImageIO; +import javax.inject.Singleton; +import javax.ws.rs.*; +import javax.ws.rs.core.CacheControl; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Singleton +@Path("map") +@Api(tags = { "Map" }, value = "Get maps of the biomes for each world on the server") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class MapServlet extends BaseServlet { + + private static final String configFileName = "map.conf"; + + private static int TILE_SIZE = 512; + private static int HALF_TILE_SIZE = TILE_SIZE / 2; + private Map biomeColorMap = new ConcurrentHashMap<>(); + + + public MapServlet() { + biomeColorMap.clear(); + + java.nio.file.Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); + MapConfig config = BaseConfig.load(configPath, new MapConfig()); + + config.save(); // Save in case we don't have the default values yet + biomeColorMap.putAll(config.biomeColors); + } + + @GET + @Path("/{world}/{x}/{z}") + @Permission("map") + @Produces("image/png") + @ApiOperation( + value = "Get a map tile", + notes = "Returns an image representing the biomes of the blocks within the specified tile") + public Response getMap( + @PathParam("world") @ApiParam("The world to get the map tile from") CachedWorld world, + @PathParam("x") @ApiParam("The x-coordinate of the tile (is multiplied by the TILE_SIZE)") int x, + @PathParam("z") @ApiParam("The z-coordinate of the tile (is multiplied by the TILE_SIZE)") int z) { + int bX = TILE_SIZE * x; + int bZ = TILE_SIZE * z; + Vector3i min = new Vector3i(bX - HALF_TILE_SIZE, 0, bZ - HALF_TILE_SIZE); + Vector3i max = new Vector3i(bX + HALF_TILE_SIZE, 0, bZ + HALF_TILE_SIZE); + + String fileName = "tile-x" + x + "z" + z + ".png"; + java.nio.file.Path filePath = Paths.get("webapi/cache/" + world.getUUID() + "/" + fileName); + if (!filePath.getParent().toFile().exists()) + filePath.getParent().toFile().mkdirs(); + + CacheControl cc = new CacheControl(); + cc.setMaxAge(31536000); + + if (Files.exists(filePath)) { + return Response.ok((StreamingOutput) output -> { + BufferedImage img = ImageIO.read(filePath.toFile()); + ImageIO.write(img, "PNG", output); + }).cacheControl(cc).build(); + } + + String[][] biomes = blockService.getBiomes(world, min, max); + BufferedImage img = new BufferedImage(TILE_SIZE, TILE_SIZE, BufferedImage.TYPE_INT_ARGB); + Graphics2D g2 = img.createGraphics(); + + for (int i = 0; i < biomes.length; i++) { + for (int j = 0; j < biomes[i].length; j++) { + String biome = biomes[i][j]; + String hexColor = biomeColorMap.get(biome); + + if (hexColor == null) + hexColor = biomeColorMap.get(biome.replace("mutated_", "")); + + if (hexColor == null) { + WebAPI.getLogger().info("No color for biome: " + biome + ". You can set one in the map.conf file"); + + hexColor = "FFFFFF"; + biomeColorMap.put(biome, hexColor); + } + + g2.setColor(Color.decode("#" + hexColor)); + g2.fillRect(i * 4, img.getHeight() - j * 4, 4, 4); + } + } + + g2.dispose(); + + try { + ImageIO.write(img, "PNG", new File(filePath.toString())); + } catch (IOException e) { + throw new InternalServerErrorException("Could not save tile image"); + } + + return Response.ok((StreamingOutput) output -> { + ImageIO.write(img, "PNG", output); + }).cacheControl(cc).build(); + } +} diff --git a/src/main/java/valandur/webapi/servlet/PermissionServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/PermissionServlet.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/PermissionServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/PermissionServlet.java index b075db19..7e08f4fc 100644 --- a/src/main/java/valandur/webapi/servlet/PermissionServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/PermissionServlet.java @@ -1,130 +1,130 @@ -package valandur.webapi.servlet; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.service.permission.PermissionService; -import org.spongepowered.api.service.permission.Subject; -import org.spongepowered.api.service.permission.SubjectCollection; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.ExplicitDetails; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ExecutionException; - -@Path("permission") -@Api(tags = { "Permission" }, value = "Manage permissions on the server") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class PermissionServlet extends BaseServlet { - - @GET - @Path("/collection") - @Permission({ "collection", "list" }) - @ExplicitDetails - @ApiOperation( - value = "List collections", - notes = "Gets a list of all the subject collections, for example groups, users, etc.") - public Set listCollections() { - PermissionService srv = getPermissionService(); - - try { - Set colls = new HashSet<>(); - for (String id : srv.getAllIdentifiers().get()) { - colls.add(srv.loadCollection(id).get()); - } - return colls; - } catch (InterruptedException e) { - throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); - } catch (ExecutionException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } - - @GET - @Path("/collection/{id}") - @Permission({ "collection", "one" }) - @ApiOperation( - value = "Get collection", - notes = "Gets a specific subject collection") - public SubjectCollection getCollection(@PathParam("id") String id) throws NotFoundException { - PermissionService srv = getPermissionService(); - - try { - if (!srv.hasCollection(id).get()) - throw new NotFoundException("Collection with id " + id + " could not be found"); - - return srv.loadCollection(id).get(); - } catch (InterruptedException e) { - throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); - } catch (ExecutionException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } - - @GET - @Path("/collection/{id}/subject") - @Permission({ "collection", "subject", "list" }) - @ExplicitDetails - @ApiOperation( - value = "List subjects", - notes = "List all subjects belonging to a certain collection") - public Set listSubjects(@PathParam("id") String id) throws NotFoundException { - PermissionService srv = getPermissionService(); - - try { - if (!srv.hasCollection(id).get()) - throw new NotFoundException("Collection with id " + id + " could not be found"); - - Set subjects = new HashSet<>(); - SubjectCollection coll = srv.loadCollection(id).get(); - for (String subId : coll.getAllIdentifiers().get()) { - subjects.add(coll.loadSubject(subId).get()); - } - return subjects; - } catch (InterruptedException e) { - throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); - } catch (ExecutionException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } - - @GET - @Path("/collection/{id}/subject/{subId}") - @Permission({ "collection", "subject", "one" }) - @ApiOperation( - value = "Get subject", - notes = "Gets one specific subject belonging to a certain collection") - public Subject getSubject(@PathParam("id") String id, @PathParam("subId") String subId) throws NotFoundException { - PermissionService srv = getPermissionService(); - - try { - if (!srv.hasCollection(id).get()) - throw new NotFoundException("Collection with id " + id + " could not be found"); - - SubjectCollection coll = srv.loadCollection(id).get(); - if (!coll.hasSubject(subId).get()) - throw new NotFoundException("Subject with id " + id + " could not be found"); - - return coll.loadSubject(subId).get(); - } catch (InterruptedException e) { - throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); - } catch (ExecutionException e) { - throw new InternalServerErrorException(e.getMessage()); - } - } - - - private PermissionService getPermissionService() { - Optional optSrv = Sponge.getServiceManager().provide(PermissionService.class); - if (!optSrv.isPresent()) - throw new NotFoundException("Permission service was not found"); - return optSrv.get(); - } -} +package valandur.webapi.servlet; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.service.permission.PermissionService; +import org.spongepowered.api.service.permission.Subject; +import org.spongepowered.api.service.permission.SubjectCollection; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.ExplicitDetails; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; + +@Path("permission") +@Api(tags = { "Permission" }, value = "Manage permissions on the server") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class PermissionServlet extends BaseServlet { + + @GET + @Path("/collection") + @Permission({ "collection", "list" }) + @ExplicitDetails + @ApiOperation( + value = "List collections", + notes = "Gets a list of all the subject collections, for example groups, users, etc.") + public Set listCollections() { + PermissionService srv = getPermissionService(); + + try { + Set colls = new HashSet<>(); + for (String id : srv.getAllIdentifiers().get()) { + colls.add(srv.loadCollection(id).get()); + } + return colls; + } catch (InterruptedException e) { + throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); + } catch (ExecutionException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } + + @GET + @Path("/collection/{id}") + @Permission({ "collection", "one" }) + @ApiOperation( + value = "Get collection", + notes = "Gets a specific subject collection") + public SubjectCollection getCollection(@PathParam("id") String id) throws NotFoundException { + PermissionService srv = getPermissionService(); + + try { + if (!srv.hasCollection(id).get()) + throw new NotFoundException("Collection with id " + id + " could not be found"); + + return srv.loadCollection(id).get(); + } catch (InterruptedException e) { + throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); + } catch (ExecutionException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } + + @GET + @Path("/collection/{id}/subject") + @Permission({ "collection", "subject", "list" }) + @ExplicitDetails + @ApiOperation( + value = "List subjects", + notes = "List all subjects belonging to a certain collection") + public Set listSubjects(@PathParam("id") String id) throws NotFoundException { + PermissionService srv = getPermissionService(); + + try { + if (!srv.hasCollection(id).get()) + throw new NotFoundException("Collection with id " + id + " could not be found"); + + Set subjects = new HashSet<>(); + SubjectCollection coll = srv.loadCollection(id).get(); + for (String subId : coll.getAllIdentifiers().get()) { + subjects.add(coll.loadSubject(subId).get()); + } + return subjects; + } catch (InterruptedException e) { + throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); + } catch (ExecutionException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } + + @GET + @Path("/collection/{id}/subject/{subId}") + @Permission({ "collection", "subject", "one" }) + @ApiOperation( + value = "Get subject", + notes = "Gets one specific subject belonging to a certain collection") + public Subject getSubject(@PathParam("id") String id, @PathParam("subId") String subId) throws NotFoundException { + PermissionService srv = getPermissionService(); + + try { + if (!srv.hasCollection(id).get()) + throw new NotFoundException("Collection with id " + id + " could not be found"); + + SubjectCollection coll = srv.loadCollection(id).get(); + if (!coll.hasSubject(subId).get()) + throw new NotFoundException("Subject with id " + id + " could not be found"); + + return coll.loadSubject(subId).get(); + } catch (InterruptedException e) { + throw new ClientErrorException(e.getMessage(), Response.Status.REQUEST_TIMEOUT); + } catch (ExecutionException e) { + throw new InternalServerErrorException(e.getMessage()); + } + } + + + private PermissionService getPermissionService() { + Optional optSrv = Sponge.getServiceManager().provide(PermissionService.class); + if (!optSrv.isPresent()) + throw new NotFoundException("Permission service was not found"); + return optSrv.get(); + } +} diff --git a/src/main/java/valandur/webapi/servlet/PlayerServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/PlayerServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/PlayerServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/PlayerServlet.java diff --git a/src/main/java/valandur/webapi/servlet/PluginServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/PluginServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/PluginServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/PluginServlet.java diff --git a/src/main/java/valandur/webapi/servlet/RecipeServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/RecipeServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/RecipeServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/RecipeServlet.java diff --git a/src/main/java/valandur/webapi/servlet/RegistryServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/RegistryServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/RegistryServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/RegistryServlet.java diff --git a/src/main/java/valandur/webapi/servlet/ServerServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/ServerServlet.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/ServerServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/ServerServlet.java index f6abee11..6a31f564 100644 --- a/src/main/java/valandur/webapi/servlet/ServerServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/ServerServlet.java @@ -1,73 +1,73 @@ -package valandur.webapi.servlet; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import valandur.webapi.WebAPI; -import valandur.webapi.security.SecurityContext; -import valandur.webapi.server.ServerProperty; -import valandur.webapi.server.ServerService; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.servlet.base.Permission; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import java.io.IOException; -import java.util.Collection; -import java.util.Map; - -@Path("server") -@Api(tags = { "Server" }, value = "Prodives information about the server, such as server propertiers") -@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -public class ServerServlet extends BaseServlet { - - @GET - @Path("/properties") - @Permission({ "properties", "list" }) - @ApiOperation( - value = "List server properties", - notes = "Get the main server properties (server.properties file).") - public Collection listProperties() { - ServerService srv = WebAPI.getServerService(); - return srv.getProperties(); - } - - @PUT - @Path("/properties") - @Permission({ "properties", "modify" }) - @Permission(value = { "properties", "modify", "[property]" }, autoCheck = false) - @ApiOperation( - value = "Modify server properties", - notes = "Modify settings in the server.properties file. **Note that these settings don't take effect " + - "until you restart the server.") - public Collection modifyProperties( - final Map properties, - @Context HttpServletRequest request) - throws BadRequestException { - - if (properties == null) { - throw new BadRequestException("Request body is required"); - } - - SecurityContext context = (SecurityContext)request.getAttribute("security"); - - ServerService srv = WebAPI.getServerService(); - for (Map.Entry entry : properties.entrySet()) { - if (!context.hasPerms(entry.getKey())) { - throw new ForbiddenException("You do not have permission to change the " + entry.getKey() + " setting"); - } - srv.setProperty(entry.getKey(), entry.getValue()); - } - - try { - srv.saveProperties(); - } catch (IOException e) { - WebAPI.sentryCapture(e); - throw new InternalServerErrorException(e.getMessage()); - } - - return srv.getProperties(); - } -} +package valandur.webapi.servlet; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import valandur.webapi.WebAPI; +import valandur.webapi.security.SecurityContext; +import valandur.webapi.server.ServerProperty; +import valandur.webapi.server.ServerService; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.servlet.base.Permission; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.util.Collection; +import java.util.Map; + +@Path("server") +@Api(tags = { "Server" }, value = "Prodives information about the server, such as server propertiers") +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +public class ServerServlet extends BaseServlet { + + @GET + @Path("/properties") + @Permission({ "properties", "list" }) + @ApiOperation( + value = "List server properties", + notes = "Get the main server properties (server.properties file).") + public Collection listProperties() { + ServerService srv = WebAPI.getServerService(); + return srv.getProperties(); + } + + @PUT + @Path("/properties") + @Permission({ "properties", "modify" }) + @Permission(value = { "properties", "modify", "[property]" }, autoCheck = false) + @ApiOperation( + value = "Modify server properties", + notes = "Modify settings in the server.properties file. **Note that these settings don't take effect " + + "until you restart the server.") + public Collection modifyProperties( + final Map properties, + @Context HttpServletRequest request) + throws BadRequestException { + + if (properties == null) { + throw new BadRequestException("Request body is required"); + } + + SecurityContext context = (SecurityContext)request.getAttribute("security"); + + ServerService srv = WebAPI.getServerService(); + for (Map.Entry entry : properties.entrySet()) { + if (!context.hasPerms(entry.getKey())) { + throw new ForbiddenException("You do not have permission to change the " + entry.getKey() + " setting"); + } + srv.setProperty(entry.getKey(), entry.getValue()); + } + + try { + srv.saveProperties(); + } catch (IOException e) { + WebAPI.sentryCapture(e); + throw new InternalServerErrorException(e.getMessage()); + } + + return srv.getProperties(); + } +} diff --git a/src/main/java/valandur/webapi/servlet/TileEntityServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/TileEntityServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/TileEntityServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/TileEntityServlet.java diff --git a/src/main/java/valandur/webapi/servlet/UserServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/UserServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/UserServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/UserServlet.java diff --git a/src/main/java/valandur/webapi/servlet/WorldServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/WorldServlet.java similarity index 100% rename from src/main/java/valandur/webapi/servlet/WorldServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/WorldServlet.java diff --git a/src/main/java/valandur/webapi/servlet/base/BaseServlet.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/BaseServlet.java similarity index 96% rename from src/main/java/valandur/webapi/servlet/base/BaseServlet.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/base/BaseServlet.java index b1048005..8e967005 100644 --- a/src/main/java/valandur/webapi/servlet/base/BaseServlet.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/BaseServlet.java @@ -1,22 +1,22 @@ -package valandur.webapi.servlet.base; - -import valandur.webapi.WebAPI; -import valandur.webapi.block.BlockService; -import valandur.webapi.cache.CacheService; -import valandur.webapi.message.InteractiveMessageService; - -public abstract class BaseServlet { - - protected BlockService blockService; - protected CacheService cacheService; - protected InteractiveMessageService messageService; - protected ServletService servletService; - - - public BaseServlet() { - blockService = WebAPI.getBlockService(); - cacheService = WebAPI.getCacheService(); - messageService = WebAPI.getMessageService(); - servletService = WebAPI.getServletService(); - } -} +package valandur.webapi.servlet.base; + +import valandur.webapi.WebAPI; +import valandur.webapi.block.BlockService; +import valandur.webapi.cache.CacheService; +import valandur.webapi.message.InteractiveMessageService; + +public abstract class BaseServlet { + + protected BlockService blockService; + protected CacheService cacheService; + protected InteractiveMessageService messageService; + protected ServletService servletService; + + + public BaseServlet() { + blockService = WebAPI.getBlockService(); + cacheService = WebAPI.getCacheService(); + messageService = WebAPI.getMessageService(); + servletService = WebAPI.getServletService(); + } +} diff --git a/src/main/java/valandur/webapi/servlet/base/ExplicitDetails.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/ExplicitDetails.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/base/ExplicitDetails.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/base/ExplicitDetails.java index 4a1a081f..c77c44c5 100644 --- a/src/main/java/valandur/webapi/servlet/base/ExplicitDetails.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/ExplicitDetails.java @@ -1,23 +1,23 @@ -package valandur.webapi.servlet.base; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * This annotation tells the Web-API that details should not be included for a certain endpoint, unless explicitly - * requested - */ -@Retention(RUNTIME) -@Target(METHOD) -public @interface ExplicitDetails { - /** - * Usually endpoints include all details of objects they send, but for lists that can contain a lot of objects - * it can be beneficial to mark them so as not to include too much information in one response. - * @return True if the details of the objects this endpoint should only be included when explicitly requested - * by the user - */ - boolean value() default true; -} +package valandur.webapi.servlet.base; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * This annotation tells the Web-API that details should not be included for a certain endpoint, unless explicitly + * requested + */ +@Retention(RUNTIME) +@Target(METHOD) +public @interface ExplicitDetails { + /** + * Usually endpoints include all details of objects they send, but for lists that can contain a lot of objects + * it can be beneficial to mark them so as not to include too much information in one response. + * @return True if the details of the objects this endpoint should only be included when explicitly requested + * by the user + */ + boolean value() default true; +} diff --git a/src/main/java/valandur/webapi/servlet/base/Permission.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/Permission.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/base/Permission.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/base/Permission.java index 63a0b569..b2b6d76d 100644 --- a/src/main/java/valandur/webapi/servlet/base/Permission.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/Permission.java @@ -1,30 +1,30 @@ -package valandur.webapi.servlet.base; - -import java.lang.annotation.Repeatable; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * This annotation tells the Web-API which permissions are required to access the annotated endpoint - */ -@Retention(RUNTIME) -@Target(METHOD) -@Repeatable(Permissions.class) -public @interface Permission { - /** - * The permissions required to access this endpoint. An empty String (the default) means that no permissions are - * required. These permissions are relative to the servlet path, which serves as the root permissions entry. - * @return The permissions required for this endpoint. - */ - String[] value() default {}; - - /** - * Specify whether this permission is automatically checked against the user's permissions. This should usually - * be set to true, unless this permissions is checked manually and only used for the docs. - * @return True if the permission is automatically checked, false otherwise. - */ - boolean autoCheck() default true; -} +package valandur.webapi.servlet.base; + +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * This annotation tells the Web-API which permissions are required to access the annotated endpoint + */ +@Retention(RUNTIME) +@Target(METHOD) +@Repeatable(Permissions.class) +public @interface Permission { + /** + * The permissions required to access this endpoint. An empty String (the default) means that no permissions are + * required. These permissions are relative to the servlet path, which serves as the root permissions entry. + * @return The permissions required for this endpoint. + */ + String[] value() default {}; + + /** + * Specify whether this permission is automatically checked against the user's permissions. This should usually + * be set to true, unless this permissions is checked manually and only used for the docs. + * @return True if the permission is automatically checked, false otherwise. + */ + boolean autoCheck() default true; +} diff --git a/src/main/java/valandur/webapi/servlet/base/Permissions.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/Permissions.java similarity index 96% rename from src/main/java/valandur/webapi/servlet/base/Permissions.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/base/Permissions.java index 260a7b62..d10c005b 100644 --- a/src/main/java/valandur/webapi/servlet/base/Permissions.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/Permissions.java @@ -1,21 +1,21 @@ -package valandur.webapi.servlet.base; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * \@Permission annotations are repeatable, multiple ones means the endpoint requires multiple permissions - */ -@Retention(RUNTIME) -@Target(METHOD) -public @interface Permissions { - - /** - * The permissions required for the annotated endpoint. - * @return An array of permissions required to access the annotated endpoint. - */ - Permission[] value(); -} +package valandur.webapi.servlet.base; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * \@Permission annotations are repeatable, multiple ones means the endpoint requires multiple permissions + */ +@Retention(RUNTIME) +@Target(METHOD) +public @interface Permissions { + + /** + * The permissions required for the annotated endpoint. + * @return An array of permissions required to access the annotated endpoint. + */ + Permission[] value(); +} diff --git a/src/main/java/valandur/webapi/servlet/base/ServletService.java b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/ServletService.java similarity index 97% rename from src/main/java/valandur/webapi/servlet/base/ServletService.java rename to webapi-sponge/src/main/java/valandur/webapi/servlet/base/ServletService.java index 153df642..a5226579 100644 --- a/src/main/java/valandur/webapi/servlet/base/ServletService.java +++ b/webapi-sponge/src/main/java/valandur/webapi/servlet/base/ServletService.java @@ -1,197 +1,197 @@ -package valandur.webapi.servlet.base; - -import org.slf4j.Logger; -import valandur.webapi.WebAPI; -import valandur.webapi.config.BaseConfig; -import valandur.webapi.config.ServletsConfig; -import valandur.webapi.integration.activetime.ActiveTimeServlet; -import valandur.webapi.integration.cmdscheduler.CmdSchedulerServlet; -import valandur.webapi.integration.gwmcrates.GWMCratesServlet; -import valandur.webapi.integration.mmcrestrict.MMCRestrictServlet; -import valandur.webapi.integration.mmctickets.MMCTicketsServlet; -import valandur.webapi.integration.nucleus.NucleusServlet; -import valandur.webapi.integration.redprotect.RedProtectServlet; -import valandur.webapi.integration.universalmarket.UniversalMarketServlet; -import valandur.webapi.integration.villagershops.VShopServlet; -import valandur.webapi.integration.webbooks.WebBooksServlet; -import valandur.webapi.servlet.*; - -import javax.ws.rs.Path; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -/** - * This service allows registering servlets with the Web-API, which it will serve for clients. - * Your servlet must inherit from {@link BaseServlet} and have the - * {@link javax.ws.rs.Path} annotation specifying the base path at which the servlet will - * be accessible. - */ -public class ServletService { - - private static final String configFileName = "servlets.conf"; - - private Map> servletClasses = new HashMap<>(); - - - public void init() { - Logger logger = WebAPI.getLogger(); - - logger.info("Registering servlets..."); - - java.nio.file.Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); - ServletsConfig config = BaseConfig.load(configPath, new ServletsConfig()); - - servletClasses.clear(); - - if (config.Block) registerServlet(BlockServlet.class); - if (config.Chunk) registerServlet(ChunkServlet.class); - if (config.Cmd) registerServlet(CmdServlet.class); - if (config.Economy) registerServlet(EconomyServlet.class); - if (config.Entity) registerServlet(EntityServlet.class); - if (config.History) registerServlet(HistoryServlet.class); - if (config.Info) registerServlet(InfoServlet.class); - if (config.InteractiveMessage) registerServlet(InteractiveMessageServlet.class); - if (config.Map) registerServlet(MapServlet.class); - if (config.Permission) registerServlet(PermissionServlet.class); - if (config.Player) registerServlet(PlayerServlet.class); - if (config.Plugin) registerServlet(PluginServlet.class); - if (config.Recipe) registerServlet(RecipeServlet.class); - if (config.Registry) registerServlet(RegistryServlet.class); - if (config.Server) registerServlet(ServerServlet.class); - if (config.TileEntity) registerServlet(TileEntityServlet.class); - if (config.User) registerServlet(UserServlet.class); - if (config.World) registerServlet(WorldServlet.class); - - // Other plugin integrations - if (config.integrations.ActiveTime) { - try { - Class.forName("com.mcsimonflash.sponge.activetime.ActiveTime"); - logger.info(" Integrating with ActiveTime..."); - registerServlet(ActiveTimeServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.CmdScheduler) { - try { - Class.forName("com.mcsimonflash.sponge.cmdscheduler.CmdScheduler"); - logger.info(" Integrating with CmdScheduler..."); - registerServlet(CmdSchedulerServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.GWMCrates) { - try { - Class.forName("org.gwmdevelopments.sponge_plugin.crates.GWMCrates"); - logger.info(" Integrating with GWMCrates..."); - registerServlet(GWMCratesServlet.class); - } catch (ClassNotFoundException ignored) { - } - } - - /*if (config.integrations.HuskyCrates) { - try { - Class.forName("com.codehusky.huskycrates.HuskyCrates"); - logger.info(" Integrating with HuskyCrates..."); - registerServlet(HuskyCratesServlet.class); - } catch (ClassNotFoundException ignored) { } - }*/ - - if (config.integrations.MMCRestrict) { - try { - Class.forName("net.moddedminecraft.mmcrestrict.Main"); - logger.info(" Integrating with MMCRestrict..."); - registerServlet(MMCRestrictServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.MMCTickets) { - try { - Class.forName("net.moddedminecraft.mmctickets.Main"); - logger.info(" Integrating with MMCTickets..."); - registerServlet(MMCTicketsServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.Nucleus) { - try { - Class.forName("io.github.nucleuspowered.nucleus.api.NucleusAPI"); - logger.info(" Integrating with Nucleus..."); - registerServlet(NucleusServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.RedProtect) { - try { - Class.forName("br.net.fabiozumbi12.RedProtect.Sponge.RedProtect"); - logger.info(" Integrating with RedProtect..."); - registerServlet(RedProtectServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.UniversalMarket) { - try { - Class.forName("com.xwaffle.universalmarket.UniversalMarket"); - logger.info(" Integrating with UniversalMarket..."); - registerServlet(UniversalMarketServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.VillagerShops) { - try { - Class.forName("de.dosmike.sponge.vshop.VillagerShops"); - logger.info(" Integrating with VillagerShops..."); - registerServlet(VShopServlet.class); - } catch (ClassNotFoundException ignored) { } - } - - if (config.integrations.WebBooks) { - try { - Class.forName("de.dosmike.sponge.WebBooks.WebBooks"); - logger.info(" Integrating with WebBooks..."); - registerServlet(WebBooksServlet.class); - } catch (ClassNotFoundException ignored) { } - } - } - - /** - * Register a servlet with the WebAPI, which will give it a separate base address - * @param servlet The class of servlet to register. The WebAPI will create an instance when starting. Make - * sure to provide an empty constructor. - */ - public void registerServlet(Class servlet) { - Logger logger = WebAPI.getLogger(); - - if (!servlet.isAnnotationPresent(Path.class)) { - logger.error("Servlet " + servlet.getName() + " is missing @Path annotation"); - return; - } - - Path info = servlet.getAnnotation(Path.class); - String basePath = info.value(); - if (basePath.endsWith("/")) - basePath = basePath.substring(0, basePath.length() - 1); - if (!basePath.startsWith("/")) - basePath = "/" + basePath; - - try { - Method m = servlet.getMethod("onRegister"); - m.invoke(null); - } catch (NoSuchMethodException ignored) { - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - WebAPI.sentryCapture(e); - } - - servletClasses.put(basePath, servlet); - } - - /** - * Gets a map of all available base paths mapped to the servlets that implement them. - * @return A map from base path to implementing servlet class. - */ - public Map> getRegisteredServlets() { - return servletClasses; - } -} +package valandur.webapi.servlet.base; + +import org.slf4j.Logger; +import valandur.webapi.WebAPI; +import valandur.webapi.config.BaseConfig; +import valandur.webapi.config.ServletsConfig; +import valandur.webapi.integration.activetime.ActiveTimeServlet; +import valandur.webapi.integration.cmdscheduler.CmdSchedulerServlet; +import valandur.webapi.integration.gwmcrates.GWMCratesServlet; +import valandur.webapi.integration.mmcrestrict.MMCRestrictServlet; +import valandur.webapi.integration.mmctickets.MMCTicketsServlet; +import valandur.webapi.integration.nucleus.NucleusServlet; +import valandur.webapi.integration.redprotect.RedProtectServlet; +import valandur.webapi.integration.universalmarket.UniversalMarketServlet; +import valandur.webapi.integration.villagershops.VShopServlet; +import valandur.webapi.integration.webbooks.WebBooksServlet; +import valandur.webapi.servlet.*; + +import javax.ws.rs.Path; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * This service allows registering servlets with the Web-API, which it will serve for clients. + * Your servlet must inherit from {@link BaseServlet} and have the + * {@link javax.ws.rs.Path} annotation specifying the base path at which the servlet will + * be accessible. + */ +public class ServletService { + + private static final String configFileName = "servlets.conf"; + + private Map> servletClasses = new HashMap<>(); + + + public void init() { + Logger logger = WebAPI.getLogger(); + + logger.info("Registering servlets..."); + + java.nio.file.Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); + ServletsConfig config = BaseConfig.load(configPath, new ServletsConfig()); + + servletClasses.clear(); + + if (config.Block) registerServlet(BlockServlet.class); + if (config.Chunk) registerServlet(ChunkServlet.class); + if (config.Cmd) registerServlet(CmdServlet.class); + if (config.Economy) registerServlet(EconomyServlet.class); + if (config.Entity) registerServlet(EntityServlet.class); + if (config.History) registerServlet(HistoryServlet.class); + if (config.Info) registerServlet(InfoServlet.class); + if (config.InteractiveMessage) registerServlet(InteractiveMessageServlet.class); + if (config.Map) registerServlet(MapServlet.class); + if (config.Permission) registerServlet(PermissionServlet.class); + if (config.Player) registerServlet(PlayerServlet.class); + if (config.Plugin) registerServlet(PluginServlet.class); + if (config.Recipe) registerServlet(RecipeServlet.class); + if (config.Registry) registerServlet(RegistryServlet.class); + if (config.Server) registerServlet(ServerServlet.class); + if (config.TileEntity) registerServlet(TileEntityServlet.class); + if (config.User) registerServlet(UserServlet.class); + if (config.World) registerServlet(WorldServlet.class); + + // Other plugin integrations + if (config.integrations.ActiveTime) { + try { + Class.forName("com.mcsimonflash.sponge.activetime.ActiveTime"); + logger.info(" Integrating with ActiveTime..."); + registerServlet(ActiveTimeServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.CmdScheduler) { + try { + Class.forName("com.mcsimonflash.sponge.cmdscheduler.CmdScheduler"); + logger.info(" Integrating with CmdScheduler..."); + registerServlet(CmdSchedulerServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.GWMCrates) { + try { + Class.forName("org.gwmdevelopments.sponge_plugin.crates.GWMCrates"); + logger.info(" Integrating with GWMCrates..."); + registerServlet(GWMCratesServlet.class); + } catch (ClassNotFoundException ignored) { + } + } + + /*if (config.integrations.HuskyCrates) { + try { + Class.forName("com.codehusky.huskycrates.HuskyCrates"); + logger.info(" Integrating with HuskyCrates..."); + registerServlet(HuskyCratesServlet.class); + } catch (ClassNotFoundException ignored) { } + }*/ + + if (config.integrations.MMCRestrict) { + try { + Class.forName("net.moddedminecraft.mmcrestrict.Main"); + logger.info(" Integrating with MMCRestrict..."); + registerServlet(MMCRestrictServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.MMCTickets) { + try { + Class.forName("net.moddedminecraft.mmctickets.Main"); + logger.info(" Integrating with MMCTickets..."); + registerServlet(MMCTicketsServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.Nucleus) { + try { + Class.forName("io.github.nucleuspowered.nucleus.api.NucleusAPI"); + logger.info(" Integrating with Nucleus..."); + registerServlet(NucleusServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.RedProtect) { + try { + Class.forName("br.net.fabiozumbi12.RedProtect.Sponge.RedProtect"); + logger.info(" Integrating with RedProtect..."); + registerServlet(RedProtectServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.UniversalMarket) { + try { + Class.forName("com.xwaffle.universalmarket.UniversalMarket"); + logger.info(" Integrating with UniversalMarket..."); + registerServlet(UniversalMarketServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.VillagerShops) { + try { + Class.forName("de.dosmike.sponge.vshop.VillagerShops"); + logger.info(" Integrating with VillagerShops..."); + registerServlet(VShopServlet.class); + } catch (ClassNotFoundException ignored) { } + } + + if (config.integrations.WebBooks) { + try { + Class.forName("de.dosmike.sponge.WebBooks.WebBooks"); + logger.info(" Integrating with WebBooks..."); + registerServlet(WebBooksServlet.class); + } catch (ClassNotFoundException ignored) { } + } + } + + /** + * Register a servlet with the WebAPI, which will give it a separate base address + * @param servlet The class of servlet to register. The WebAPI will create an instance when starting. Make + * sure to provide an empty constructor. + */ + public void registerServlet(Class servlet) { + Logger logger = WebAPI.getLogger(); + + if (!servlet.isAnnotationPresent(Path.class)) { + logger.error("Servlet " + servlet.getName() + " is missing @Path annotation"); + return; + } + + Path info = servlet.getAnnotation(Path.class); + String basePath = info.value(); + if (basePath.endsWith("/")) + basePath = basePath.substring(0, basePath.length() - 1); + if (!basePath.startsWith("/")) + basePath = "/" + basePath; + + try { + Method m = servlet.getMethod("onRegister"); + m.invoke(null); + } catch (NoSuchMethodException ignored) { + } catch (IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + WebAPI.sentryCapture(e); + } + + servletClasses.put(basePath, servlet); + } + + /** + * Gets a map of all available base paths mapped to the servlets that implement them. + * @return A map from base path to implementing servlet class. + */ + public Map> getRegisteredServlets() { + return servletClasses; + } +} diff --git a/src/main/java/valandur/webapi/swagger/SwaggerDefinition.java b/webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerDefinition.java similarity index 98% rename from src/main/java/valandur/webapi/swagger/SwaggerDefinition.java rename to webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerDefinition.java index 84d09f70..d7478279 100644 --- a/src/main/java/valandur/webapi/swagger/SwaggerDefinition.java +++ b/webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerDefinition.java @@ -1,325 +1,325 @@ -package valandur.webapi.swagger; - -import io.swagger.annotations.*; -import io.swagger.annotations.Contact; -import io.swagger.annotations.Info; -import io.swagger.annotations.License; -import io.swagger.converter.ModelConverter; -import io.swagger.converter.ModelConverterContextImpl; -import io.swagger.converter.ModelConverters; -import io.swagger.jaxrs.Reader; -import io.swagger.jaxrs.config.ReaderListener; -import io.swagger.models.*; -import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.ObjectProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; -import org.spongepowered.api.data.manipulator.DataManipulator; -import valandur.webapi.WebAPI; -import valandur.webapi.servlet.base.BaseServlet; -import valandur.webapi.util.Constants; - -import javax.ws.rs.core.MediaType; -import java.lang.reflect.Field; -import java.util.*; -import java.util.stream.Collectors; - -@io.swagger.annotations.SwaggerDefinition( - info = @Info( - title = Constants.NAME, - version = Constants.VERSION, - description = "Access Sponge powered Minecraft servers through a WebAPI\n\n" + - "# Introduction\n" + - "This is the documentation of the various API routes offered by the WebAPI plugin.\n\n" + - "This documentation assumes that you are familiar with the basic concepts of Web API's, " + - "such as `GET`, `PUT`, `POST` and `DELETE` methods, request `HEADERS` and `RESPONSE CODES` " + - "and `JSON` data.\n\n" + - "By default this documentation can be found at http:/localhost:8080 " + - "(while your minecraft server is running) and the various routes start with " + - "http:/localhost:8080/api/v5...\n\n" + - "As a quick test try reaching the route http:/localhost:8080/api/v5/info " + - "(remember that you can only access \\\"localhost\\\" routes on the server on which you " + - "are running minecraft).\n" + - "This route should show you basic information about your server, like the motd and " + - "player count.\n\n" + - "# List endpoints\n" + - "Lots of objects offer an endpoint to list all objects (e.g. `GET: /world` to get all worlds). " + - "These endpoints return only the properties marked 'required' by default, because the list " + - "might be quite large. If you want to return ALL data for a list endpoint add the query " + - "parameter `details`, (e.g. `GET: /world?details`).\n\n" + - "> Remember that in this case the data returned by the endpoint might be quite large.\n\n" + - "# Debugging endpoints\n" + - "Apart from the `?details` flag you can also pass some other flags for debugging purposes. " + - "Remember that you must include the first query parameter with `?`, and further ones with `&`:\n\n" + - "`details`: Includes details for list endpoints\n\n" + - "`accept=[json/xml]`: Manually set the accept content type. This is good for browser testing, " + - "**BUT DON'T USE THIS IN PRODUCTION, YOU CAN SUPPLY THE `Accepts` HEADER FOR THAT**\n\n" + - "`pretty`: Pretty prints the data, also good for debugging in the browser.\n\n" + - "An example request might look like this: " + - "`http://localhost:8080/api/v5/world?details&accpet=json&pretty&key=MY-API-KEY`\n\n" + - "# Additional data\n" + - "Certain endpoints (such as `/player`, `/entity` and `/tile-entity` have additional " + - "properties which are not documented here, because the data depends on the concrete " + - "object type (eg. `Sheep` have a wool color, others do not) and on the other plugins/mods " + - "that are running on your server which might add additional data.\n\n" + - "You can also find more information in the github docs " + - "(https:/github.com/Valandur/Web-API/tree/master/docs/DATA.md)", - contact = @Contact( - name = "Valandur", - email = "inithilian@gmail.com", - url = "https://github.com/Valandur" - ), - license = @License( - name = "MIT", - url = "https://github.com/Valandur/Web-API/blob/master/LICENSE" - ) - ), - consumes = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }, - produces = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }, - securityDefinition = @SecurityDefinition(apiKeyAuthDefinitions = { - @ApiKeyAuthDefinition( - key = "ApiKeyHeader", - name = "X-WebAPI-Key", - description = "Authorize using an HTTP header. This can also be done using the " + - "`Authorization` header with a `Bearer` token", - in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER), - @ApiKeyAuthDefinition( - key = "ApiKeyQuery", - name = "key", - description = "Authorize using a query value.", - in = ApiKeyAuthDefinition.ApiKeyLocation.QUERY), - }) -) -public class SwaggerDefinition implements ReaderListener { - - private static QueryParameter constructQueryParameter(String name, String description, String... values) { - QueryParameter param = new QueryParameter(); - param.setName(name); - param.setDescription(description); - if (values != null && values.length > 0) { - param.setType("string"); - param.setEnum(Arrays.asList(values)); - } else { - param.setType("boolean"); - } - return param; - } - private static Response constructResponse(int status, String error) { - Property statusProp = new IntegerProperty() - .description("The status code of the error (also provided in the HTTP header)"); - statusProp.setExample(status); - - Property errorProp = new StringProperty() - .description("The error message describing the error"); - errorProp.setExample((Object)error); - - return new Response() - .description(error) - .schema(new ObjectProperty() - .property("status", statusProp) - .property("error", errorProp)); - } - - @Override - public void beforeScan(Reader reader, Swagger swagger) { - swagger.addParameter("details", constructQueryParameter( - "details", - "Add to include additional details, omit or false otherwise")); - swagger.addParameter("accept", constructQueryParameter( - "accept", - "Override the 'Accept' request header (useful for debugging your requests)", - "json", "xml")); - swagger.addParameter("pretty", constructQueryParameter( - "pretty", - "Add to make the Web-API pretty print the response (useful for debugging your requests)")); - - swagger.response("400", constructResponse(400, "Bad request")); - swagger.response("401", constructResponse(401, "Unauthorized")); - swagger.response("403", constructResponse(403, "Access denied")); - swagger.response("404", constructResponse(404, "Not found")); - swagger.response("500", constructResponse(500, "Internal server error")); - swagger.response("501", constructResponse(501, "Not implemented")); - } - - @Override - public void afterScan(Reader reader, Swagger swagger) { - List webapiTags = new ArrayList<>(); - List integrationTags = new ArrayList<>(); - - swagger.setTags(new ArrayList<>()); - - // Collect tags for servlets - for (Class servletClass : WebAPI.getServletService().getRegisteredServlets().values()) { - Api api = servletClass.getAnnotation(Api.class); - String descr = api.value(); - - Set tags = new HashSet<>(Arrays.asList(api.tags())); - tags.addAll(Arrays.stream(servletClass.getMethods()) - .flatMap(m -> Arrays.stream(m.getAnnotationsByType(ApiOperation.class))) - .flatMap(a -> Arrays.stream(a.tags())) - .filter(t -> !t.isEmpty()) - .collect(Collectors.toList())); - - if (servletClass.getPackage().getName().startsWith("valandur.webapi.servlet")) { - for (String tag : tags) { - webapiTags.add(tag); - swagger.addTag(new io.swagger.models.Tag().name(tag).description(descr)); - } - } else { - for (String tag : tags) { - integrationTags.add(tag); - swagger.addTag(new io.swagger.models.Tag().name(tag).description(descr)); - } - } - } - - // Sort properties by "required" and alphabetically - for (Model model : swagger.getDefinitions().values()) { - Map props = new LinkedHashMap<>(); - if (model.getProperties() == null) continue; - - List> newProps = model.getProperties().entrySet().stream() - .sorted((p1, p2) -> { - int req = Boolean.compare(p2.getValue().getRequired(), p1.getValue().getRequired()); - if (req != 0) return req; - return p1.getKey().compareTo(p2.getKey()); - }).collect(Collectors.toList()); - for (Map.Entry newProp : newProps) { - props.put(newProp.getKey(), newProp.getValue()); - } - model.getProperties().clear(); - model.setProperties(props); - } - - // Dirty hack to set up our model converter, because we need access to the context, - // otherwise we have to do multiple calls resolving the model, which isn't worth it - List converters = new ArrayList<>(); - try { - Field f = ModelConverters.class.getDeclaredField("converters"); - f.setAccessible(true); - converters = (List) f.get(ModelConverters.getInstance()); - } catch (IllegalAccessException | NoSuchFieldException e) { - e.printStackTrace(); - WebAPI.sentryCapture(e); - } - - Set oldModels = swagger.getDefinitions().keySet(); - - // Generate types for additional data - Map props = new LinkedHashMap<>(); - // Collect all additional data from our serializer - List>>> dataList = - WebAPI.getSerializeService().getSupportedData().entrySet().stream() - .sorted(Comparator.comparing(Map.Entry::getKey)) - .collect(Collectors.toList()); - // Iterate all the additional data - for (Map.Entry>> entry : dataList) { - String key = entry.getKey(); - - // Create our context and resolve the model (manually, instead of ModelConverters.getInstance().readYYY() - ModelConverterContextImpl context = new ModelConverterContextImpl(converters); - Property prop = context.resolveProperty(entry.getValue(), null); - - // Read the view as a model, and add all the read models to the definition - for (Map.Entry modelEntry : context.getDefinedModels().entrySet()) { - if (oldModels.contains(modelEntry.getKey())) { - continue; - } - - swagger.addDefinition(modelEntry.getKey(), modelEntry.getValue()); - } - - // Add the data we read - props.put(key, prop); - } - - // Collect all additional properties from our serializer - List>, String>> propList = - WebAPI.getSerializeService().getSupportedProperties().entrySet().stream() - .sorted(Comparator.comparing(Map.Entry::getValue)) - .collect(Collectors.toList()); - // Iterate all the additional props - for (Map.Entry>, String> entry : propList) { - String key = entry.getValue(); - - // Create our context and resolve the model (manually, instead of ModelConverters.getInstance().readYYY() - ModelConverterContextImpl context = new ModelConverterContextImpl(converters); - Property prop = context.resolveProperty(entry.getKey(), null); - - // Read the view as a model, and add all the read models to the definition - for (Map.Entry modelEntry : context.getDefinedModels().entrySet()) { - if (oldModels.contains(modelEntry.getKey())) { - continue; - } - - swagger.addDefinition(modelEntry.getKey(), modelEntry.getValue()); - } - - // Add the property we read to the data props - props.put(key, prop); - } - - // Add the additional properties to the required DataObjects - // TODO: Automate this with an annotation - Map defs = swagger.getDefinitions(); - attachAdditionalProps(defs.get("Player"), props); - attachAdditionalProps(defs.get("World"), props); - attachAdditionalProps(defs.get("Entity"), props); - attachAdditionalProps(defs.get("TileEntity"), props); - attachAdditionalProps(defs.get("ItemStack"), props); - attachAdditionalProps(defs.get("FluidStack"), props); - attachAdditionalProps(defs.get("Slot"), props); - - // Sort tags alphabetically - webapiTags.sort(String::compareTo); - integrationTags.sort(String::compareTo); - - // Sort paths alphabetically - List> paths = swagger.getPaths().entrySet().stream() - .sorted(Comparator.comparing(Map.Entry::getKey)) - .collect(Collectors.toList()); - swagger.setPaths(new LinkedHashMap<>()); - for (Map.Entry entry : paths) { - swagger.path(entry.getKey(), entry.getValue()); - } - - // Add tag groups for redoc - swagger.vendorExtension("x-tagGroups", Arrays.asList( - new TagGroup("Web-API", webapiTags), - new TagGroup("Integrations", integrationTags) - )); - } - - private void attachAdditionalProps(Model model, Map dataProps) { - if (model instanceof ComposedModel) { - model = ((ComposedModel) model).getChild(); - } - Map props = model.getProperties(); - if (props == null) { - props = new HashMap<>(); - } - for (Map.Entry entry : dataProps.entrySet()) { - props.put(entry.getKey(), entry.getValue()); - } - model.setProperties(props); - } - - - public static class TagGroup { - private String name; - public String getName() { - return name; - } - - private List tags; - public List getTags() { - return tags; - } - - public TagGroup(String name, List tags) { - this.name = name; - this.tags = tags; - } - } -} +package valandur.webapi.swagger; + +import io.swagger.annotations.*; +import io.swagger.annotations.Contact; +import io.swagger.annotations.Info; +import io.swagger.annotations.License; +import io.swagger.converter.ModelConverter; +import io.swagger.converter.ModelConverterContextImpl; +import io.swagger.converter.ModelConverters; +import io.swagger.jaxrs.Reader; +import io.swagger.jaxrs.config.ReaderListener; +import io.swagger.models.*; +import io.swagger.models.parameters.QueryParameter; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.ObjectProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; +import org.spongepowered.api.data.manipulator.DataManipulator; +import valandur.webapi.WebAPI; +import valandur.webapi.servlet.base.BaseServlet; +import valandur.webapi.util.Constants; + +import javax.ws.rs.core.MediaType; +import java.lang.reflect.Field; +import java.util.*; +import java.util.stream.Collectors; + +@io.swagger.annotations.SwaggerDefinition( + info = @Info( + title = Constants.NAME, + version = Constants.VERSION, + description = "Access Sponge powered Minecraft servers through a WebAPI\n\n" + + "# Introduction\n" + + "This is the documentation of the various API routes offered by the WebAPI plugin.\n\n" + + "This documentation assumes that you are familiar with the basic concepts of Web API's, " + + "such as `GET`, `PUT`, `POST` and `DELETE` methods, request `HEADERS` and `RESPONSE CODES` " + + "and `JSON` data.\n\n" + + "By default this documentation can be found at http:/localhost:8080 " + + "(while your minecraft server is running) and the various routes start with " + + "http:/localhost:8080/api/v5...\n\n" + + "As a quick test try reaching the route http:/localhost:8080/api/v5/info " + + "(remember that you can only access \\\"localhost\\\" routes on the server on which you " + + "are running minecraft).\n" + + "This route should show you basic information about your server, like the motd and " + + "player count.\n\n" + + "# List endpoints\n" + + "Lots of objects offer an endpoint to list all objects (e.g. `GET: /world` to get all worlds). " + + "These endpoints return only the properties marked 'required' by default, because the list " + + "might be quite large. If you want to return ALL data for a list endpoint add the query " + + "parameter `details`, (e.g. `GET: /world?details`).\n\n" + + "> Remember that in this case the data returned by the endpoint might be quite large.\n\n" + + "# Debugging endpoints\n" + + "Apart from the `?details` flag you can also pass some other flags for debugging purposes. " + + "Remember that you must include the first query parameter with `?`, and further ones with `&`:\n\n" + + "`details`: Includes details for list endpoints\n\n" + + "`accept=[json/xml]`: Manually set the accept content type. This is good for browser testing, " + + "**BUT DON'T USE THIS IN PRODUCTION, YOU CAN SUPPLY THE `Accepts` HEADER FOR THAT**\n\n" + + "`pretty`: Pretty prints the data, also good for debugging in the browser.\n\n" + + "An example request might look like this: " + + "`http://localhost:8080/api/v5/world?details&accpet=json&pretty&key=MY-API-KEY`\n\n" + + "# Additional data\n" + + "Certain endpoints (such as `/player`, `/entity` and `/tile-entity` have additional " + + "properties which are not documented here, because the data depends on the concrete " + + "object type (eg. `Sheep` have a wool color, others do not) and on the other plugins/mods " + + "that are running on your server which might add additional data.\n\n" + + "You can also find more information in the github docs " + + "(https:/github.com/Valandur/Web-API/tree/master/docs/DATA.md)", + contact = @Contact( + name = "Valandur", + email = "inithilian@gmail.com", + url = "https://github.com/Valandur" + ), + license = @License( + name = "MIT", + url = "https://github.com/Valandur/Web-API/blob/master/LICENSE" + ) + ), + consumes = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }, + produces = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }, + securityDefinition = @SecurityDefinition(apiKeyAuthDefinitions = { + @ApiKeyAuthDefinition( + key = "ApiKeyHeader", + name = "X-WebAPI-Key", + description = "Authorize using an HTTP header. This can also be done using the " + + "`Authorization` header with a `Bearer` token", + in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER), + @ApiKeyAuthDefinition( + key = "ApiKeyQuery", + name = "key", + description = "Authorize using a query value.", + in = ApiKeyAuthDefinition.ApiKeyLocation.QUERY), + }) +) +public class SwaggerDefinition implements ReaderListener { + + private static QueryParameter constructQueryParameter(String name, String description, String... values) { + QueryParameter param = new QueryParameter(); + param.setName(name); + param.setDescription(description); + if (values != null && values.length > 0) { + param.setType("string"); + param.setEnum(Arrays.asList(values)); + } else { + param.setType("boolean"); + } + return param; + } + private static Response constructResponse(int status, String error) { + Property statusProp = new IntegerProperty() + .description("The status code of the error (also provided in the HTTP header)"); + statusProp.setExample(status); + + Property errorProp = new StringProperty() + .description("The error message describing the error"); + errorProp.setExample((Object)error); + + return new Response() + .description(error) + .schema(new ObjectProperty() + .property("status", statusProp) + .property("error", errorProp)); + } + + @Override + public void beforeScan(Reader reader, Swagger swagger) { + swagger.addParameter("details", constructQueryParameter( + "details", + "Add to include additional details, omit or false otherwise")); + swagger.addParameter("accept", constructQueryParameter( + "accept", + "Override the 'Accept' request header (useful for debugging your requests)", + "json", "xml")); + swagger.addParameter("pretty", constructQueryParameter( + "pretty", + "Add to make the Web-API pretty print the response (useful for debugging your requests)")); + + swagger.response("400", constructResponse(400, "Bad request")); + swagger.response("401", constructResponse(401, "Unauthorized")); + swagger.response("403", constructResponse(403, "Access denied")); + swagger.response("404", constructResponse(404, "Not found")); + swagger.response("500", constructResponse(500, "Internal server error")); + swagger.response("501", constructResponse(501, "Not implemented")); + } + + @Override + public void afterScan(Reader reader, Swagger swagger) { + List webapiTags = new ArrayList<>(); + List integrationTags = new ArrayList<>(); + + swagger.setTags(new ArrayList<>()); + + // Collect tags for servlets + for (Class servletClass : WebAPI.getServletService().getRegisteredServlets().values()) { + Api api = servletClass.getAnnotation(Api.class); + String descr = api.value(); + + Set tags = new HashSet<>(Arrays.asList(api.tags())); + tags.addAll(Arrays.stream(servletClass.getMethods()) + .flatMap(m -> Arrays.stream(m.getAnnotationsByType(ApiOperation.class))) + .flatMap(a -> Arrays.stream(a.tags())) + .filter(t -> !t.isEmpty()) + .collect(Collectors.toList())); + + if (servletClass.getPackage().getName().startsWith("valandur.webapi.servlet")) { + for (String tag : tags) { + webapiTags.add(tag); + swagger.addTag(new io.swagger.models.Tag().name(tag).description(descr)); + } + } else { + for (String tag : tags) { + integrationTags.add(tag); + swagger.addTag(new io.swagger.models.Tag().name(tag).description(descr)); + } + } + } + + // Sort properties by "required" and alphabetically + for (Model model : swagger.getDefinitions().values()) { + Map props = new LinkedHashMap<>(); + if (model.getProperties() == null) continue; + + List> newProps = model.getProperties().entrySet().stream() + .sorted((p1, p2) -> { + int req = Boolean.compare(p2.getValue().getRequired(), p1.getValue().getRequired()); + if (req != 0) return req; + return p1.getKey().compareTo(p2.getKey()); + }).collect(Collectors.toList()); + for (Map.Entry newProp : newProps) { + props.put(newProp.getKey(), newProp.getValue()); + } + model.getProperties().clear(); + model.setProperties(props); + } + + // Dirty hack to set up our model converter, because we need access to the context, + // otherwise we have to do multiple calls resolving the model, which isn't worth it + List converters = new ArrayList<>(); + try { + Field f = ModelConverters.class.getDeclaredField("converters"); + f.setAccessible(true); + converters = (List) f.get(ModelConverters.getInstance()); + } catch (IllegalAccessException | NoSuchFieldException e) { + e.printStackTrace(); + WebAPI.sentryCapture(e); + } + + Set oldModels = swagger.getDefinitions().keySet(); + + // Generate types for additional data + Map props = new LinkedHashMap<>(); + // Collect all additional data from our serializer + List>>> dataList = + WebAPI.getSerializeService().getSupportedData().entrySet().stream() + .sorted(Comparator.comparing(Map.Entry::getKey)) + .collect(Collectors.toList()); + // Iterate all the additional data + for (Map.Entry>> entry : dataList) { + String key = entry.getKey(); + + // Create our context and resolve the model (manually, instead of ModelConverters.getInstance().readYYY() + ModelConverterContextImpl context = new ModelConverterContextImpl(converters); + Property prop = context.resolveProperty(entry.getValue(), null); + + // Read the view as a model, and add all the read models to the definition + for (Map.Entry modelEntry : context.getDefinedModels().entrySet()) { + if (oldModels.contains(modelEntry.getKey())) { + continue; + } + + swagger.addDefinition(modelEntry.getKey(), modelEntry.getValue()); + } + + // Add the data we read + props.put(key, prop); + } + + // Collect all additional properties from our serializer + List>, String>> propList = + WebAPI.getSerializeService().getSupportedProperties().entrySet().stream() + .sorted(Comparator.comparing(Map.Entry::getValue)) + .collect(Collectors.toList()); + // Iterate all the additional props + for (Map.Entry>, String> entry : propList) { + String key = entry.getValue(); + + // Create our context and resolve the model (manually, instead of ModelConverters.getInstance().readYYY() + ModelConverterContextImpl context = new ModelConverterContextImpl(converters); + Property prop = context.resolveProperty(entry.getKey(), null); + + // Read the view as a model, and add all the read models to the definition + for (Map.Entry modelEntry : context.getDefinedModels().entrySet()) { + if (oldModels.contains(modelEntry.getKey())) { + continue; + } + + swagger.addDefinition(modelEntry.getKey(), modelEntry.getValue()); + } + + // Add the property we read to the data props + props.put(key, prop); + } + + // Add the additional properties to the required DataObjects + // TODO: Automate this with an annotation + Map defs = swagger.getDefinitions(); + attachAdditionalProps(defs.get("Player"), props); + attachAdditionalProps(defs.get("World"), props); + attachAdditionalProps(defs.get("Entity"), props); + attachAdditionalProps(defs.get("TileEntity"), props); + attachAdditionalProps(defs.get("ItemStack"), props); + attachAdditionalProps(defs.get("FluidStack"), props); + attachAdditionalProps(defs.get("Slot"), props); + + // Sort tags alphabetically + webapiTags.sort(String::compareTo); + integrationTags.sort(String::compareTo); + + // Sort paths alphabetically + List> paths = swagger.getPaths().entrySet().stream() + .sorted(Comparator.comparing(Map.Entry::getKey)) + .collect(Collectors.toList()); + swagger.setPaths(new LinkedHashMap<>()); + for (Map.Entry entry : paths) { + swagger.path(entry.getKey(), entry.getValue()); + } + + // Add tag groups for redoc + swagger.vendorExtension("x-tagGroups", Arrays.asList( + new TagGroup("Web-API", webapiTags), + new TagGroup("Integrations", integrationTags) + )); + } + + private void attachAdditionalProps(Model model, Map dataProps) { + if (model instanceof ComposedModel) { + model = ((ComposedModel) model).getChild(); + } + Map props = model.getProperties(); + if (props == null) { + props = new HashMap<>(); + } + for (Map.Entry entry : dataProps.entrySet()) { + props.put(entry.getKey(), entry.getValue()); + } + model.setProperties(props); + } + + + public static class TagGroup { + private String name; + public String getName() { + return name; + } + + private List tags; + public List getTags() { + return tags; + } + + public TagGroup(String name, List tags) { + this.name = name; + this.tags = tags; + } + } +} diff --git a/src/main/java/valandur/webapi/swagger/SwaggerExtension.java b/webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerExtension.java similarity index 97% rename from src/main/java/valandur/webapi/swagger/SwaggerExtension.java rename to webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerExtension.java index f0479412..f07e8c8a 100644 --- a/src/main/java/valandur/webapi/swagger/SwaggerExtension.java +++ b/webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerExtension.java @@ -1,66 +1,66 @@ -package valandur.webapi.swagger; - -import io.swagger.jersey.SwaggerJersey2Jaxrs; -import io.swagger.models.Operation; -import io.swagger.models.RefResponse; -import io.swagger.models.parameters.RefParameter; -import valandur.webapi.exceptions.NotImplementedException; -import valandur.webapi.servlet.base.Permission; - -import javax.ws.rs.BadRequestException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.Path; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Iterator; - -public class SwaggerExtension extends SwaggerJersey2Jaxrs { - - @Override - public void decorateOperation(Operation operation, Method method, - Iterator chain) { - // Automatically add query params - operation.addParameter(new RefParameter("details")); - operation.addParameter(new RefParameter("accept")); - operation.addParameter(new RefParameter("pretty")); - - // Automatically add 500 as a possible response - operation.addResponse("500", new RefResponse("500")); - - // Automatically add error codes depending on thrown exceptions - for (Class execClass : method.getExceptionTypes()) { - if (BadRequestException.class.isAssignableFrom(execClass)) { - operation.addResponse("400", new RefResponse("400")); - } - if (NotFoundException.class.isAssignableFrom(execClass)) { - operation.addResponse("404", new RefResponse("404")); - } - if (NotImplementedException.class.isAssignableFrom(execClass)) { - operation.addResponse("501", new RefResponse("501")); - } - } - - Permission[] perms = method.getAnnotationsByType(Permission.class); - if (perms.length > 0) { - // Automatically add 401 & 403 as a possible response - operation.addResponse("401", new RefResponse("401")); - operation.addResponse("403", new RefResponse("403")); - - // Automatically add required permission notes if we have a @Permission annotation - Path path = method.getDeclaringClass().getAnnotation(Path.class); - String prefix = path != null ? path.value() + "." : ""; - - StringBuilder permStr = new StringBuilder(" \n\n **Required permissions:** \n\n"); - for (Permission perm : perms) { - permStr.append("- **").append(prefix).append(String.join(".", perm.value())).append("** \n"); - } - - operation.setDescription(operation.getDescription() + permStr.toString()); - - // Add security definitions - operation.addSecurity("ApiKeyHeader", new ArrayList<>()); - operation.addSecurity("ApiKeyQuery", new ArrayList<>()); - } - super.decorateOperation(operation, method, chain); - } -} +package valandur.webapi.swagger; + +import io.swagger.jersey.SwaggerJersey2Jaxrs; +import io.swagger.models.Operation; +import io.swagger.models.RefResponse; +import io.swagger.models.parameters.RefParameter; +import valandur.webapi.exceptions.NotImplementedException; +import valandur.webapi.servlet.base.Permission; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.Path; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Iterator; + +public class SwaggerExtension extends SwaggerJersey2Jaxrs { + + @Override + public void decorateOperation(Operation operation, Method method, + Iterator chain) { + // Automatically add query params + operation.addParameter(new RefParameter("details")); + operation.addParameter(new RefParameter("accept")); + operation.addParameter(new RefParameter("pretty")); + + // Automatically add 500 as a possible response + operation.addResponse("500", new RefResponse("500")); + + // Automatically add error codes depending on thrown exceptions + for (Class execClass : method.getExceptionTypes()) { + if (BadRequestException.class.isAssignableFrom(execClass)) { + operation.addResponse("400", new RefResponse("400")); + } + if (NotFoundException.class.isAssignableFrom(execClass)) { + operation.addResponse("404", new RefResponse("404")); + } + if (NotImplementedException.class.isAssignableFrom(execClass)) { + operation.addResponse("501", new RefResponse("501")); + } + } + + Permission[] perms = method.getAnnotationsByType(Permission.class); + if (perms.length > 0) { + // Automatically add 401 & 403 as a possible response + operation.addResponse("401", new RefResponse("401")); + operation.addResponse("403", new RefResponse("403")); + + // Automatically add required permission notes if we have a @Permission annotation + Path path = method.getDeclaringClass().getAnnotation(Path.class); + String prefix = path != null ? path.value() + "." : ""; + + StringBuilder permStr = new StringBuilder(" \n\n **Required permissions:** \n\n"); + for (Permission perm : perms) { + permStr.append("- **").append(prefix).append(String.join(".", perm.value())).append("** \n"); + } + + operation.setDescription(operation.getDescription() + permStr.toString()); + + // Add security definitions + operation.addSecurity("ApiKeyHeader", new ArrayList<>()); + operation.addSecurity("ApiKeyQuery", new ArrayList<>()); + } + super.decorateOperation(operation, method, chain); + } +} diff --git a/src/main/java/valandur/webapi/swagger/SwaggerModelConverter.java b/webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerModelConverter.java similarity index 97% rename from src/main/java/valandur/webapi/swagger/SwaggerModelConverter.java rename to webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerModelConverter.java index ab7c6532..6555030c 100644 --- a/src/main/java/valandur/webapi/swagger/SwaggerModelConverter.java +++ b/webapi-sponge/src/main/java/valandur/webapi/swagger/SwaggerModelConverter.java @@ -1,104 +1,104 @@ -package valandur.webapi.swagger; - -import com.fasterxml.jackson.annotation.JsonValue; -import com.fasterxml.jackson.databind.type.SimpleType; -import io.swagger.converter.ModelConverter; -import io.swagger.converter.ModelConverterContext; -import io.swagger.models.Model; -import io.swagger.models.properties.Property; -import valandur.webapi.WebAPI; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Iterator; -import java.util.Optional; - -public class SwaggerModelConverter implements ModelConverter { - - @Override - public Property resolveProperty(Type type, ModelConverterContext context, - Annotation[] annotations, Iterator chain) { - if (chain.hasNext()) { - Class c = null; - if (type instanceof SimpleType) { - c = ((SimpleType) type).getRawClass(); - } else if (type instanceof Class) { - c = (Class) type; - } else if (type instanceof ParameterizedType) { - c = (Class) ((ParameterizedType)type).getRawType(); - } - - if (c != null) { - // Process @JsonValue annotation on field first if we have any - Optional optField = Arrays.stream(c.getFields()) - .filter(f -> f.getAnnotation(JsonValue.class) != null) - .findAny(); - if (optField.isPresent()) { - return resolveProperty(optField.get().getGenericType(), context, annotations, chain); - } - - // Process @JsonValue annotation on method first if we have any - Optional optMethod = Arrays.stream(c.getMethods()) - .filter(m -> m.getAnnotation(JsonValue.class) != null) - .findAny(); - if (optMethod.isPresent()) { - return resolveProperty(optMethod.get().getGenericReturnType(), context, annotations, chain); - } - - // If we can find a cache/view object for this type, then use that for documentation, - // because we can't annotate Sponge classes with @Swagger stuff - Optional optClass = WebAPI.getSerializeService().getViewFor(c); - if (optClass.isPresent()) { - return resolveProperty(optClass.get(), context, annotations, chain); - } - } - return chain.next().resolveProperty(type, context, annotations, chain); - } else { - return null; - } - } - - @Override - public Model resolve(Type type, ModelConverterContext context, Iterator chain) { - if (chain.hasNext()) { - Class c = null; - if (type instanceof SimpleType) { - c = ((SimpleType) type).getRawClass(); - } else if (type instanceof Class) { - c = (Class) type; - } - - if (c != null) { - // Process @JsonValue annotation on field first if we have any - Optional optField = Arrays.stream(c.getFields()) - .filter(f -> f.getAnnotation(JsonValue.class) != null) - .findAny(); - if (optField.isPresent()) { - return resolve(optField.get().getGenericType(), context, chain); - } - - // Process @JsonValue annotation on method first if we have any - Optional optMethod = Arrays.stream(c.getMethods()) - .filter(m -> m.getAnnotation(JsonValue.class) != null) - .findAny(); - if (optMethod.isPresent()) { - return resolve(optMethod.get().getGenericReturnType(), context, chain); - } - - // If we can find a cache/view object for this type, then use that for documentation, - // because we can't annotate Sponge classes with @Swagger stuff - Optional optClass = WebAPI.getSerializeService().getViewFor(c); - if (optClass.isPresent()) { - return resolve(optClass.get(), context, chain); - } - } - return chain.next().resolve(type, context, chain); - } else { - return null; - } - } -} +package valandur.webapi.swagger; + +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.type.SimpleType; +import io.swagger.converter.ModelConverter; +import io.swagger.converter.ModelConverterContext; +import io.swagger.models.Model; +import io.swagger.models.properties.Property; +import valandur.webapi.WebAPI; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Optional; + +public class SwaggerModelConverter implements ModelConverter { + + @Override + public Property resolveProperty(Type type, ModelConverterContext context, + Annotation[] annotations, Iterator chain) { + if (chain.hasNext()) { + Class c = null; + if (type instanceof SimpleType) { + c = ((SimpleType) type).getRawClass(); + } else if (type instanceof Class) { + c = (Class) type; + } else if (type instanceof ParameterizedType) { + c = (Class) ((ParameterizedType)type).getRawType(); + } + + if (c != null) { + // Process @JsonValue annotation on field first if we have any + Optional optField = Arrays.stream(c.getFields()) + .filter(f -> f.getAnnotation(JsonValue.class) != null) + .findAny(); + if (optField.isPresent()) { + return resolveProperty(optField.get().getGenericType(), context, annotations, chain); + } + + // Process @JsonValue annotation on method first if we have any + Optional optMethod = Arrays.stream(c.getMethods()) + .filter(m -> m.getAnnotation(JsonValue.class) != null) + .findAny(); + if (optMethod.isPresent()) { + return resolveProperty(optMethod.get().getGenericReturnType(), context, annotations, chain); + } + + // If we can find a cache/view object for this type, then use that for documentation, + // because we can't annotate Sponge classes with @Swagger stuff + Optional optClass = WebAPI.getSerializeService().getViewFor(c); + if (optClass.isPresent()) { + return resolveProperty(optClass.get(), context, annotations, chain); + } + } + return chain.next().resolveProperty(type, context, annotations, chain); + } else { + return null; + } + } + + @Override + public Model resolve(Type type, ModelConverterContext context, Iterator chain) { + if (chain.hasNext()) { + Class c = null; + if (type instanceof SimpleType) { + c = ((SimpleType) type).getRawClass(); + } else if (type instanceof Class) { + c = (Class) type; + } + + if (c != null) { + // Process @JsonValue annotation on field first if we have any + Optional optField = Arrays.stream(c.getFields()) + .filter(f -> f.getAnnotation(JsonValue.class) != null) + .findAny(); + if (optField.isPresent()) { + return resolve(optField.get().getGenericType(), context, chain); + } + + // Process @JsonValue annotation on method first if we have any + Optional optMethod = Arrays.stream(c.getMethods()) + .filter(m -> m.getAnnotation(JsonValue.class) != null) + .findAny(); + if (optMethod.isPresent()) { + return resolve(optMethod.get().getGenericReturnType(), context, chain); + } + + // If we can find a cache/view object for this type, then use that for documentation, + // because we can't annotate Sponge classes with @Swagger stuff + Optional optClass = WebAPI.getSerializeService().getViewFor(c); + if (optClass.isPresent()) { + return resolve(optClass.get(), context, chain); + } + } + return chain.next().resolve(type, context, chain); + } else { + return null; + } + } +} diff --git a/src/main/java/valandur/webapi/user/UserPermissionStruct.java b/webapi-sponge/src/main/java/valandur/webapi/user/UserPermissionStruct.java similarity index 100% rename from src/main/java/valandur/webapi/user/UserPermissionStruct.java rename to webapi-sponge/src/main/java/valandur/webapi/user/UserPermissionStruct.java diff --git a/src/main/java/valandur/webapi/user/UserPermissionStructSerializer.java b/webapi-sponge/src/main/java/valandur/webapi/user/UserPermissionStructSerializer.java similarity index 100% rename from src/main/java/valandur/webapi/user/UserPermissionStructSerializer.java rename to webapi-sponge/src/main/java/valandur/webapi/user/UserPermissionStructSerializer.java diff --git a/src/main/java/valandur/webapi/user/UserService.java b/webapi-sponge/src/main/java/valandur/webapi/user/UserService.java similarity index 96% rename from src/main/java/valandur/webapi/user/UserService.java rename to webapi-sponge/src/main/java/valandur/webapi/user/UserService.java index 5be22c99..cc26abea 100644 --- a/src/main/java/valandur/webapi/user/UserService.java +++ b/webapi-sponge/src/main/java/valandur/webapi/user/UserService.java @@ -1,94 +1,94 @@ -package valandur.webapi.user; - -import org.mindrot.jbcrypt.BCrypt; -import org.slf4j.Logger; -import valandur.webapi.WebAPI; -import valandur.webapi.config.BaseConfig; -import valandur.webapi.config.UserConfig; -import valandur.webapi.util.TreeNode; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -public class UserService { - private static final String configFileName = "user.conf"; - - private UserConfig config; - private Map users = new ConcurrentHashMap<>(); - public List getUsers() { - return new ArrayList<>(users.values()); - } - - public void init() { - Logger logger = WebAPI.getLogger(); - - logger.info("Loading users..."); - Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); - config = BaseConfig.load(configPath, new UserConfig()); - - users = config.users; - } - public void save() { - config.save(); - } - - public Optional getUser(String username) { - UserPermissionStruct user = users.get(username); - return user != null ? Optional.of(user) : Optional.empty(); - } - public Optional getUser(String username, String password) { - if (username == null || password == null || !users.containsKey(username)) { - return Optional.empty(); - } - - try { - UserPermissionStruct perm = users.get(username); - if (!BCrypt.checkpw(password, perm.getPassword())) { - return Optional.empty(); - } - - return Optional.of(perm); - } catch (IllegalArgumentException ignored) { - return Optional.empty(); - } - } - - public Optional addUser(String username, String password, TreeNode permissions) { - if (users.containsKey(username)) - return Optional.empty(); - - UserPermissionStruct user = new UserPermissionStruct(username, hashPassword(password), permissions); - users.put(username, user); - save(); - - return Optional.of(user); - } - public UserPermissionStruct modifyUser(UserPermissionStruct user, TreeNode permissions) { - UserPermissionStruct newUser = user.withPermissions(permissions); - users.put(newUser.getName(), newUser); - save(); - - WebAPI.getSecurityService().updateAllFrom(newUser); - - return newUser; - } - public Optional removeUser(String username) { - if (!users.containsKey(username)) - return Optional.empty(); - - UserPermissionStruct user = users.remove(username); - save(); - - WebAPI.getSecurityService().removeAllFrom(user.getName()); - - return Optional.of(user); - } - - public String hashPassword(String password) { - return BCrypt.hashpw(password, BCrypt.gensalt()); - } -} +package valandur.webapi.user; + +import org.mindrot.jbcrypt.BCrypt; +import org.slf4j.Logger; +import valandur.webapi.WebAPI; +import valandur.webapi.config.BaseConfig; +import valandur.webapi.config.UserConfig; +import valandur.webapi.util.TreeNode; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +public class UserService { + private static final String configFileName = "user.conf"; + + private UserConfig config; + private Map users = new ConcurrentHashMap<>(); + public List getUsers() { + return new ArrayList<>(users.values()); + } + + public void init() { + Logger logger = WebAPI.getLogger(); + + logger.info("Loading users..."); + Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); + config = BaseConfig.load(configPath, new UserConfig()); + + users = config.users; + } + public void save() { + config.save(); + } + + public Optional getUser(String username) { + UserPermissionStruct user = users.get(username); + return user != null ? Optional.of(user) : Optional.empty(); + } + public Optional getUser(String username, String password) { + if (username == null || password == null || !users.containsKey(username)) { + return Optional.empty(); + } + + try { + UserPermissionStruct perm = users.get(username); + if (!BCrypt.checkpw(password, perm.getPassword())) { + return Optional.empty(); + } + + return Optional.of(perm); + } catch (IllegalArgumentException ignored) { + return Optional.empty(); + } + } + + public Optional addUser(String username, String password, TreeNode permissions) { + if (users.containsKey(username)) + return Optional.empty(); + + UserPermissionStruct user = new UserPermissionStruct(username, hashPassword(password), permissions); + users.put(username, user); + save(); + + return Optional.of(user); + } + public UserPermissionStruct modifyUser(UserPermissionStruct user, TreeNode permissions) { + UserPermissionStruct newUser = user.withPermissions(permissions); + users.put(newUser.getName(), newUser); + save(); + + WebAPI.getSecurityService().updateAllFrom(newUser); + + return newUser; + } + public Optional removeUser(String username) { + if (!users.containsKey(username)) + return Optional.empty(); + + UserPermissionStruct user = users.remove(username); + save(); + + WebAPI.getSecurityService().removeAllFrom(user.getName()); + + return Optional.of(user); + } + + public String hashPassword(String password) { + return BCrypt.hashpw(password, BCrypt.gensalt()); + } +} diff --git a/src/main/java/valandur/webapi/util/Constants.java b/webapi-sponge/src/main/java/valandur/webapi/util/Constants.java similarity index 97% rename from src/main/java/valandur/webapi/util/Constants.java rename to webapi-sponge/src/main/java/valandur/webapi/util/Constants.java index 825e6fe0..7d92f0b8 100644 --- a/src/main/java/valandur/webapi/util/Constants.java +++ b/webapi-sponge/src/main/java/valandur/webapi/util/Constants.java @@ -1,12 +1,12 @@ -package valandur.webapi.util; - -public class Constants { - public static final String ID = "webapi"; - public static final String NAME = "Web-API"; - public static final String VERSION = "@version@"; - public static final String DESCRIPTION = "Access Minecraft through a RESTful web server and an admin panel"; - public static final String URL = "https://github.com/Valandur/Web-API"; - public static final String UPDATE_URL = "https://api.github.com/repos/Valandur/Web-API/releases/latest"; - - public static final String BASE_PATH = "/api/v5"; -} +package valandur.webapi.util; + +public class Constants { + public static final String ID = "webapi"; + public static final String NAME = "Web-API"; + public static final String VERSION = "@version@"; + public static final String DESCRIPTION = "Access Minecraft through a RESTful web server and an admin panel"; + public static final String URL = "https://github.com/Valandur/Web-API"; + public static final String UPDATE_URL = "https://api.github.com/repos/Valandur/Web-API/releases/latest"; + + public static final String BASE_PATH = "/api/v5"; +} diff --git a/src/main/java/valandur/webapi/util/JettyLogger.java b/webapi-sponge/src/main/java/valandur/webapi/util/JettyLogger.java similarity index 100% rename from src/main/java/valandur/webapi/util/JettyLogger.java rename to webapi-sponge/src/main/java/valandur/webapi/util/JettyLogger.java diff --git a/src/main/java/valandur/webapi/util/SubnetUtils.java b/webapi-sponge/src/main/java/valandur/webapi/util/SubnetUtils.java similarity index 97% rename from src/main/java/valandur/webapi/util/SubnetUtils.java rename to webapi-sponge/src/main/java/valandur/webapi/util/SubnetUtils.java index 4dac33bb..cd377338 100644 --- a/src/main/java/valandur/webapi/util/SubnetUtils.java +++ b/webapi-sponge/src/main/java/valandur/webapi/util/SubnetUtils.java @@ -1,357 +1,357 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package valandur.webapi.util; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class SubnetUtils { - - private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"; - private static final String SLASH_FORMAT = IP_ADDRESS + "/(\\d{1,2})"; // 0 -> 32 - private static final Pattern addressPattern = Pattern.compile(IP_ADDRESS); - private static final Pattern cidrPattern = Pattern.compile(SLASH_FORMAT); - private static final int NBITS = 32; - - private final int netmask; - private final int address; - private final int network; - private final int broadcast; - - /** Whether the broadcast/network address are included in host count */ - private boolean inclusiveHostCount = false; - - - /** - * Constructor that takes a CIDR-notation string, e.g. "192.168.0.1/16" - * @param cidrNotation A CIDR-notation string, e.g. "192.168.0.1/16" - * @throws IllegalArgumentException if the parameter is invalid, - * i.e. does not match n.n.n.n/m where n=1-3 decimal digits, m = 1-2 decimal digits in range 0-32 - */ - public SubnetUtils(String cidrNotation) { - Matcher matcher = cidrPattern.matcher(cidrNotation); - - if (matcher.matches()) { - this.address = matchAddress(matcher); - - /* Create a binary netmask from the number of bits specification /x */ - - int trailingZeroes = NBITS - rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS); - /* - * An IPv4 netmask consists of 32 bits, a contiguous sequence - * of the specified number of ones followed by all zeros. - * So, it can be obtained by shifting an unsigned integer (32 bits) to the left by - * the number of trailing zeros which is (32 - the # bits specification). - * Note that there is no unsigned left shift operator, so we have to use - * a long to ensure that the left-most bit is shifted out correctly. - */ - this.netmask = (int) (0x0FFFFFFFFL << trailingZeroes ); - - /* Calculate base network address */ - this.network = (address & netmask); - - /* Calculate broadcast address */ - this.broadcast = network | ~(netmask); - } else { - throw new IllegalArgumentException("Could not parse [" + cidrNotation + "]"); - } - } - - /** - * Constructor that takes a dotted decimal address and a dotted decimal mask. - * @param address An IP address, e.g. "192.168.0.1" - * @param mask A dotted decimal netmask e.g. "255.255.0.0" - * @throws IllegalArgumentException if the address or mask is invalid, - * i.e. does not match n.n.n.n where n=1-3 decimal digits and the mask is not all zeros - */ - public SubnetUtils(String address, String mask) { - this.address = toInteger(address); - this.netmask = toInteger(mask); - - if ((this.netmask & -this.netmask) - 1 != ~this.netmask) { - throw new IllegalArgumentException("Could not parse [" + mask + "]"); - } - - /* Calculate base network address */ - this.network = (this.address & this.netmask); - - /* Calculate broadcast address */ - this.broadcast = this.network | ~(this.netmask); - } - - - /** - * Returns true if the return value of {@link SubnetInfo#getAddressCount()} - * includes the network and broadcast addresses. - * @since 2.2 - * @return true if the host count includes the network and broadcast addresses - */ - public boolean isInclusiveHostCount() { - return inclusiveHostCount; - } - - /** - * Set to true if you want the return value of {@link SubnetInfo#getAddressCount()} - * to include the network and broadcast addresses. - * @param inclusiveHostCount true if network and broadcast addresses are to be included - * @since 2.2 - */ - public void setInclusiveHostCount(boolean inclusiveHostCount) { - this.inclusiveHostCount = inclusiveHostCount; - } - - - - /** - * Convenience container for subnet summary information. - * - */ - public final class SubnetInfo { - /* Mask to convert unsigned int to a long (i.e. keep 32 bits) */ - private static final long UNSIGNED_INT_MASK = 0x0FFFFFFFFL; - - private SubnetInfo() {} - - // long versions of the values (as unsigned int) which are more suitable for range checking - private long networkLong() { return network & UNSIGNED_INT_MASK; } - private long broadcastLong(){ return broadcast & UNSIGNED_INT_MASK; } - - private int low() { - return (isInclusiveHostCount() ? network : - broadcastLong() - networkLong() > 1 ? network + 1 : 0); - } - - private int high() { - return (isInclusiveHostCount() ? broadcast : - broadcastLong() - networkLong() > 1 ? broadcast -1 : 0); - } - - /** - * Returns true if the parameter address is in the - * range of usable endpoint addresses for this subnet. This excludes the - * network and broadcast addresses. - * @param address A dot-delimited IPv4 address, e.g. "192.168.0.1" - * @return True if in range, false otherwise - */ - public boolean isInRange(String address) { - return isInRange(toInteger(address)); - } - - /** - * Returns true if the parameter address is in the - * range of usable endpoint addresses for this subnet. This excludes the - * network and broadcast addresses. - * @param address the address to check - * @return true if it is in range - * @since 3.4 (made public) - */ - public boolean isInRange(int address) { - if (address == 0) { // cannot ever be in range; rejecting now avoids problems with CIDR/31,32 - return false; - } - long addLong = address & UNSIGNED_INT_MASK; - long lowLong = low() & UNSIGNED_INT_MASK; - long highLong = high() & UNSIGNED_INT_MASK; - return addLong >= lowLong && addLong <= highLong; - } - - public String getBroadcastAddress() { - return format(toArray(broadcast)); - } - - public String getNetworkAddress() { - return format(toArray(network)); - } - - public String getNetmask() { - return format(toArray(netmask)); - } - - public String getAddress() { - return format(toArray(address)); - } - - /** - * Return the low address as a dotted IP address. - * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. - * - * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address - */ - public String getLowAddress() { - return format(toArray(low())); - } - - /** - * Return the high address as a dotted IP address. - * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. - * - * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address - */ - public String getHighAddress() { - return format(toArray(high())); - } - - /** - * Get the count of available addresses. - * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. - * @return the count of addresses, may be zero. - * @throws RuntimeException if the correct count is greater than {@code Integer.MAX_VALUE} - * @deprecated (3.4) use {@link #getAddressCountLong()} instead - */ - @Deprecated - public int getAddressCount() { - long countLong = getAddressCountLong(); - if (countLong > Integer.MAX_VALUE) { - throw new RuntimeException("Count is larger than an integer: " + countLong); - } - // N.B. cannot be negative - return (int)countLong; - } - - /** - * Get the count of available addresses. - * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. - * @return the count of addresses, may be zero. - * @since 3.4 - */ - public long getAddressCountLong() { - long b = broadcastLong(); - long n = networkLong(); - long count = b - n + (isInclusiveHostCount() ? 1 : -1); - return count < 0 ? 0 : count; - } - - public int asInteger(String address) { - return toInteger(address); - } - - public String getCidrSignature() { - return format(toArray(address)) + "/" + pop(netmask); - } - - public String[] getAllAddresses() { - int ct = getAddressCount(); - String[] addresses = new String[ct]; - if (ct == 0) { - return addresses; - } - for (int add = low(), j=0; add <= high(); ++add, ++j) { - addresses[j] = format(toArray(add)); - } - return addresses; - } - - /** - * {@inheritDoc} - * @since 2.2 - */ - @Override - public String toString() { - final StringBuilder buf = new StringBuilder(); - buf.append("CIDR Signature:\t[").append(getCidrSignature()).append("]") - .append(" Netmask: [").append(getNetmask()).append("]\n") - .append("Network:\t[").append(getNetworkAddress()).append("]\n") - .append("Broadcast:\t[").append(getBroadcastAddress()).append("]\n") - .append("First Address:\t[").append(getLowAddress()).append("]\n") - .append("Last Address:\t[").append(getHighAddress()).append("]\n") - .append("# Addresses:\t[").append(getAddressCount()).append("]\n"); - return buf.toString(); - } - } - - /** - * Return a {@link SubnetInfo} instance that contains subnet-specific statistics - * @return new instance - */ - public final SubnetInfo getInfo() { return new SubnetInfo(); } - - /* - * Convert a dotted decimal format address to a packed integer format - */ - private static int toInteger(String address) { - Matcher matcher = addressPattern.matcher(address); - if (matcher.matches()) { - return matchAddress(matcher); - } else { - throw new IllegalArgumentException("Could not parse [" + address + "]"); - } - } - - /* - * Convenience method to extract the components of a dotted decimal address and - * pack into an integer using a regex match - */ - private static int matchAddress(Matcher matcher) { - int addr = 0; - for (int i = 1; i <= 4; ++i) { - int n = (rangeCheck(Integer.parseInt(matcher.group(i)), 0, 255)); - addr |= ((n & 0xff) << 8*(4-i)); - } - return addr; - } - - /* - * Convert a packed integer address into a 4-element array - */ - private int[] toArray(int val) { - int ret[] = new int[4]; - for (int j = 3; j >= 0; --j) { - ret[j] |= ((val >>> 8*(3-j)) & (0xff)); - } - return ret; - } - - /* - * Convert a 4-element array into dotted decimal format - */ - private String format(int[] octets) { - StringBuilder str = new StringBuilder(); - for (int i =0; i < octets.length; ++i){ - str.append(octets[i]); - if (i != octets.length - 1) { - str.append("."); - } - } - return str.toString(); - } - - /* - * Convenience function to check integer boundaries. - * Checks if a value x is in the range [begin,end]. - * Returns x if it is in range, throws an exception otherwise. - */ - private static int rangeCheck(int value, int begin, int end) { - if (value >= begin && value <= end) { // (begin,end] - return value; - } - - throw new IllegalArgumentException("Value [" + value + "] not in range ["+begin+","+end+"]"); - } - - /* - * Count the number of 1-bits in a 32-bit integer using a divide-and-conquer strategy - * see Hacker's Delight section 5.1 - */ - int pop(int x) { - x = x - ((x >>> 1) & 0x55555555); - x = (x & 0x33333333) + ((x >>> 2) & 0x33333333); - x = (x + (x >>> 4)) & 0x0F0F0F0F; - x = x + (x >>> 8); - x = x + (x >>> 16); - return x & 0x0000003F; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package valandur.webapi.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SubnetUtils { + + private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"; + private static final String SLASH_FORMAT = IP_ADDRESS + "/(\\d{1,2})"; // 0 -> 32 + private static final Pattern addressPattern = Pattern.compile(IP_ADDRESS); + private static final Pattern cidrPattern = Pattern.compile(SLASH_FORMAT); + private static final int NBITS = 32; + + private final int netmask; + private final int address; + private final int network; + private final int broadcast; + + /** Whether the broadcast/network address are included in host count */ + private boolean inclusiveHostCount = false; + + + /** + * Constructor that takes a CIDR-notation string, e.g. "192.168.0.1/16" + * @param cidrNotation A CIDR-notation string, e.g. "192.168.0.1/16" + * @throws IllegalArgumentException if the parameter is invalid, + * i.e. does not match n.n.n.n/m where n=1-3 decimal digits, m = 1-2 decimal digits in range 0-32 + */ + public SubnetUtils(String cidrNotation) { + Matcher matcher = cidrPattern.matcher(cidrNotation); + + if (matcher.matches()) { + this.address = matchAddress(matcher); + + /* Create a binary netmask from the number of bits specification /x */ + + int trailingZeroes = NBITS - rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS); + /* + * An IPv4 netmask consists of 32 bits, a contiguous sequence + * of the specified number of ones followed by all zeros. + * So, it can be obtained by shifting an unsigned integer (32 bits) to the left by + * the number of trailing zeros which is (32 - the # bits specification). + * Note that there is no unsigned left shift operator, so we have to use + * a long to ensure that the left-most bit is shifted out correctly. + */ + this.netmask = (int) (0x0FFFFFFFFL << trailingZeroes ); + + /* Calculate base network address */ + this.network = (address & netmask); + + /* Calculate broadcast address */ + this.broadcast = network | ~(netmask); + } else { + throw new IllegalArgumentException("Could not parse [" + cidrNotation + "]"); + } + } + + /** + * Constructor that takes a dotted decimal address and a dotted decimal mask. + * @param address An IP address, e.g. "192.168.0.1" + * @param mask A dotted decimal netmask e.g. "255.255.0.0" + * @throws IllegalArgumentException if the address or mask is invalid, + * i.e. does not match n.n.n.n where n=1-3 decimal digits and the mask is not all zeros + */ + public SubnetUtils(String address, String mask) { + this.address = toInteger(address); + this.netmask = toInteger(mask); + + if ((this.netmask & -this.netmask) - 1 != ~this.netmask) { + throw new IllegalArgumentException("Could not parse [" + mask + "]"); + } + + /* Calculate base network address */ + this.network = (this.address & this.netmask); + + /* Calculate broadcast address */ + this.broadcast = this.network | ~(this.netmask); + } + + + /** + * Returns true if the return value of {@link SubnetInfo#getAddressCount()} + * includes the network and broadcast addresses. + * @since 2.2 + * @return true if the host count includes the network and broadcast addresses + */ + public boolean isInclusiveHostCount() { + return inclusiveHostCount; + } + + /** + * Set to true if you want the return value of {@link SubnetInfo#getAddressCount()} + * to include the network and broadcast addresses. + * @param inclusiveHostCount true if network and broadcast addresses are to be included + * @since 2.2 + */ + public void setInclusiveHostCount(boolean inclusiveHostCount) { + this.inclusiveHostCount = inclusiveHostCount; + } + + + + /** + * Convenience container for subnet summary information. + * + */ + public final class SubnetInfo { + /* Mask to convert unsigned int to a long (i.e. keep 32 bits) */ + private static final long UNSIGNED_INT_MASK = 0x0FFFFFFFFL; + + private SubnetInfo() {} + + // long versions of the values (as unsigned int) which are more suitable for range checking + private long networkLong() { return network & UNSIGNED_INT_MASK; } + private long broadcastLong(){ return broadcast & UNSIGNED_INT_MASK; } + + private int low() { + return (isInclusiveHostCount() ? network : + broadcastLong() - networkLong() > 1 ? network + 1 : 0); + } + + private int high() { + return (isInclusiveHostCount() ? broadcast : + broadcastLong() - networkLong() > 1 ? broadcast -1 : 0); + } + + /** + * Returns true if the parameter address is in the + * range of usable endpoint addresses for this subnet. This excludes the + * network and broadcast addresses. + * @param address A dot-delimited IPv4 address, e.g. "192.168.0.1" + * @return True if in range, false otherwise + */ + public boolean isInRange(String address) { + return isInRange(toInteger(address)); + } + + /** + * Returns true if the parameter address is in the + * range of usable endpoint addresses for this subnet. This excludes the + * network and broadcast addresses. + * @param address the address to check + * @return true if it is in range + * @since 3.4 (made public) + */ + public boolean isInRange(int address) { + if (address == 0) { // cannot ever be in range; rejecting now avoids problems with CIDR/31,32 + return false; + } + long addLong = address & UNSIGNED_INT_MASK; + long lowLong = low() & UNSIGNED_INT_MASK; + long highLong = high() & UNSIGNED_INT_MASK; + return addLong >= lowLong && addLong <= highLong; + } + + public String getBroadcastAddress() { + return format(toArray(broadcast)); + } + + public String getNetworkAddress() { + return format(toArray(network)); + } + + public String getNetmask() { + return format(toArray(netmask)); + } + + public String getAddress() { + return format(toArray(address)); + } + + /** + * Return the low address as a dotted IP address. + * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. + * + * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address + */ + public String getLowAddress() { + return format(toArray(low())); + } + + /** + * Return the high address as a dotted IP address. + * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. + * + * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address + */ + public String getHighAddress() { + return format(toArray(high())); + } + + /** + * Get the count of available addresses. + * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. + * @return the count of addresses, may be zero. + * @throws RuntimeException if the correct count is greater than {@code Integer.MAX_VALUE} + * @deprecated (3.4) use {@link #getAddressCountLong()} instead + */ + @Deprecated + public int getAddressCount() { + long countLong = getAddressCountLong(); + if (countLong > Integer.MAX_VALUE) { + throw new RuntimeException("Count is larger than an integer: " + countLong); + } + // N.B. cannot be negative + return (int)countLong; + } + + /** + * Get the count of available addresses. + * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. + * @return the count of addresses, may be zero. + * @since 3.4 + */ + public long getAddressCountLong() { + long b = broadcastLong(); + long n = networkLong(); + long count = b - n + (isInclusiveHostCount() ? 1 : -1); + return count < 0 ? 0 : count; + } + + public int asInteger(String address) { + return toInteger(address); + } + + public String getCidrSignature() { + return format(toArray(address)) + "/" + pop(netmask); + } + + public String[] getAllAddresses() { + int ct = getAddressCount(); + String[] addresses = new String[ct]; + if (ct == 0) { + return addresses; + } + for (int add = low(), j=0; add <= high(); ++add, ++j) { + addresses[j] = format(toArray(add)); + } + return addresses; + } + + /** + * {@inheritDoc} + * @since 2.2 + */ + @Override + public String toString() { + final StringBuilder buf = new StringBuilder(); + buf.append("CIDR Signature:\t[").append(getCidrSignature()).append("]") + .append(" Netmask: [").append(getNetmask()).append("]\n") + .append("Network:\t[").append(getNetworkAddress()).append("]\n") + .append("Broadcast:\t[").append(getBroadcastAddress()).append("]\n") + .append("First Address:\t[").append(getLowAddress()).append("]\n") + .append("Last Address:\t[").append(getHighAddress()).append("]\n") + .append("# Addresses:\t[").append(getAddressCount()).append("]\n"); + return buf.toString(); + } + } + + /** + * Return a {@link SubnetInfo} instance that contains subnet-specific statistics + * @return new instance + */ + public final SubnetInfo getInfo() { return new SubnetInfo(); } + + /* + * Convert a dotted decimal format address to a packed integer format + */ + private static int toInteger(String address) { + Matcher matcher = addressPattern.matcher(address); + if (matcher.matches()) { + return matchAddress(matcher); + } else { + throw new IllegalArgumentException("Could not parse [" + address + "]"); + } + } + + /* + * Convenience method to extract the components of a dotted decimal address and + * pack into an integer using a regex match + */ + private static int matchAddress(Matcher matcher) { + int addr = 0; + for (int i = 1; i <= 4; ++i) { + int n = (rangeCheck(Integer.parseInt(matcher.group(i)), 0, 255)); + addr |= ((n & 0xff) << 8*(4-i)); + } + return addr; + } + + /* + * Convert a packed integer address into a 4-element array + */ + private int[] toArray(int val) { + int ret[] = new int[4]; + for (int j = 3; j >= 0; --j) { + ret[j] |= ((val >>> 8*(3-j)) & (0xff)); + } + return ret; + } + + /* + * Convert a 4-element array into dotted decimal format + */ + private String format(int[] octets) { + StringBuilder str = new StringBuilder(); + for (int i =0; i < octets.length; ++i){ + str.append(octets[i]); + if (i != octets.length - 1) { + str.append("."); + } + } + return str.toString(); + } + + /* + * Convenience function to check integer boundaries. + * Checks if a value x is in the range [begin,end]. + * Returns x if it is in range, throws an exception otherwise. + */ + private static int rangeCheck(int value, int begin, int end) { + if (value >= begin && value <= end) { // (begin,end] + return value; + } + + throw new IllegalArgumentException("Value [" + value + "] not in range ["+begin+","+end+"]"); + } + + /* + * Count the number of 1-bits in a 32-bit integer using a divide-and-conquer strategy + * see Hacker's Delight section 5.1 + */ + int pop(int x) { + x = x - ((x >>> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >>> 2) & 0x33333333); + x = (x + (x >>> 4)) & 0x0F0F0F0F; + x = x + (x >>> 8); + x = x + (x >>> 16); + return x & 0x0000003F; + } +} diff --git a/src/main/java/valandur/webapi/util/Timings.java b/webapi-sponge/src/main/java/valandur/webapi/util/Timings.java similarity index 97% rename from src/main/java/valandur/webapi/util/Timings.java rename to webapi-sponge/src/main/java/valandur/webapi/util/Timings.java index 1c689e13..eadfa19a 100644 --- a/src/main/java/valandur/webapi/util/Timings.java +++ b/webapi-sponge/src/main/java/valandur/webapi/util/Timings.java @@ -1,21 +1,21 @@ -package valandur.webapi.util; - -import co.aikar.timings.Timing; -import valandur.webapi.WebAPI; - -public class Timings { - public static final Timing RUN_ON_MAIN = - co.aikar.timings.Timings.of(WebAPI.getInstance(), "Run on main"); - public static final Timing STARTUP = - co.aikar.timings.Timings.of(WebAPI.getInstance(), "Startup"); - public static final Timing CACHE_WORLD = - co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache world"); - public static final Timing CACHE_PLAYER = - co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache player"); - public static final Timing CACHE_ENTITY = - co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache entity"); - public static final Timing CACHE_TILE_ENTITY = - co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache tile-entity"); - public static final Timing WEBHOOK_NOTIFY = - co.aikar.timings.Timings.of(WebAPI.getInstance(), "WebHook notify"); -} +package valandur.webapi.util; + +import co.aikar.timings.Timing; +import valandur.webapi.WebAPI; + +public class Timings { + public static final Timing RUN_ON_MAIN = + co.aikar.timings.Timings.of(WebAPI.getInstance(), "Run on main"); + public static final Timing STARTUP = + co.aikar.timings.Timings.of(WebAPI.getInstance(), "Startup"); + public static final Timing CACHE_WORLD = + co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache world"); + public static final Timing CACHE_PLAYER = + co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache player"); + public static final Timing CACHE_ENTITY = + co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache entity"); + public static final Timing CACHE_TILE_ENTITY = + co.aikar.timings.Timings.of(WebAPI.getInstance(), "Cache tile-entity"); + public static final Timing WEBHOOK_NOTIFY = + co.aikar.timings.Timings.of(WebAPI.getInstance(), "WebHook notify"); +} diff --git a/src/main/java/valandur/webapi/util/TreeNode.java b/webapi-sponge/src/main/java/valandur/webapi/util/TreeNode.java similarity index 96% rename from src/main/java/valandur/webapi/util/TreeNode.java rename to webapi-sponge/src/main/java/valandur/webapi/util/TreeNode.java index 21ee4d13..145f7248 100644 --- a/src/main/java/valandur/webapi/util/TreeNode.java +++ b/webapi-sponge/src/main/java/valandur/webapi/util/TreeNode.java @@ -1,217 +1,217 @@ -package valandur.webapi.util; - -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonValue; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Represents a tree structure where each node as a key and a value. - */ -public class TreeNode { - - private String key; - private boolean value; - - private TreeNode parent; - private Map children = new HashMap<>(); - - - /** - * Gets the key of the current node. - * @return The key of the current node. - */ - public String getKey() { - return key; - } - - /** - * Gets the value of the current node. - * @return The value of the current node. - */ - public boolean getValue() { - return value; - } - - - @JsonValue - public Object anyGetter() { - if (this.children.size() == 0) { - return this.value; - } else { - Map map = new HashMap<>(); - if (!this.value) { - map.put(".", false); - } - for (Map.Entry entry : children.entrySet()) { - map.put(entry.getKey(), entry.getValue()); - } - return map; - } - } - @JsonAnySetter - public void anySetter(String key, Object value) { - if (".".equalsIgnoreCase(key)) { - this.value = (boolean)value; - return; - } - - if (value instanceof Map) { - this.addChild(new TreeNode(key, (Map)value)); - } else { - this.addChild(new TreeNode(key, (boolean)value)); - } - } - - /** - * Gets the parent node of this node, or null if this node has no parent. - * @return The parent node of this node. Null if this node doesn't have a parent. - */ - @JsonIgnore - public TreeNode getParent() { - return parent; - } - - /** - * Gets the direct child of this node with the specified key - * @param key The key which identifies the child - * @return An optional containing the child with the specified key if it was found. - */ - public Optional getChild(String key) { - TreeNode child = children.get(key); - return child != null ? Optional.of(child) : Optional.empty(); - } - - /** - * Gets all direct children of the current node. - * @return A collection of all the children of this node. - */ - public Collection getChildren() { - return children.values(); - } - - /** - * Creates a new (root) node with null as the key and 'true' as the value. - */ - public TreeNode() { - this.value = true; - } - - /** - * Creates a new (root) node with null as the key and the specified value. - * @param value The value of this node. - */ - public TreeNode(boolean value) { - this.value = value; - } - - /** - * Creates a new node with the specified key and value. - * @param key The key of the new node. - * @param value The value of the new node. - */ - public TreeNode(String key, boolean value) { - this.key = key; - this.value = value; - } - - /** - * Creates a new node with the specified key and value. Also adds the node to the children of the specified parent. - * @param key The key of the new node. - * @param value The value of the new node. - * @param parent The parent node which this new node is attached to. - */ - public TreeNode(String key, boolean value, TreeNode parent) { - this(key, value); - setParent(parent); - } - - /** - * Creates a new node with the specified key and children. - * @param key The key of the new node. - * @param children A map of child nodes of this node. - */ - public TreeNode(String key, Map children) { - this.key = key; - this.value = true; - - for (Map.Entry entry : children.entrySet()) { - if (".".equalsIgnoreCase(entry.getKey())) { - this.value = (boolean)entry.getValue(); - continue; - } - - if (entry.getValue() instanceof Map) { - this.addChild(new TreeNode(entry.getKey(), (Map)entry.getValue())); - } else { - this.addChild(new TreeNode(entry.getKey(), (boolean)entry.getValue())); - } - } - } - - /** - * Sets the value of this node. - * @param value The new value of this node. - */ - public void setValue(boolean value) { - this.value = value; - } - - /** - * Sets the parent of this node. This registers this node in the list of children for the specified parent. - * It also removes this node from any previous parent. - * @param parent - */ - public void setParent(TreeNode parent) { - if (this.parent != null) { - this.parent.doRemoveChild(this); - } - - parent.doAddChild(this); - } - - /** - * Adds a new child node to this node. - * @param child The child to attach to this node. - * @return The child node. - */ - public TreeNode addChild(TreeNode child) { - return doAddChild(child); - } - private TreeNode doAddChild(TreeNode child) { - child.parent = this; - children.put(child.key, child); - return child; - } - - /** - * Removes the child with the specified key from the list of children. - * @param key The key which identifies the child. - * @return The child node. - */ - public TreeNode removeChild(String key) { - return doRemoveChild(children.get(key)); - } - - /** - * Removes the specified child from the list of children of this node. - * @param child The child to remove. - * @return The child node. - */ - public TreeNode removeChild(TreeNode child) { - return doRemoveChild(child); - } - private TreeNode doRemoveChild(TreeNode child) { - child.parent = null; - return children.remove(child.key); - } - - @Override - public String toString() { - return "[" + (key != null ? key : "") + ":" + value + "]"; - } -} +package valandur.webapi.util; + +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * Represents a tree structure where each node as a key and a value. + */ +public class TreeNode { + + private String key; + private boolean value; + + private TreeNode parent; + private Map children = new HashMap<>(); + + + /** + * Gets the key of the current node. + * @return The key of the current node. + */ + public String getKey() { + return key; + } + + /** + * Gets the value of the current node. + * @return The value of the current node. + */ + public boolean getValue() { + return value; + } + + + @JsonValue + public Object anyGetter() { + if (this.children.size() == 0) { + return this.value; + } else { + Map map = new HashMap<>(); + if (!this.value) { + map.put(".", false); + } + for (Map.Entry entry : children.entrySet()) { + map.put(entry.getKey(), entry.getValue()); + } + return map; + } + } + @JsonAnySetter + public void anySetter(String key, Object value) { + if (".".equalsIgnoreCase(key)) { + this.value = (boolean)value; + return; + } + + if (value instanceof Map) { + this.addChild(new TreeNode(key, (Map)value)); + } else { + this.addChild(new TreeNode(key, (boolean)value)); + } + } + + /** + * Gets the parent node of this node, or null if this node has no parent. + * @return The parent node of this node. Null if this node doesn't have a parent. + */ + @JsonIgnore + public TreeNode getParent() { + return parent; + } + + /** + * Gets the direct child of this node with the specified key + * @param key The key which identifies the child + * @return An optional containing the child with the specified key if it was found. + */ + public Optional getChild(String key) { + TreeNode child = children.get(key); + return child != null ? Optional.of(child) : Optional.empty(); + } + + /** + * Gets all direct children of the current node. + * @return A collection of all the children of this node. + */ + public Collection getChildren() { + return children.values(); + } + + /** + * Creates a new (root) node with null as the key and 'true' as the value. + */ + public TreeNode() { + this.value = true; + } + + /** + * Creates a new (root) node with null as the key and the specified value. + * @param value The value of this node. + */ + public TreeNode(boolean value) { + this.value = value; + } + + /** + * Creates a new node with the specified key and value. + * @param key The key of the new node. + * @param value The value of the new node. + */ + public TreeNode(String key, boolean value) { + this.key = key; + this.value = value; + } + + /** + * Creates a new node with the specified key and value. Also adds the node to the children of the specified parent. + * @param key The key of the new node. + * @param value The value of the new node. + * @param parent The parent node which this new node is attached to. + */ + public TreeNode(String key, boolean value, TreeNode parent) { + this(key, value); + setParent(parent); + } + + /** + * Creates a new node with the specified key and children. + * @param key The key of the new node. + * @param children A map of child nodes of this node. + */ + public TreeNode(String key, Map children) { + this.key = key; + this.value = true; + + for (Map.Entry entry : children.entrySet()) { + if (".".equalsIgnoreCase(entry.getKey())) { + this.value = (boolean)entry.getValue(); + continue; + } + + if (entry.getValue() instanceof Map) { + this.addChild(new TreeNode(entry.getKey(), (Map)entry.getValue())); + } else { + this.addChild(new TreeNode(entry.getKey(), (boolean)entry.getValue())); + } + } + } + + /** + * Sets the value of this node. + * @param value The new value of this node. + */ + public void setValue(boolean value) { + this.value = value; + } + + /** + * Sets the parent of this node. This registers this node in the list of children for the specified parent. + * It also removes this node from any previous parent. + * @param parent + */ + public void setParent(TreeNode parent) { + if (this.parent != null) { + this.parent.doRemoveChild(this); + } + + parent.doAddChild(this); + } + + /** + * Adds a new child node to this node. + * @param child The child to attach to this node. + * @return The child node. + */ + public TreeNode addChild(TreeNode child) { + return doAddChild(child); + } + private TreeNode doAddChild(TreeNode child) { + child.parent = this; + children.put(child.key, child); + return child; + } + + /** + * Removes the child with the specified key from the list of children. + * @param key The key which identifies the child. + * @return The child node. + */ + public TreeNode removeChild(String key) { + return doRemoveChild(children.get(key)); + } + + /** + * Removes the specified child from the list of children of this node. + * @param child The child to remove. + * @return The child node. + */ + public TreeNode removeChild(TreeNode child) { + return doRemoveChild(child); + } + private TreeNode doRemoveChild(TreeNode child) { + child.parent = null; + return children.remove(child.key); + } + + @Override + public String toString() { + return "[" + (key != null ? key : "") + ":" + value + "]"; + } +} diff --git a/src/main/resources/META-INF/services/io.swagger.jaxrs.ext.SwaggerExtension b/webapi-sponge/src/main/resources/META-INF/services/io.swagger.jaxrs.ext.SwaggerExtension similarity index 97% rename from src/main/resources/META-INF/services/io.swagger.jaxrs.ext.SwaggerExtension rename to webapi-sponge/src/main/resources/META-INF/services/io.swagger.jaxrs.ext.SwaggerExtension index 4f72218a..4df2a88c 100644 --- a/src/main/resources/META-INF/services/io.swagger.jaxrs.ext.SwaggerExtension +++ b/webapi-sponge/src/main/resources/META-INF/services/io.swagger.jaxrs.ext.SwaggerExtension @@ -1 +1 @@ -valandur.webapi.swagger.SwaggerExtension +valandur.webapi.swagger.SwaggerExtension diff --git a/src/main/resources/assets/webapi/admin/LICENSE b/webapi-sponge/src/main/resources/assets/webapi/admin/LICENSE similarity index 100% rename from src/main/resources/assets/webapi/admin/LICENSE rename to webapi-sponge/src/main/resources/assets/webapi/admin/LICENSE diff --git a/src/main/resources/assets/webapi/admin/asset-manifest.json b/webapi-sponge/src/main/resources/assets/webapi/admin/asset-manifest.json similarity index 100% rename from src/main/resources/assets/webapi/admin/asset-manifest.json rename to webapi-sponge/src/main/resources/assets/webapi/admin/asset-manifest.json diff --git a/src/main/resources/assets/webapi/admin/config.js b/webapi-sponge/src/main/resources/assets/webapi/admin/config.js similarity index 95% rename from src/main/resources/assets/webapi/admin/config.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/config.js index 8b8f63dc..61aa0a59 100644 --- a/src/main/resources/assets/webapi/admin/config.js +++ b/webapi-sponge/src/main/resources/assets/webapi/admin/config.js @@ -1,8 +1,8 @@ -window.config = { - "basePath": "/admin/", - "servers": [{ - "name": "Localhost", - "apiUrl": "http://localhost:8080", - "apiUrlHttps": "https://localhost:8081", - }] +window.config = { + "basePath": "/admin/", + "servers": [{ + "name": "Localhost", + "apiUrl": "http://localhost:8080", + "apiUrlHttps": "https://localhost:8081", + }] }; \ No newline at end of file diff --git a/src/main/resources/assets/webapi/admin/css/font-awesome.css b/webapi-sponge/src/main/resources/assets/webapi/admin/css/font-awesome.css similarity index 100% rename from src/main/resources/assets/webapi/admin/css/font-awesome.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/css/font-awesome.css diff --git a/src/main/resources/assets/webapi/admin/css/font-awesome.css.map b/webapi-sponge/src/main/resources/assets/webapi/admin/css/font-awesome.css.map similarity index 100% rename from src/main/resources/assets/webapi/admin/css/font-awesome.css.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/css/font-awesome.css.map diff --git a/src/main/resources/assets/webapi/admin/css/font-awesome.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/css/font-awesome.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/css/font-awesome.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/css/font-awesome.min.css diff --git a/src/main/resources/assets/webapi/admin/css/simple-line-icons.css b/webapi-sponge/src/main/resources/assets/webapi/admin/css/simple-line-icons.css similarity index 100% rename from src/main/resources/assets/webapi/admin/css/simple-line-icons.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/css/simple-line-icons.css diff --git a/src/main/resources/assets/webapi/admin/css/style.css b/webapi-sponge/src/main/resources/assets/webapi/admin/css/style.css similarity index 100% rename from src/main/resources/assets/webapi/admin/css/style.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/css/style.css diff --git a/src/main/resources/assets/webapi/admin/css/style.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/css/style.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/css/style.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/css/style.min.css diff --git a/src/main/resources/assets/webapi/admin/favicon.ico b/webapi-sponge/src/main/resources/assets/webapi/admin/favicon.ico similarity index 100% rename from src/main/resources/assets/webapi/admin/favicon.ico rename to webapi-sponge/src/main/resources/assets/webapi/admin/favicon.ico diff --git a/src/main/resources/assets/webapi/admin/fonts/FontAwesome.otf b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/FontAwesome.otf similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/FontAwesome.otf rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/FontAwesome.otf diff --git a/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.eot b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.eot similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.eot rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.eot diff --git a/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.svg b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.svg similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.svg rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.svg diff --git a/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.ttf b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.ttf similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.ttf rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.ttf diff --git a/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff diff --git a/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff2 b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff2 similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff2 rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/Simple-Line-Icons.woff2 diff --git a/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.eot b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.eot similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.eot rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.eot diff --git a/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.svg b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.svg similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.svg rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.svg diff --git a/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.ttf b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.ttf similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.ttf rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.ttf diff --git a/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff diff --git a/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff2 b/webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff2 similarity index 100% rename from src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff2 rename to webapi-sponge/src/main/resources/assets/webapi/admin/fonts/fontawesome-webfont.woff2 diff --git a/src/main/resources/assets/webapi/admin/index.html b/webapi-sponge/src/main/resources/assets/webapi/admin/index.html similarity index 100% rename from src/main/resources/assets/webapi/admin/index.html rename to webapi-sponge/src/main/resources/assets/webapi/admin/index.html diff --git a/src/main/resources/assets/webapi/admin/service-worker.js b/webapi-sponge/src/main/resources/assets/webapi/admin/service-worker.js similarity index 100% rename from src/main/resources/assets/webapi/admin/service-worker.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/service-worker.js diff --git a/src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css b/webapi-sponge/src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css similarity index 100% rename from src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css diff --git a/src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/css/main.6396af2e.css.map diff --git a/src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/0.81950f00.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/1.15e4bf86.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/10.b6be3827.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/11.e1b5e1af.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/12.9f94e989.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/13.5e988199.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/14.fa541889.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/15.ab1441fd.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/16.d9402ff1.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/17.517ad988.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/18.f07e3b4d.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/2.a6f4b259.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/3.5506694b.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/4.b5164743.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/5.61e8b96d.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/6.1d8a313a.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/7.18290c55.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/8.7349722f.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js diff --git a/src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/9.4ea8d425.chunk.js.map diff --git a/src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js diff --git a/src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js.map b/webapi-sponge/src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js.map similarity index 100% rename from src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js.map rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/js/main.915ae32e.js.map diff --git a/src/main/resources/assets/webapi/admin/static/media/jsoneditor-icons.d961fdfa.svg b/webapi-sponge/src/main/resources/assets/webapi/admin/static/media/jsoneditor-icons.d961fdfa.svg similarity index 100% rename from src/main/resources/assets/webapi/admin/static/media/jsoneditor-icons.d961fdfa.svg rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/media/jsoneditor-icons.d961fdfa.svg diff --git a/src/main/resources/assets/webapi/admin/static/media/logo.db6c2609.png b/webapi-sponge/src/main/resources/assets/webapi/admin/static/media/logo.db6c2609.png similarity index 100% rename from src/main/resources/assets/webapi/admin/static/media/logo.db6c2609.png rename to webapi-sponge/src/main/resources/assets/webapi/admin/static/media/logo.db6c2609.png diff --git a/src/main/resources/assets/webapi/admin/theme/LICENSE b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/LICENSE similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/LICENSE rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/LICENSE diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.cerulean.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.cerulean.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.cerulean.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.cerulean.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.cosmo.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.cosmo.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.cosmo.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.cosmo.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.cyborg.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.cyborg.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.cyborg.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.cyborg.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.darkly.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.darkly.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.darkly.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.darkly.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.default.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.default.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.default.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.default.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.flatly.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.flatly.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.flatly.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.flatly.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.journal.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.journal.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.journal.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.journal.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.lumen.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.lumen.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.lumen.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.lumen.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.paper.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.paper.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.paper.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.paper.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.readable.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.readable.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.readable.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.readable.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.sandstone.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.sandstone.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.sandstone.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.sandstone.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.simplex.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.simplex.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.simplex.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.simplex.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.slate.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.slate.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.slate.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.slate.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.solar.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.solar.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.solar.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.solar.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.spacelab.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.spacelab.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.spacelab.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.spacelab.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.superhero.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.superhero.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.superhero.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.superhero.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.united.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.united.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.united.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.united.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/semantic.yeti.min.css b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.yeti.min.css similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/semantic.yeti.min.css rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/semantic.yeti.min.css diff --git a/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.eot b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.eot similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.eot rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.eot diff --git a/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.svg b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.svg similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.svg rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.svg diff --git a/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.ttf b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.ttf similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.ttf rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.ttf diff --git a/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff diff --git a/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff2 b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff2 similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff2 rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/fonts/icons.woff2 diff --git a/src/main/resources/assets/webapi/admin/theme/themes/default/assets/images/flags.png b/webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/images/flags.png similarity index 100% rename from src/main/resources/assets/webapi/admin/theme/themes/default/assets/images/flags.png rename to webapi-sponge/src/main/resources/assets/webapi/admin/theme/themes/default/assets/images/flags.png diff --git a/src/main/resources/assets/webapi/keystore.jks b/webapi-sponge/src/main/resources/assets/webapi/keystore.jks similarity index 100% rename from src/main/resources/assets/webapi/keystore.jks rename to webapi-sponge/src/main/resources/assets/webapi/keystore.jks diff --git a/src/main/resources/assets/webapi/pages/redoc.html b/webapi-sponge/src/main/resources/assets/webapi/pages/redoc.html similarity index 96% rename from src/main/resources/assets/webapi/pages/redoc.html rename to webapi-sponge/src/main/resources/assets/webapi/pages/redoc.html index f890bbd1..91fa1454 100644 --- a/src/main/resources/assets/webapi/pages/redoc.html +++ b/webapi-sponge/src/main/resources/assets/webapi/pages/redoc.html @@ -1,17 +1,17 @@ - - - - WebAPI - ReDoc - - - - - - - - + + + + WebAPI - ReDoc + + + + + + + + diff --git a/src/main/resources/assets/webapi/swagger/config.json b/webapi-sponge/src/main/resources/assets/webapi/swagger/config.json similarity index 97% rename from src/main/resources/assets/webapi/swagger/config.json rename to webapi-sponge/src/main/resources/assets/webapi/swagger/config.json index cbcf1624..65678323 100644 --- a/src/main/resources/assets/webapi/swagger/config.json +++ b/webapi-sponge/src/main/resources/assets/webapi/swagger/config.json @@ -1,120 +1,120 @@ -{ - "resourcePackages": [ - "valandur.webapi" - ], - "prettyPrint" : true, - "openAPI": { - "info": { - "version": "1.0", - "title": "Web-API", - "description": "Access Sponge powered Minecraft servers through a WebAPI\n\n# Introduction\nThis is the documentation of the various API routes offered by the WebAPI plugin.\n\nThis documentation assumes that you are familiar with the basic concepts of Web API's, such as `GET`, `PUT`, `POST` and `DELETE` methods,\nrequest `HEADERS` and `RESPONSE CODES` and `JSON` data.\n\nBy default this documentation can be found at http:/localhost:8080 (while your minecraft server is running) and the various routes start with http:/localhost:8080/api/...\n\nAs a quick test try reaching the route http:/localhost:8080/api/info (remember that you can only access \"localhost\" routes on the server on which you are running minecraft).\nThis route should show you basic information about your server, like the motd and player count.\n\n# Additional data\nCertain endpoints (such as `/player`, `/entity` and `/tile-entity` have additional properties which are not documented here, because the data depends on the concrete\nobject type (eg. `Sheep` have a wool color, others do not) and on the other plugins/mods that are running on your server which might add additional data.\n\nYou can also find more information in the github docs (https:/github.com/Valandur/Web-API/tree/master/docs/DATA.md)", - "basePath": "/api", - "schemes": [ - "http", - "https" - ], - "produces": [ - "application/json", - "application/xml" - ], - "consumes": [ - "application/json", - "application/xml" - ], - "tags": [ - { - "name": "Block", - "description": "Get information about blocks and manipulate them." - }, - { - "name": "Chunk", - "description": "Gets information about chunks, and allow creating new chunks." - }, - { - "name": "Class", - "description": "Provides information about the classes loaded on the server." - }, - { - "name": "Command", - "description": "List all commands on the server and execute them." - }, - { - "name": "Entity", - "description": "List all entities and get detailed information about them." - }, - { - "name": "History", - "description": "Provides access to the command and chat history." - }, - { - "name": "Info", - "description": "Get information about the minecraft server" - }, - { - "name": "Message", - "description": "Send (interactive) messages to clients." - }, - { - "name": "Player", - "description": "List all players and get detailed information about them." - }, - { - "name": "Plugin", - "description": "List all plugins and get detailed information about them." - }, - { - "name": "Registry", - "description": "Query Sponge registry values, such as DimensionTypes and EntityTypes." - }, - { - "name": "Servlet", - "description": "Get information about the runnings servlets on the server." - }, - { - "name": "Tile Entity", - "description": "List all tile entities and get detailed information about them." - }, - { - "name": "User", - "description": "Authenticate and get user information." - }, - { - "name": "World", - "description": "List all worlds and get detailed information about them." - } - ], - "x-tagGroups": [ - { - "name": "WebAPI", - "tags": [ - "Block", - "Chunk", - "Class", - "Command", - "Entity", - "History", - "Info", - "Message", - "Player", - "Plugin", - "Registry", - "Servlet", - "Tile Entity", - "User", - "World" - ] - }, - { - "name": "Integrations", - "tags": [ - "Husky Crates", - "MMC Restrict", - "MMC Tickets", - "Nucleus", - "Web Books" - ] - } - ] - } - } -} +{ + "resourcePackages": [ + "valandur.webapi" + ], + "prettyPrint" : true, + "openAPI": { + "info": { + "version": "1.0", + "title": "Web-API", + "description": "Access Sponge powered Minecraft servers through a WebAPI\n\n# Introduction\nThis is the documentation of the various API routes offered by the WebAPI plugin.\n\nThis documentation assumes that you are familiar with the basic concepts of Web API's, such as `GET`, `PUT`, `POST` and `DELETE` methods,\nrequest `HEADERS` and `RESPONSE CODES` and `JSON` data.\n\nBy default this documentation can be found at http:/localhost:8080 (while your minecraft server is running) and the various routes start with http:/localhost:8080/api/...\n\nAs a quick test try reaching the route http:/localhost:8080/api/info (remember that you can only access \"localhost\" routes on the server on which you are running minecraft).\nThis route should show you basic information about your server, like the motd and player count.\n\n# Additional data\nCertain endpoints (such as `/player`, `/entity` and `/tile-entity` have additional properties which are not documented here, because the data depends on the concrete\nobject type (eg. `Sheep` have a wool color, others do not) and on the other plugins/mods that are running on your server which might add additional data.\n\nYou can also find more information in the github docs (https:/github.com/Valandur/Web-API/tree/master/docs/DATA.md)", + "basePath": "/api", + "schemes": [ + "http", + "https" + ], + "produces": [ + "application/json", + "application/xml" + ], + "consumes": [ + "application/json", + "application/xml" + ], + "tags": [ + { + "name": "Block", + "description": "Get information about blocks and manipulate them." + }, + { + "name": "Chunk", + "description": "Gets information about chunks, and allow creating new chunks." + }, + { + "name": "Class", + "description": "Provides information about the classes loaded on the server." + }, + { + "name": "Command", + "description": "List all commands on the server and execute them." + }, + { + "name": "Entity", + "description": "List all entities and get detailed information about them." + }, + { + "name": "History", + "description": "Provides access to the command and chat history." + }, + { + "name": "Info", + "description": "Get information about the minecraft server" + }, + { + "name": "Message", + "description": "Send (interactive) messages to clients." + }, + { + "name": "Player", + "description": "List all players and get detailed information about them." + }, + { + "name": "Plugin", + "description": "List all plugins and get detailed information about them." + }, + { + "name": "Registry", + "description": "Query Sponge registry values, such as DimensionTypes and EntityTypes." + }, + { + "name": "Servlet", + "description": "Get information about the runnings servlets on the server." + }, + { + "name": "Tile Entity", + "description": "List all tile entities and get detailed information about them." + }, + { + "name": "User", + "description": "Authenticate and get user information." + }, + { + "name": "World", + "description": "List all worlds and get detailed information about them." + } + ], + "x-tagGroups": [ + { + "name": "WebAPI", + "tags": [ + "Block", + "Chunk", + "Class", + "Command", + "Entity", + "History", + "Info", + "Message", + "Player", + "Plugin", + "Registry", + "Servlet", + "Tile Entity", + "User", + "World" + ] + }, + { + "name": "Integrations", + "tags": [ + "Husky Crates", + "MMC Restrict", + "MMC Tickets", + "Nucleus", + "Web Books" + ] + } + ] + } + } +}