Conform to google's checkstyle standard

This commit is contained in:
Frank van der Heijden 2020-06-27 01:28:10 +02:00
parent 3a52f9afa1
commit 83401bf622
No known key found for this signature in database
GPG key ID: 26DA56488D314D11
42 changed files with 1181 additions and 380 deletions

View file

@ -1,5 +1,6 @@
plugins { plugins {
id 'java' id 'java'
id 'checkstyle'
id 'com.github.johnrengelman.shadow' version '5.2.0' id 'com.github.johnrengelman.shadow' version '5.2.0'
} }
@ -39,4 +40,13 @@ shadowJar {
relocate 'org.bstats.bukkit', packagePath + '.dependencies.bstats' relocate 'org.bstats.bukkit', packagePath + '.dependencies.bstats'
} }
checkstyle {
toolVersion "8.25"
configFile = rootProject.file('config/checkstyle/checkstyle.xml')
ignoreFailures = false
maxErrors = 0
maxWarnings = 0
}
build.dependsOn shadowJar build.dependsOn shadowJar

View file

@ -0,0 +1,268 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!--
Checkstyle configuration that checks the Google coding conventions from Google Java Style
that can be found at https://google.github.io/styleguide/javaguide.html
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution).
To completely disable a check, just comment it out or delete it from the file.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name = "Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<!-- changed from 100 to 120, loosen a bit -->
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<!-- Disabled because it makes certain code pieces neater.
<module name="NeedBraces"/>
-->
<module name="LeftCurly"/>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE,
LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT,
INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapDot"/>
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapComma"/>
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/258 -->
<property name="id" value="SeparatorWrapEllipsis"/>
<property name="tokens" value="ELLIPSIS"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/259 -->
<property name="id" value="SeparatorWrapArrayDeclarator"/>
<property name="tokens" value="ARRAY_DECLARATOR"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapMethodRef"/>
<property name="tokens" value="METHOD_REF"/>
<property name="option" value="nl"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LambdaParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="4"/>
<property name="arrayInitIndent" value="4"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="separateLineBetweenGroups" value="true"/>
<property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/>
</module>
<module name="MethodParamPad"/>
<module name="NoWhitespaceBefore">
<property name="tokens"
value="COMMA, SEMI, POST_INC, POST_DEC, DOT, ELLIPSIS, METHOD_REF"/>
<property name="allowLineBreaks" value="true"/>
</module>
<module name="ParenPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR,
LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationMostCases"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationVariables"/>
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="InvalidJavadocPosition"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
</module>
<module name="MissingJavadocMethod">
<property name="scope" value="public"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation"/>
</module>
</module>

View file

@ -1,26 +1,32 @@
package net.frankheijden.serverutils; package net.frankheijden.serverutils;
import co.aikar.commands.BukkitCommandCompletionContext;
import co.aikar.commands.CommandCompletions;
import co.aikar.commands.PaperCommandManager; import co.aikar.commands.PaperCommandManager;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import net.frankheijden.serverutils.commands.CommandPlugins; import net.frankheijden.serverutils.commands.CommandPlugins;
import net.frankheijden.serverutils.commands.CommandServerUtils; import net.frankheijden.serverutils.commands.CommandServerUtils;
import net.frankheijden.serverutils.config.Config; import net.frankheijden.serverutils.config.Config;
import net.frankheijden.serverutils.config.Messenger; import net.frankheijden.serverutils.config.Messenger;
import net.frankheijden.serverutils.listeners.MainListener; import net.frankheijden.serverutils.listeners.MainListener;
import net.frankheijden.serverutils.managers.VersionManager; import net.frankheijden.serverutils.managers.VersionManager;
import net.frankheijden.serverutils.reflection.*; import net.frankheijden.serverutils.reflection.RCommandMap;
import net.frankheijden.serverutils.reflection.RCraftServer;
import net.frankheijden.serverutils.tasks.UpdateCheckerTask; import net.frankheijden.serverutils.tasks.UpdateCheckerTask;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.*; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.defaults.PluginsCommand; import org.bukkit.command.defaults.PluginsCommand;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;
public class ServerUtils extends JavaPlugin implements CommandExecutor { public class ServerUtils extends JavaPlugin implements CommandExecutor {
private static final int BSTATS_METRICS_ID = 7790; private static final int BSTATS_METRICS_ID = 7790;
@ -44,14 +50,11 @@ public class ServerUtils extends JavaPlugin implements CommandExecutor {
commandManager.registerCommand(new CommandServerUtils()); commandManager.registerCommand(new CommandServerUtils());
this.commandPlugins = null; this.commandPlugins = null;
commandManager.getCommandCompletions().registerAsyncCompletion("plugins", context -> Arrays.stream(Bukkit.getPluginManager().getPlugins()) CommandCompletions<BukkitCommandCompletionContext> completions = commandManager.getCommandCompletions();
.map(Plugin::getName) completions.registerAsyncCompletion("plugins", context -> getPluginNames());
.collect(Collectors.toList())); completions.registerAsyncCompletion("pluginJars", context -> getPluginFileNames());
commandManager.getCommandCompletions().registerAsyncCompletion("pluginJars", context -> Arrays.stream(getJars()) completions.registerAsyncCompletion("supportedConfigs", context -> CommandServerUtils.getSupportedConfigs());
.map(File::getName) completions.registerAsyncCompletion("commands", context -> {
.collect(Collectors.toList()));
commandManager.getCommandCompletions().registerAsyncCompletion("supportedConfigs", context -> CommandServerUtils.getSupportedConfigs());
commandManager.getCommandCompletions().registerAsyncCompletion("commands", context -> {
try { try {
return RCommandMap.getKnownCommands(RCraftServer.getCommandMap()).keySet(); return RCommandMap.getKnownCommands(RCraftServer.getCommandMap()).keySet();
} catch (IllegalAccessException | InvocationTargetException ex) { } catch (IllegalAccessException | InvocationTargetException ex) {
@ -73,6 +76,18 @@ public class ServerUtils extends JavaPlugin implements CommandExecutor {
restoreBukkitPluginCommand(); restoreBukkitPluginCommand();
} }
private List<String> getPluginNames() {
return Arrays.stream(Bukkit.getPluginManager().getPlugins())
.map(Plugin::getName)
.collect(Collectors.toList());
}
private List<String> getPluginFileNames() {
return Arrays.stream(getJars())
.map(File::getName)
.collect(Collectors.toList());
}
private void removeCommands(String... commands) { private void removeCommands(String... commands) {
Map<String, Command> map; Map<String, Command> map;
try { try {
@ -91,6 +106,10 @@ public class ServerUtils extends JavaPlugin implements CommandExecutor {
RCraftServer.getCommandMap().register("bukkit", new PluginsCommand("plugins")); RCraftServer.getCommandMap().register("bukkit", new PluginsCommand("plugins"));
} }
/**
* Reloads the configurations of the plugin.
* Also makes sure the bukkit /pl command gets restored.
*/
public void reload() { public void reload() {
if (commandPlugins != null) { if (commandPlugins != null) {
commandManager.unregisterCommand(commandPlugins); commandManager.unregisterCommand(commandPlugins);

View file

@ -1,7 +1,14 @@
package net.frankheijden.serverutils.commands; package net.frankheijden.serverutils.commands;
import co.aikar.commands.BaseCommand; import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*; import co.aikar.commands.annotation.CommandAlias;
import co.aikar.commands.annotation.CommandPermission;
import co.aikar.commands.annotation.Default;
import co.aikar.commands.annotation.Description;
import co.aikar.commands.annotation.Subcommand;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import net.frankheijden.serverutils.config.Messenger; import net.frankheijden.serverutils.config.Messenger;
import net.frankheijden.serverutils.utils.ListBuilder; import net.frankheijden.serverutils.utils.ListBuilder;
import net.frankheijden.serverutils.utils.ListFormat; import net.frankheijden.serverutils.utils.ListFormat;
@ -9,11 +16,13 @@ import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.util.*;
@CommandAlias("plugins|pl") @CommandAlias("plugins|pl")
public class CommandPlugins extends BaseCommand { public class CommandPlugins extends BaseCommand {
/**
* Sends the plugin list to the sender, without plugin version.
* @param sender The sender of the command.
*/
@Default @Default
@CommandPermission("serverutils.plugins") @CommandPermission("serverutils.plugins")
@Description("Shows the plugins of this server.") @Description("Shows the plugins of this server.")
@ -24,13 +33,18 @@ public class CommandPlugins extends BaseCommand {
}); });
} }
/**
* Sends the plugin list to the sender, with plugin version.
* @param sender The sender of the command.
*/
@Subcommand("-v") @Subcommand("-v")
@CommandPermission("serverutils.plugins.version") @CommandPermission("serverutils.plugins.version")
@Description("Shows the plugins of this server with version.") @Description("Shows the plugins of this server with version.")
public void onPluginsWithVersion(CommandSender sender) { public void onPluginsWithVersion(CommandSender sender) {
sendPlugins(sender, pl -> { sendPlugins(sender, pl -> {
String format = "serverutils.plugins.format" + (pl.isEnabled() ? "" : "_disabled"); String format = "serverutils.plugins.format" + (pl.isEnabled() ? "" : "_disabled");
String version = Messenger.getMessage("serverutils.plugins.version", "%version%", pl.getDescription().getVersion()); String version = Messenger.getMessage("serverutils.plugins.version",
"%version%", pl.getDescription().getVersion());
return Messenger.getMessage(format, "%plugin%", pl.getName()) + version; return Messenger.getMessage(format, "%plugin%", pl.getName()) + version;
}); });
} }

View file

@ -1,27 +1,46 @@
package net.frankheijden.serverutils.commands; package net.frankheijden.serverutils.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*;
import net.frankheijden.serverutils.ServerUtils;
import net.frankheijden.serverutils.config.Messenger;
import net.frankheijden.serverutils.managers.*;
import net.frankheijden.serverutils.reflection.*;
import net.frankheijden.serverutils.utils.*;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import java.util.*;
import static net.frankheijden.serverutils.config.Messenger.sendMessage; import static net.frankheijden.serverutils.config.Messenger.sendMessage;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MINOR; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MINOR;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.CommandAlias;
import co.aikar.commands.annotation.CommandCompletion;
import co.aikar.commands.annotation.CommandPermission;
import co.aikar.commands.annotation.Default;
import co.aikar.commands.annotation.Dependency;
import co.aikar.commands.annotation.Description;
import co.aikar.commands.annotation.Subcommand;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.frankheijden.serverutils.ServerUtils;
import net.frankheijden.serverutils.config.Messenger;
import net.frankheijden.serverutils.managers.LoadResult;
import net.frankheijden.serverutils.managers.PluginManager;
import net.frankheijden.serverutils.managers.Result;
import net.frankheijden.serverutils.reflection.RCraftServer;
import net.frankheijden.serverutils.utils.FormatBuilder;
import net.frankheijden.serverutils.utils.ForwardFilter;
import net.frankheijden.serverutils.utils.ListBuilder;
import net.frankheijden.serverutils.utils.ListFormat;
import net.frankheijden.serverutils.utils.ReloadHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginIdentifiableCommand;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
@CommandAlias("serverutils|su") @CommandAlias("serverutils|su")
public class CommandServerUtils extends BaseCommand { public class CommandServerUtils extends BaseCommand {
private static final Set<String> ALIASES; private static final Set<String> ALIASES;
private static final Map<String, ReloadHandler> supportedConfigs; private static final Map<String, ReloadHandler> supportedConfigs;
static { static {
ALIASES = new HashSet<>(); ALIASES = new HashSet<>();
ALIASES.add("serverutils"); ALIASES.add("serverutils");
@ -31,7 +50,7 @@ public class CommandServerUtils extends BaseCommand {
supportedConfigs.put("bukkit", RCraftServer::reloadBukkitConfiguration); supportedConfigs.put("bukkit", RCraftServer::reloadBukkitConfiguration);
supportedConfigs.put("commands.yml", RCraftServer::reloadCommandsConfiguration); supportedConfigs.put("commands.yml", RCraftServer::reloadCommandsConfiguration);
supportedConfigs.put("server-icon.png", RCraftServer::loadIcon); supportedConfigs.put("server-icon.png", RCraftServer::loadIcon);
supportedConfigs.put("banned-ips.json", RCraftServer::reloadIPBans); supportedConfigs.put("banned-ips.json", RCraftServer::reloadIpBans);
supportedConfigs.put("banned-players.json", RCraftServer::reloadProfileBans); supportedConfigs.put("banned-players.json", RCraftServer::reloadProfileBans);
} }
@ -42,6 +61,10 @@ public class CommandServerUtils extends BaseCommand {
return supportedConfigs.keySet(); return supportedConfigs.keySet();
} }
/**
* Shows the help page to the sender.
* @param sender The sender of the command.
*/
@Default @Default
@Subcommand("help") @Subcommand("help")
@CommandPermission("serverutils.help") @CommandPermission("serverutils.help")
@ -64,6 +87,10 @@ public class CommandServerUtils extends BaseCommand {
Messenger.sendMessage(sender, "serverutils.help.footer"); Messenger.sendMessage(sender, "serverutils.help.footer");
} }
/**
* Reloads the configurations of ServerUtils.
* @param sender The sender of the command.
*/
@Subcommand("reload") @Subcommand("reload")
@CommandPermission("serverutils.reload") @CommandPermission("serverutils.reload")
@Description("Reloads the ServerUtils plugin.") @Description("Reloads the ServerUtils plugin.")
@ -74,6 +101,11 @@ public class CommandServerUtils extends BaseCommand {
"%what%", "ServerUtils configurations"); "%what%", "ServerUtils configurations");
} }
/**
* Reloads a config from a set of configurations of the server.
* @param sender The sender of the command.
* @param config The configuration to reload.
*/
@Subcommand("reloadconfig") @Subcommand("reloadconfig")
@CommandCompletion("@supportedConfigs") @CommandCompletion("@supportedConfigs")
@CommandPermission("serverutils.reloadconfig") @CommandPermission("serverutils.reloadconfig")
@ -103,6 +135,11 @@ public class CommandServerUtils extends BaseCommand {
} }
} }
/**
* Loads the specified plugin on the server.
* @param sender The sender of the command.
* @param jarFile The filename of the plugin in the plugins/ directory.
*/
@Subcommand("loadplugin") @Subcommand("loadplugin")
@CommandCompletion("@pluginJars") @CommandCompletion("@pluginJars")
@CommandPermission("serverutils.loadplugin") @CommandPermission("serverutils.loadplugin")
@ -118,6 +155,11 @@ public class CommandServerUtils extends BaseCommand {
result.sendTo(sender, "load", jarFile); result.sendTo(sender, "load", jarFile);
} }
/**
* Unloads the specified plugin from the server.
* @param sender The sender of the command.
* @param pluginName The plugin name.
*/
@Subcommand("unloadplugin") @Subcommand("unloadplugin")
@CommandCompletion("@plugins") @CommandCompletion("@plugins")
@CommandPermission("serverutils.unloadplugin") @CommandPermission("serverutils.unloadplugin")
@ -133,6 +175,11 @@ public class CommandServerUtils extends BaseCommand {
unloadResult.sendTo(sender, "unload", pluginName); unloadResult.sendTo(sender, "unload", pluginName);
} }
/**
* Reloads the specified plugin on the server.
* @param sender The sender of the command.
* @param pluginName The plugin name.
*/
@Subcommand("reloadplugin") @Subcommand("reloadplugin")
@CommandCompletion("@plugins") @CommandCompletion("@plugins")
@CommandPermission("serverutils.reloadplugin") @CommandPermission("serverutils.reloadplugin")
@ -142,6 +189,11 @@ public class CommandServerUtils extends BaseCommand {
result.sendTo(sender, "reload", pluginName); result.sendTo(sender, "reload", pluginName);
} }
/**
* Enables the specified plugin on the server.
* @param sender The sender of the command.
* @param pluginName The plugin name.
*/
@Subcommand("enableplugin") @Subcommand("enableplugin")
@CommandCompletion("@plugins") @CommandCompletion("@plugins")
@CommandPermission("serverutils.enableplugin") @CommandPermission("serverutils.enableplugin")
@ -151,6 +203,11 @@ public class CommandServerUtils extends BaseCommand {
result.sendTo(sender, "enabl", pluginName); result.sendTo(sender, "enabl", pluginName);
} }
/**
* Disables the specified plugin on the server.
* @param sender The sender of the command.
* @param pluginName The plugin name.
*/
@Subcommand("disableplugin") @Subcommand("disableplugin")
@CommandCompletion("@plugins") @CommandCompletion("@plugins")
@CommandPermission("serverutils.disableplugin") @CommandPermission("serverutils.disableplugin")
@ -160,6 +217,11 @@ public class CommandServerUtils extends BaseCommand {
result.sendTo(sender, "disabl", pluginName); result.sendTo(sender, "disabl", pluginName);
} }
/**
* Shows information about the specified plugin.
* @param sender The sender of the command.
* @param pluginName The plugin name.
*/
@Subcommand("plugininfo") @Subcommand("plugininfo")
@CommandCompletion("@plugins") @CommandCompletion("@plugins")
@CommandPermission("serverutils.plugininfo") @CommandPermission("serverutils.plugininfo")
@ -186,7 +248,7 @@ public class CommandServerUtils extends BaseCommand {
.add("Name", plugin.getName()) .add("Name", plugin.getName())
.add("Full Name", description.getFullName()) .add("Full Name", description.getFullName())
.add("Version", description.getVersion()); .add("Version", description.getVersion());
if (MINOR >= 13) builder.add( "API Version", description.getAPIVersion()); if (MINOR >= 13) builder.add("API Version", description.getAPIVersion());
builder.add("Website", description.getWebsite()) builder.add("Website", description.getWebsite())
.add("Authors", ListBuilder.create(description.getAuthors()) .add("Authors", ListBuilder.create(description.getAuthors())
.format(listFormat) .format(listFormat)
@ -222,6 +284,11 @@ public class CommandServerUtils extends BaseCommand {
Messenger.sendMessage(sender, "serverutils.plugininfo.footer"); Messenger.sendMessage(sender, "serverutils.plugininfo.footer");
} }
/**
* Shows information about a provided command.
* @param sender The sender of the command.
* @param command The command to lookup.
*/
@Subcommand("commandinfo") @Subcommand("commandinfo")
@CommandCompletion("@commands") @CommandCompletion("@commands")
@CommandPermission("serverutils.commandinfo") @CommandPermission("serverutils.commandinfo")

View file

@ -1,39 +1,21 @@
package net.frankheijden.serverutils.config; package net.frankheijden.serverutils.config;
import net.frankheijden.serverutils.ServerUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
public class Config { public class Config extends YamlResource {
private static Defaults DEFAULT_CONFIG = Defaults.of(
"settings", Defaults.of(
"disable-plugins-command", false,
"check-updates", true,
"download-updates", false,
"download-at-startup-and-update", false
)
);
private static final ServerUtils plugin = ServerUtils.getInstance();
private static Config instance; private static Config instance;
private final YamlConfiguration config;
public Config(File file) { public Config(File file) {
super(file, "config.yml");
instance = this; instance = this;
config = Defaults.init(file, DEFAULT_CONFIG);
} }
public static Config getInstance() { public static Config getInstance() {
return instance; return instance;
} }
public YamlConfiguration getConfig() {
return config;
}
public boolean getBoolean(String path) { public boolean getBoolean(String path) {
return config.getBoolean(path, (boolean) DEFAULT_CONFIG.get(path)); return getConfiguration().getBoolean(path);
} }
} }

View file

@ -1,69 +0,0 @@
package net.frankheijden.serverutils.config;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
public class Defaults {
private final Map<String, Object> rootMap;
private Defaults(Object... objects) {
this.rootMap = new LinkedHashMap<>();
for (int i = 0; i < objects.length; i += 2) {
this.rootMap.put(String.valueOf(objects[i]), objects[i + 1]);
}
}
public static Defaults of(Object... objects) {
return new Defaults(objects);
}
public static void addDefaults(Defaults defaults, YamlConfiguration yml) {
addDefaults(defaults, yml, "");
}
private static void addDefaults(Defaults defaults, YamlConfiguration yml, String root) {
for (Map.Entry<String, Object> entry : defaults.rootMap.entrySet()) {
String key = (root.isEmpty() ? "" : root + ".") + entry.getKey();
Object value = entry.getValue();
if (value instanceof Defaults) {
addDefaults((Defaults) value, yml, key);
} else if (yml.get(key) == null) {
yml.set(key, value);
}
}
}
public Object get(String path) {
return get(this, path);
}
private Object get(Defaults defaults, String path) {
String[] split = path.split("\\.");
if (split.length > 1) {
return get((Defaults) defaults.rootMap.get(split[0]), path.substring(split[0].length() + 1));
}
return defaults.rootMap.get(split[0]);
}
public static YamlConfiguration init(File file, Defaults defaults) {
YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
Defaults.addDefaults(defaults, yml);
try {
// Idk somehow the order messes up
// of the messages if we don't do this
file.delete();
file.createNewFile();
yml.save(file);
} catch (IOException ex) {
ex.printStackTrace();
}
return yml;
}
}

View file

@ -1,88 +1,29 @@
package net.frankheijden.serverutils.config; package net.frankheijden.serverutils.config;
import java.io.File;
import net.frankheijden.serverutils.ServerUtils; import net.frankheijden.serverutils.ServerUtils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; public class Messenger extends YamlResource {
public class Messenger {
private static final Defaults DEFAULT_MESSAGES = Defaults.of(
"serverutils", Defaults.of(
"success", "&3Successfully %action%ed &b%what%&3!",
"warning", "&3Successfully %action%ed &b%what%&3, but with warnings.",
"error", "&cAn error occurred while %action%ing &4%what%&c, please check the console!",
"not_exists", "&cAn error occurred while %action%ing &4%what%&c, plugin does not exist!",
"not_enabled", "&cAn error occurred while %action%ing &4%what%&c, plugin is not enabled!",
"already_loaded", "&cAn error occurred while %action%ing &4%what%&c, plugin is already loaded!",
"already_enabled", "&cAn error occurred while %action%ing &4%what%&c, plugin is already enabled!",
"already_disabled", "&cAn error occurred while %action%ing &4%what%&c, plugin is already disabled!",
"file_changed", "&cAccessing the jar file while %action%ing &4%what%&c went wrong, please load the plugin manually!",
"invalid_description", "&cAn error occurred while %action%ing &4%what%&c, plugin doesn't have a valid description!",
"invalid_plugin", "&cAn error occurred while %action%ing &4%what%&c, plugin is invalid!",
"unknown_dependency", "&cAn error occurred while %action%ing &4%what%&c, plugin has a dependeny which is not loaded: &4%arg%",
"update", Defaults.of(
"available", "&8&m------------=&r&8[ &b&lServerUtils Update&r &8]&m=--------------\n"
+ " &3Current version: &b%old%\n"
+ " &3New version: &b%new%\n"
+ " &3Release info: &b%info%\n"
+ "&8&m-------------------------------------------------",
"downloading", "&8&m------------=&r&8[ &b&lServerUtils Update&r &8]&m=--------------\n"
+ " &3A new version of ServerUtils will be downloaded and installed after a restart!\n"
+ " &3Current version: &b%old%\n"
+ " &3New version: &b%new%\n"
+ " &3Release info: &b%info%\n"
+ "&8&m-------------------------------------------------",
"download_failed", "&cFailed to download version %new% of ServerUtils. Please update manually.",
"download_success", "&3ServerUtils has been downloaded and will be installed on the next restart."
),
"help", Defaults.of(
"header", "&8&m-------------=&r&8[ &b&lServerUtils Help&r &8]&m=---------------",
"format", "&8/&3%command%&b%subcommand% &f(&7%help%&f)",
"footer", "&8&m-------------------------------------------------"
),
"plugins", Defaults.of(
"header", "&8&m------------=&r&8[ &b&lServerUtils Plugins&r &8]&m=-------------",
"format", "&3%plugin%",
"format_disabled", "&c%plugin%",
"seperator", "&b, ",
"last_seperator", " &band ",
"version", " &8(&a%version%&8)",
"footer", "&8&m-------------------------------------------------"
),
"plugininfo", Defaults.of(
"header", "&8&m-----------=&r&8[ &b&lServerUtils PluginInfo&r &8]&m=-----------",
"format", " &3%key%&8: &b%value%",
"list_format", "&b%value%",
"seperator", "&8, ",
"last_seperator", " &8and ",
"footer", "&8&m-------------------------------------------------"
),
"commandinfo", Defaults.of(
"header", "&8&m-----------=&r&8[ &b&lServerUtils CommandInfo&r &8]&m=----------",
"format", " &3%key%&8: &b%value%",
"list_format", "&b%value%",
"seperator", "&8, ",
"last_seperator", " &8and ",
"footer", "&8&m-------------------------------------------------",
"not_exists", "&cThat command is not a valid registered command."
)
)
);
private static final ServerUtils plugin = ServerUtils.getInstance(); private static final ServerUtils plugin = ServerUtils.getInstance();
private static Messenger instance; private static Messenger instance;
private final YamlConfiguration messages;
public Messenger(File file) { public Messenger(File file) {
super(file, "messages.yml");
instance = this; instance = this;
messages = Defaults.init(file, DEFAULT_MESSAGES);
} }
/**
* Retrieves a message from the config.
* @param path The yml path to the message.
* @param replacements The replacements to be taken into account.
* @return The config message with translated placeholders.
*/
public static String getMessage(String path, String... replacements) { public static String getMessage(String path, String... replacements) {
String message = instance.messages.getString(path); String message = instance.getConfiguration().getString(path);
if (message != null) { if (message != null) {
return apply(message, replacements); return apply(message, replacements);
} else { } else {
@ -91,6 +32,13 @@ public class Messenger {
return null; return null;
} }
/**
* Applies placeholders to a message.
* @param message The message.
* @param replacements The replacements of the message. Expects input to be even and in a key-value like format.
* Example: ["%player%", "Player"]
* @return The message with translated placeholders.
*/
public static String apply(String message, String... replacements) { public static String apply(String message, String... replacements) {
if (message == null || message.isEmpty()) return null; if (message == null || message.isEmpty()) return null;
for (int i = 0; i < replacements.length; i++, i++) { for (int i = 0; i < replacements.length; i++, i++) {
@ -99,6 +47,12 @@ public class Messenger {
return message; return message;
} }
/**
* Sends a message to a player with translated placeholders.
* @param sender The receiver.
* @param msg The message to be sent.
* @param replacements The replacements to be taken into account.
*/
public static void sendRawMessage(CommandSender sender, String msg, String... replacements) { public static void sendRawMessage(CommandSender sender, String msg, String... replacements) {
String message = apply(msg, replacements); String message = apply(msg, replacements);
if (message != null) { if (message != null) {
@ -106,6 +60,12 @@ public class Messenger {
} }
} }
/**
* Sends a message from the specified config path to a player with translated placeholders.
* @param sender The receiver.
* @param path The yml path to the message.
* @param replacements The replacements to be taken into account.
*/
public static void sendMessage(CommandSender sender, String path, String... replacements) { public static void sendMessage(CommandSender sender, String path, String... replacements) {
String message = getMessage(path, replacements); String message = getMessage(path, replacements);
if (message != null) { if (message != null) {

View file

@ -0,0 +1,32 @@
package net.frankheijden.serverutils.config;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import net.frankheijden.serverutils.ServerUtils;
import net.frankheijden.serverutils.utils.YamlUtils;
import org.bukkit.configuration.file.YamlConfiguration;
public abstract class YamlResource {
private static final ServerUtils plugin = ServerUtils.getInstance();
private final YamlConfiguration configuration;
/**
* Creates a new YamlResource instance.
* Loads the resource from the jar file.
* @param file The destination file.
* @param resource The resource from the jar file.
*/
public YamlResource(File file, String resource) {
InputStream is = plugin.getResource(resource);
YamlConfiguration def = YamlConfiguration.loadConfiguration(new InputStreamReader(is));
configuration = YamlUtils.init(file, def);
}
public YamlConfiguration getConfiguration() {
return configuration;
}
}

View file

@ -3,13 +3,20 @@ package net.frankheijden.serverutils.listeners;
import net.frankheijden.serverutils.config.Config; import net.frankheijden.serverutils.config.Config;
import net.frankheijden.serverutils.tasks.UpdateCheckerTask; import net.frankheijden.serverutils.tasks.UpdateCheckerTask;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.*; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
public class MainListener implements Listener { public class MainListener implements Listener {
private static final Config config = Config.getInstance(); private static final Config config = Config.getInstance();
/**
* Called when a player joins the server.
* Used for sending an update message to the player, if enabled and has permission.
* @param event The PlayerJoinEvent.
*/
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
if (!config.getBoolean("settings.check-updates")) return; if (!config.getBoolean("settings.check-updates")) return;

View file

@ -1,23 +1,45 @@
package net.frankheijden.serverutils.managers; package net.frankheijden.serverutils.managers;
import net.frankheijden.serverutils.ServerUtils;
import net.frankheijden.serverutils.reflection.*;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.plugin.*;
import java.io.File; import java.io.File;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import net.frankheijden.serverutils.ServerUtils;
import net.frankheijden.serverutils.reflection.RCommandMap;
import net.frankheijden.serverutils.reflection.RCraftServer;
import net.frankheijden.serverutils.reflection.RCraftingManager;
import net.frankheijden.serverutils.reflection.RJavaPlugin;
import net.frankheijden.serverutils.reflection.RPlugin;
import net.frankheijden.serverutils.reflection.RPluginClassLoader;
import net.frankheijden.serverutils.reflection.RSimplePluginManager;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.UnknownDependencyException;
public class PluginManager { public class PluginManager {
/**
* Loads the specified file as a plugin.
* @param jarFile The name of the file in the plugins/ folder.
* @return The result of the loading procedure.
*/
public static LoadResult loadPlugin(String jarFile) { public static LoadResult loadPlugin(String jarFile) {
return loadPlugin(new File(ServerUtils.getInstance().getDataFolder().getParent(), jarFile)); return loadPlugin(new File(ServerUtils.getInstance().getDataFolder().getParent(), jarFile));
} }
/**
* Loads the specified file as a plugin.
* @param file The file to be loaded.
* @return The result of the loading procedure.
*/
public static LoadResult loadPlugin(File file) { public static LoadResult loadPlugin(File file) {
if (!file.exists()) return new LoadResult(Result.NOT_EXISTS); if (!file.exists()) return new LoadResult(Result.NOT_EXISTS);
@ -47,10 +69,20 @@ public class PluginManager {
return new LoadResult(plugin); return new LoadResult(plugin);
} }
/**
* Disables the specified plugin by name and cleans all commands and recipes of the plugin.
* @param pluginName The plugin to disable.
* @return The result of the disable call.
*/
public static Result disablePlugin(String pluginName) { public static Result disablePlugin(String pluginName) {
return disablePlugin(Bukkit.getPluginManager().getPlugin(pluginName)); return disablePlugin(Bukkit.getPluginManager().getPlugin(pluginName));
} }
/**
* Disables the specified plugin and cleans all commands and recipes of the plugin.
* @param plugin The plugin to disable.
* @return The result of the disable call.
*/
public static Result disablePlugin(Plugin plugin) { public static Result disablePlugin(Plugin plugin) {
if (plugin == null) return Result.NOT_ENABLED; if (plugin == null) return Result.NOT_ENABLED;
if (!plugin.isEnabled()) return Result.ALREADY_DISABLED; if (!plugin.isEnabled()) return Result.ALREADY_DISABLED;
@ -65,10 +97,20 @@ public class PluginManager {
return Result.SUCCESS; return Result.SUCCESS;
} }
/**
* Unloads the specified plugin by name and cleans all traces within bukkit.
* @param pluginName The plugin to unload.
* @return The result of the unload.
*/
public static Result unloadPlugin(String pluginName) { public static Result unloadPlugin(String pluginName) {
return unloadPlugin(Bukkit.getPluginManager().getPlugin(pluginName)); return unloadPlugin(Bukkit.getPluginManager().getPlugin(pluginName));
} }
/**
* Unloads the specified plugin and cleans all traces within bukkit.
* @param plugin The plugin to unload.
* @return The result of the unload.
*/
public static Result unloadPlugin(Plugin plugin) { public static Result unloadPlugin(Plugin plugin) {
if (plugin == null) return Result.NOT_EXISTS; if (plugin == null) return Result.NOT_EXISTS;
try { try {
@ -82,10 +124,20 @@ public class PluginManager {
return Result.SUCCESS; return Result.SUCCESS;
} }
/**
* Enables the specified plugin by name.
* @param pluginName The plugin to enable.
* @return The result of the enabling.
*/
public static Result enablePlugin(String pluginName) { public static Result enablePlugin(String pluginName) {
return enablePlugin(Bukkit.getPluginManager().getPlugin(pluginName)); return enablePlugin(Bukkit.getPluginManager().getPlugin(pluginName));
} }
/**
* Enables the specified plugin.
* @param plugin The plugin to enable.
* @return The result of the enabling.
*/
public static Result enablePlugin(Plugin plugin) { public static Result enablePlugin(Plugin plugin) {
if (plugin == null) return Result.NOT_EXISTS; if (plugin == null) return Result.NOT_EXISTS;
if (Bukkit.getPluginManager().isPluginEnabled(plugin.getName())) return Result.ALREADY_ENABLED; if (Bukkit.getPluginManager().isPluginEnabled(plugin.getName())) return Result.ALREADY_ENABLED;
@ -96,12 +148,22 @@ public class PluginManager {
return Result.ERROR; return Result.ERROR;
} }
/**
* Reloads the specified plugin by name.
* @param pluginName The plugin to reload.
* @return The result of the reload.
*/
public static Result reloadPlugin(String pluginName) { public static Result reloadPlugin(String pluginName) {
Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName); Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (plugin == null) return Result.NOT_EXISTS; if (plugin == null) return Result.NOT_EXISTS;
return reloadPlugin(plugin); return reloadPlugin(plugin);
} }
/**
* Reloads the specified plugin.
* @param plugin The plugin to reload.
* @return The result of the reload.
*/
public static Result reloadPlugin(Plugin plugin) { public static Result reloadPlugin(Plugin plugin) {
Result disableResult = disablePlugin(plugin); Result disableResult = disablePlugin(plugin);
if (disableResult != Result.SUCCESS && disableResult != Result.ALREADY_DISABLED) return disableResult; if (disableResult != Result.SUCCESS && disableResult != Result.ALREADY_DISABLED) return disableResult;
@ -125,6 +187,10 @@ public class PluginManager {
return enablePlugin(loadResult.getPlugin()); return enablePlugin(loadResult.getPlugin());
} }
/**
* Retrieves all known commands registered to bukkit.
* @return A map with all known commands.
*/
public static Map<String, Command> getKnownCommands() { public static Map<String, Command> getKnownCommands() {
try { try {
return RCommandMap.getKnownCommands(RCraftServer.getCommandMap()); return RCommandMap.getKnownCommands(RCraftServer.getCommandMap());
@ -134,6 +200,10 @@ public class PluginManager {
} }
} }
/**
* Unregisters all commands from the specified plugin.
* @param plugin The plugin.
*/
public static void unregisterCommands(Plugin plugin) { public static void unregisterCommands(Plugin plugin) {
Map<String, Command> knownCommands = getKnownCommands(); Map<String, Command> knownCommands = getKnownCommands();
if (knownCommands == null) return; if (knownCommands == null) return;
@ -151,12 +221,21 @@ public class PluginManager {
}); });
} }
/**
* Retrieves a command from the command map.
* @param command The command string.
* @return The command.
*/
public static Command getCommand(String command) { public static Command getCommand(String command) {
Map<String, Command> knownCommands = getKnownCommands(); Map<String, Command> knownCommands = getKnownCommands();
if (knownCommands == null) return null; if (knownCommands == null) return null;
return knownCommands.get(command); return knownCommands.get(command);
} }
/**
* Retrieves all file associations, i.e. all plugin loaders.
* @return A map with all pluginloaders.
*/
public static Map<Pattern, PluginLoader> getFileAssociations() { public static Map<Pattern, PluginLoader> getFileAssociations() {
try { try {
return RSimplePluginManager.getFileAssociations(Bukkit.getPluginManager()); return RSimplePluginManager.getFileAssociations(Bukkit.getPluginManager());
@ -166,6 +245,11 @@ public class PluginManager {
} }
} }
/**
* Retrieves the PluginLoader for the input file.
* @param file The file.
* @return The appropiate PluginLoader.
*/
public static PluginLoader getPluginLoader(File file) { public static PluginLoader getPluginLoader(File file) {
Map<Pattern, PluginLoader> fileAssociations = getFileAssociations(); Map<Pattern, PluginLoader> fileAssociations = getFileAssociations();
if (fileAssociations == null) return null; if (fileAssociations == null) return null;
@ -179,6 +263,11 @@ public class PluginManager {
return null; return null;
} }
/**
* Retrieves a loaded plugin associated to a jar file.
* @param file The jar file.
* @return The already loaded plugin, or null if none.
*/
public static Plugin getLoadedPlugin(File file) { public static Plugin getLoadedPlugin(File file) {
PluginDescriptionFile descriptionFile; PluginDescriptionFile descriptionFile;
try { try {
@ -190,6 +279,12 @@ public class PluginManager {
return Bukkit.getPluginManager().getPlugin(descriptionFile.getName()); return Bukkit.getPluginManager().getPlugin(descriptionFile.getName());
} }
/**
* Retrieves the PluginDescriptionFile of a jar file.
* @param file The jar file.
* @return The PluginDescriptionFile.
* @throws InvalidDescriptionException Iff the PluginDescriptionFile is invalid.
*/
public static PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException { public static PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException {
PluginLoader loader = getPluginLoader(file); PluginLoader loader = getPluginLoader(file);
if (loader == null) return null; if (loader == null) return null;

View file

@ -27,6 +27,13 @@ public enum Result {
return this; return this;
} }
/**
* Retrieves the associated message of the result
* and sends it to a CommandSender.
* @param sender The receiver.
* @param action The action which let to the result.
* @param what An associated variable.
*/
public void sendTo(CommandSender sender, String action, String what) { public void sendTo(CommandSender sender, String action, String what) {
Messenger.sendMessage(sender, "serverutils." + this.name().toLowerCase(), Messenger.sendMessage(sender, "serverutils." + this.name().toLowerCase(),
"%action%", action, "%action%", action,

View file

@ -9,6 +9,10 @@ public class VersionManager {
private final String currentVersion; private final String currentVersion;
private String downloadedVersion; private String downloadedVersion;
/**
* Creates a new VersionManager instance.
* Used for automatic updating.
*/
public VersionManager() { public VersionManager() {
instance = this; instance = this;
this.currentVersion = plugin.getDescription().getVersion(); this.currentVersion = plugin.getDescription().getVersion();

View file

@ -1,17 +1,20 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getDeclaredField;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.SimpleCommandMap; import org.bukkit.command.SimpleCommandMap;
import java.lang.reflect.*;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getDeclaredField;
public class RCommandMap { public class RCommandMap {
private static Field knownCommands = null; private static Field knownCommands = null;
private static Method getKnownCommands = null; private static Method getKnownCommands = null;
static { static {
try { try {
try { try {
@ -25,7 +28,8 @@ public class RCommandMap {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static Map<String, Command> getKnownCommands(SimpleCommandMap map) throws IllegalAccessException, InvocationTargetException { public static Map<String, Command> getKnownCommands(SimpleCommandMap map)
throws IllegalAccessException, InvocationTargetException {
return (Map<String, Command>) (knownCommands == null ? getKnownCommands.invoke(map) : knownCommands.get(map)); return (Map<String, Command>) (knownCommands == null ? getKnownCommands.invoke(map) : knownCommands.get(map));
} }
} }

View file

@ -1,19 +1,31 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.max;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.min;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.versionOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getDeclaredField;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getDeclaredMethod;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.invoke;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.set;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Warning; import org.bukkit.Warning;
import org.bukkit.command.*; import org.bukkit.command.Command;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.lang.reflect.*;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.*;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.*;
public class RCraftServer { public class RCraftServer {
private static Class<?> craftServerClass; private static Class<?> craftServerClass;
@ -27,10 +39,12 @@ public class RCraftServer {
static { static {
try { try {
craftServerClass = Class.forName(String.format("org.bukkit.craftbukkit.%s.CraftServer", ReflectionUtils.NMS)); craftServerClass = Class.forName(String.format("org.bukkit.craftbukkit.%s.CraftServer",
ReflectionUtils.NMS));
craftServer = craftServerClass.cast(Bukkit.getServer()); craftServer = craftServerClass.cast(Bukkit.getServer());
commandsConfigFile = (File) getDeclaredMethod(craftServerClass, "getCommandsConfigFile").invoke(craftServer); commandsConfigFile = (File) getDeclaredMethod(craftServerClass,
"getCommandsConfigFile").invoke(craftServer);
configFile = (File) getDeclaredMethod(craftServerClass, "getConfigFile").invoke(craftServer); configFile = (File) getDeclaredMethod(craftServerClass, "getConfigFile").invoke(craftServer);
commandMap = (SimpleCommandMap) getDeclaredField(craftServerClass, "commandMap").get(Bukkit.getServer()); commandMap = (SimpleCommandMap) getDeclaredField(craftServerClass, "commandMap").get(Bukkit.getServer());
@ -66,6 +80,13 @@ public class RCraftServer {
return configFile; return configFile;
} }
/**
* Retrieves the options file from a key.
* @param option The option key.
* @return The associated file.
* @throws InvocationTargetException If the method call produced an exception.
* @throws IllegalAccessException When prohibited access to the method.
*/
public static File getOptionsFile(String option) throws IllegalAccessException, InvocationTargetException { public static File getOptionsFile(String option) throws IllegalAccessException, InvocationTargetException {
Object console = get(fields, craftServer, "console"); Object console = get(fields, craftServer, "console");
Object options = get(RDedicatedServer.getFields(), console, "options"); Object options = get(RDedicatedServer.getFields(), console, "options");
@ -80,7 +101,11 @@ public class RCraftServer {
return commandMap; return commandMap;
} }
public static void reloadBukkitConfiguration() throws Exception { /**
* Reloads the bukkit configuration.
* @throws ReflectiveOperationException Iff exception thrown regarding reflection.
*/
public static void reloadBukkitConfiguration() throws ReflectiveOperationException {
YamlConfiguration bukkit = YamlConfiguration.loadConfiguration(getConfigFile()); YamlConfiguration bukkit = YamlConfiguration.loadConfiguration(getConfigFile());
set(fields, craftServer, "configuration", bukkit); set(fields, craftServer, "configuration", bukkit);
@ -91,7 +116,8 @@ public class RCraftServer {
set(fields, craftServer, "animalSpawn", bukkit.getInt("spawn-limits.animals")); set(fields, craftServer, "animalSpawn", bukkit.getInt("spawn-limits.animals"));
set(fields, craftServer, "waterAnimalSpawn", bukkit.getInt("spawn-limits.water-animals")); set(fields, craftServer, "waterAnimalSpawn", bukkit.getInt("spawn-limits.water-animals"));
set(fields, craftServer, "ambientSpawn", bukkit.getInt("spawn-limits.ambient")); set(fields, craftServer, "ambientSpawn", bukkit.getInt("spawn-limits.ambient"));
set(fields, craftServer, "warningState", Warning.WarningState.value(bukkit.getString("settings.deprecated-verbose"))); set(fields, craftServer, "warningState",
Warning.WarningState.value(bukkit.getString("settings.deprecated-verbose")));
set(fields, craftServer, "minimumAPI", bukkit.getString("settings.minimum-api")); set(fields, craftServer, "minimumAPI", bukkit.getString("settings.minimum-api"));
set(fields, craftServer, "printSaveWarning", false); set(fields, craftServer, "printSaveWarning", false);
@ -105,25 +131,43 @@ public class RCraftServer {
invoke(methods, craftServer, "loadIcon"); invoke(methods, craftServer, "loadIcon");
} }
/**
* Reloads the commands.yml file.
* @throws InvocationTargetException If the method call produced an exception.
* @throws IllegalAccessException When prohibited access to the method.
*/
public static void reloadCommandsConfiguration() throws IllegalAccessException, InvocationTargetException { public static void reloadCommandsConfiguration() throws IllegalAccessException, InvocationTargetException {
Map<String, Command> map = RCommandMap.getKnownCommands(commandMap); Map<String, Command> map = RCommandMap.getKnownCommands(commandMap);
Bukkit.getCommandAliases().keySet().forEach(map::remove); Bukkit.getCommandAliases().keySet().forEach(map::remove);
YamlConfiguration commands = YamlConfiguration.loadConfiguration(getCommandsConfigFile()); YamlConfiguration commands = YamlConfiguration.loadConfiguration(getCommandsConfigFile());
set(fields, craftServer, "commandsConfiguration", commands); set(fields, craftServer, "commandsConfiguration", commands);
set(fields, craftServer, "overrideAllCommandBlockCommands", commands.getStringList("command-block-overrides").contains("*")); set(fields, craftServer, "overrideAllCommandBlockCommands",
set(fields, craftServer, "ignoreVanillaPermissions", commands.getBoolean("ignore-vanilla-permissions")); commands.getStringList("command-block-overrides").contains("*"));
set(fields, craftServer, "unrestrictedAdvancements", commands.getBoolean("unrestricted-advancements")); set(fields, craftServer, "ignoreVanillaPermissions",
commands.getBoolean("ignore-vanilla-permissions"));
set(fields, craftServer, "unrestrictedAdvancements",
commands.getBoolean("unrestricted-advancements"));
commandMap.registerServerAliases(); commandMap.registerServerAliases();
} }
public static void reloadIPBans() throws IllegalAccessException, InvocationTargetException { /**
* Reloads the ip-bans file.
* @throws InvocationTargetException If the method call produced an exception.
* @throws IllegalAccessException When prohibited access to the method.
*/
public static void reloadIpBans() throws IllegalAccessException, InvocationTargetException {
Object playerList = get(fields, craftServer, "playerList"); Object playerList = get(fields, craftServer, "playerList");
Object jsonList = invoke(RPlayerList.getMethods(), playerList, "getIPBans"); Object jsonList = invoke(RPlayerList.getMethods(), playerList, "getIPBans");
RJsonList.load(jsonList); RJsonList.load(jsonList);
} }
/**
* Reloads the profile bans file.
* @throws InvocationTargetException If the method call produced an exception.
* @throws IllegalAccessException When prohibited access to the method.
*/
public static void reloadProfileBans() throws IllegalAccessException, InvocationTargetException { public static void reloadProfileBans() throws IllegalAccessException, InvocationTargetException {
Object playerList = get(fields, craftServer, "playerList"); Object playerList = get(fields, craftServer, "playerList");
Object jsonList = invoke(RPlayerList.getMethods(), playerList, "getProfileBans"); Object jsonList = invoke(RPlayerList.getMethods(), playerList, "getProfileBans");

View file

@ -1,16 +1,21 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import net.frankheijden.serverutils.utils.MapUtils; import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import org.bukkit.plugin.Plugin; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MINOR;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.min;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.invoke;
import java.lang.reflect.*; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.*; import net.frankheijden.serverutils.utils.MapUtils;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf; import org.bukkit.plugin.Plugin;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.min;
public class RCraftingManager { public class RCraftingManager {
@ -19,7 +24,8 @@ public class RCraftingManager {
static { static {
try { try {
craftingManagerClass = Class.forName(String.format("net.minecraft.server.%s.CraftingManager", ReflectionUtils.NMS)); craftingManagerClass = Class.forName(String.format("net.minecraft.server.%s.CraftingManager",
ReflectionUtils.NMS));
fields = getAllFields(craftingManagerClass, fields = getAllFields(craftingManagerClass,
fieldOf("recipes", min(12))); fieldOf("recipes", min(12)));
} catch (Exception ex) { } catch (Exception ex) {
@ -27,6 +33,12 @@ public class RCraftingManager {
} }
} }
/**
* Removes all associated recipes of a plugin.
* @param plugin The plugin to remove recipes for.
* @throws IllegalAccessException When prohibited access to the method.
* @throws InvocationTargetException If the method call produced an exception.
*/
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
public static void removeRecipesFor(Plugin plugin) throws IllegalAccessException, InvocationTargetException { public static void removeRecipesFor(Plugin plugin) throws IllegalAccessException, InvocationTargetException {
// Cleaning up recipes before MC 1.12 is not possible, // Cleaning up recipes before MC 1.12 is not possible,
@ -43,11 +55,12 @@ public class RCraftingManager {
Object craftingManager = invoke(RMinecraftServer.getMethods(), server, "getCraftingManager"); Object craftingManager = invoke(RMinecraftServer.getMethods(), server, "getCraftingManager");
Map recipes = (Map) recipesField.get(craftingManager); Map recipes = (Map) recipesField.get(craftingManager);
Predicate<Object> predicate = RMinecraftKey.matchingPluginPredicate(new AtomicBoolean(false), plugin);
if (MINOR == 13) { if (MINOR == 13) {
MapUtils.removeKeys(recipes, RMinecraftKey.matchingPluginPredicate(new AtomicBoolean(false), plugin)); MapUtils.removeKeys(recipes, predicate);
} else { } else {
Collection<Map> list = (Collection<Map>) recipes.values(); Collection<Map> list = (Collection<Map>) recipes.values();
list.forEach(map -> MapUtils.removeKeys(map, RMinecraftKey.matchingPluginPredicate(new AtomicBoolean(false), plugin))); list.forEach(map -> MapUtils.removeKeys(map, predicate));
} }
} }
} }

View file

@ -1,14 +1,21 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MINOR;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.min;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.invoke;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.set;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Map; import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.*;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.*;
public class RDedicatedServer { public class RDedicatedServer {
private static Class<?> dedicatedServerClass; private static Class<?> dedicatedServerClass;
@ -17,7 +24,8 @@ public class RDedicatedServer {
static { static {
try { try {
dedicatedServerClass = Class.forName(String.format("net.minecraft.server.%s.DedicatedServer", ReflectionUtils.NMS)); dedicatedServerClass = Class.forName(String.format("net.minecraft.server.%s.DedicatedServer",
ReflectionUtils.NMS));
fields = getAllFields(dedicatedServerClass, fields = getAllFields(dedicatedServerClass,
fieldOf("propertyManager", ALL_VERSIONS), fieldOf("propertyManager", ALL_VERSIONS),
@ -47,29 +55,57 @@ public class RDedicatedServer {
return fields; return fields;
} }
public static void reload(Object console) throws Exception { /**
* Reloads the specified console (= DedicatedServer) instance's bukkit config.
* @param console The console to reload.
* @throws ReflectiveOperationException Iff exception thrown regarding reflection.
*/
public static void reload(Object console) throws ReflectiveOperationException {
Object options = get(fields, console, "options"); Object options = get(fields, console, "options");
if (MINOR >= 13) { if (MINOR >= 13) {
Object propertyManager = RDedicatedServerSettings.newInstance(options); Object propertyManager = RDedicatedServerSettings.newInstance(options);
set(fields, console, "propertyManager", propertyManager); set(fields, console, "propertyManager", propertyManager);
Object config = invoke(RDedicatedServerSettings.getMethods(), propertyManager, "getProperties"); Object config = invoke(RDedicatedServerSettings.getMethods(), propertyManager, "getProperties");
invoke(methods, console, "setSpawnAnimals", get(RDedicatedServerProperties.getFields(), config, "spawnAnimals")); invoke(methods, console, "setSpawnAnimals", getConfigValue(config, "spawnAnimals"));
invoke(methods, console, "setSpawnNPCs", get(RDedicatedServerProperties.getFields(), config, "spawnNpcs")); invoke(methods, console, "setSpawnNPCs", getConfigValue(config, "spawnNpcs"));
invoke(methods, console, "setPVP", get(RDedicatedServerProperties.getFields(), config, "pvp")); invoke(methods, console, "setPVP", getConfigValue(config, "pvp"));
invoke(methods, console, "setAllowFlight", get(RDedicatedServerProperties.getFields(), config, "allowFlight")); invoke(methods, console, "setAllowFlight", getConfigValue(config, "allowFlight"));
invoke(methods, console, "setResourcePack", get(RDedicatedServerProperties.getFields(), config, "resourcePack"), invoke(methods, console, "aZ")); invoke(methods, console, "setResourcePack", getConfigValue(config, "resourcePack"),
invoke(methods, console, "setMotd", get(RDedicatedServerProperties.getFields(), config, "motd")); invoke(methods, console, "aZ"));
invoke(methods, console, "setForceGamemode", get(RDedicatedServerProperties.getFields(), config, "forceGamemode")); invoke(methods, console, "setMotd", getConfigValue(config, "motd"));
invoke(methods, console, "n", get(RDedicatedServerProperties.getFields(), config, "enforceWhitelist")); invoke(methods, console, "setForceGamemode", getConfigValue(config, "forceGamemode"));
set(fields, console, "o", get(RDedicatedServerProperties.getFields(), config, "gamemode")); invoke(methods, console, "n", getConfigValue(config, "enforceWhitelist"));
set(fields, console, "o", getConfigValue(config, "gamemode"));
} else { } else {
Object config = RPropertyManager.newInstance(options); Object config = RPropertyManager.newInstance(options);
set(fields, console, "propertyManager", config); setConfigValue(config, console, "getSpawnAnimals", "setSpawnAnimals", "getBoolean", "spawn-animals");
invoke(methods, console, "setSpawnAnimals", invoke(RPropertyManager.getMethods(), config, "getBoolean", "spawn-animals", invoke(methods, console, "getSpawnAnimals"))); setConfigValue(config, console, "getPVP", "setPVP", "getBoolean", "pvp");
invoke(methods, console, "setPVP", invoke(RPropertyManager.getMethods(), config, "getBoolean", "pvp", invoke(methods, console, "getPVP"))); setConfigValue(config, console, "getAllowFlight", "setAllowFlight", "getBoolean", "allow-flight");
invoke(methods, console, "setAllowFlight", invoke(RPropertyManager.getMethods(), config, "getBoolean", "allow-flight", invoke(methods, console, "getAllowFlight"))); setConfigValue(config, console, "getMotd", "setMotd", "getString", "motd");
invoke(methods, console, "setMotd", invoke(RPropertyManager.getMethods(), config, "getString", "motd", invoke(methods, console, "getMotd")));
} }
} }
public static Object getConfigValue(Object config, String key) throws IllegalAccessException {
return get(RDedicatedServerProperties.getFields(), config, key);
}
/**
* Sets the specified bukkit config value.
* @param config The config instance (= PropertyManager)
* @param console The console instance (= DedicatedServer)
* @param getMethod The getter method for the config value.
* @param setMethod The setter method for the config value.
* @param configMethod The method which we call the config value upon.
* @param key The config key.
* @throws InvocationTargetException If the method call produced an exception.
* @throws IllegalAccessException When prohibited access to the method.
*/
public static void setConfigValue(Object config, Object console, String getMethod, String setMethod,
String configMethod, String key)
throws InvocationTargetException, IllegalAccessException {
Object defaultValue = invoke(methods, console, getMethod);
Object configValue = invoke(RPropertyManager.getMethods(), config, configMethod, key, defaultValue);
invoke(methods, console, setMethod, configValue);
}
} }

View file

@ -1,21 +1,22 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.lang.reflect.Field;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import java.lang.reflect.Field;
import java.util.Map;
public class RDedicatedServerProperties { public class RDedicatedServerProperties {
private static Class<?> dedicatedServerPropertiesClass; private static Class<?> serverPropertiesClass;
private static Map<String, Field> fields; private static Map<String, Field> fields;
static { static {
try { try {
dedicatedServerPropertiesClass = Class.forName(String.format("net.minecraft.server.%s.DedicatedServerProperties", ReflectionUtils.NMS)); serverPropertiesClass = Class.forName(String.format("net.minecraft.server.%s.DedicatedServerProperties",
fields = getAllFields(dedicatedServerPropertiesClass, ReflectionUtils.NMS));
fields = getAllFields(serverPropertiesClass,
fieldOf("spawnAnimals", ALL_VERSIONS), fieldOf("spawnAnimals", ALL_VERSIONS),
fieldOf("spawnNpcs", ALL_VERSIONS), fieldOf("spawnNpcs", ALL_VERSIONS),
fieldOf("pvp", ALL_VERSIONS), fieldOf("pvp", ALL_VERSIONS),

View file

@ -1,29 +1,30 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.lang.reflect.Method;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import java.lang.reflect.Method;
import java.util.Map;
public class RDedicatedServerSettings { public class RDedicatedServerSettings {
private static Class<?> dedicatedServerSettingsClass; private static Class<?> serverSettingsClass;
private static Map<String, Method> methods; private static Map<String, Method> methods;
static { static {
try { try {
dedicatedServerSettingsClass = Class.forName(String.format("net.minecraft.server.%s.DedicatedServerSettings", ReflectionUtils.NMS)); serverSettingsClass = Class.forName(String.format("net.minecraft.server.%s.DedicatedServerSettings",
methods = getAllMethods(dedicatedServerSettingsClass, ReflectionUtils.NMS));
methods = getAllMethods(serverSettingsClass,
methodOf("getProperties", ALL_VERSIONS)); methodOf("getProperties", ALL_VERSIONS));
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public static Object newInstance(Object options) throws Exception { public static Object newInstance(Object options)throws ReflectiveOperationException {
return dedicatedServerSettingsClass.getDeclaredConstructor(Class.forName("joptsimple.OptionSet")).newInstance(options); return serverSettingsClass.getDeclaredConstructor(Class.forName("joptsimple.OptionSet")).newInstance(options);
} }
public static Map<String, Method> getMethods() { public static Map<String, Method> getMethods() {

View file

@ -1,16 +1,16 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.invoke; import static net.frankheijden.serverutils.reflection.ReflectionUtils.invoke;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.bukkit.plugin.java.JavaPlugin;
public class RJavaPlugin { public class RJavaPlugin {
private static Class<?> javaPluginClass; private static Class<?> javaPluginClass;

View file

@ -1,18 +1,19 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.invoke; import static net.frankheijden.serverutils.reflection.ReflectionUtils.invoke;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
public class RJsonList { public class RJsonList {
private static Class<?> jsonListClass; private static Class<?> jsonListClass;
private static Map<String, Method> methods; private static Map<String, Method> methods;
static { static {
try { try {
jsonListClass = Class.forName(String.format("net.minecraft.server.%s.JsonList", ReflectionUtils.NMS)); jsonListClass = Class.forName(String.format("net.minecraft.server.%s.JsonList", ReflectionUtils.NMS));

View file

@ -1,6 +1,10 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import org.bukkit.plugin.Plugin; import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.max;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.min;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Locale; import java.util.Locale;
@ -8,10 +12,7 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate; import java.util.function.Predicate;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf; import org.bukkit.plugin.Plugin;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.*;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
public class RMinecraftKey { public class RMinecraftKey {
@ -20,7 +21,8 @@ public class RMinecraftKey {
static { static {
try { try {
minecraftKeyClass = Class.forName(String.format("net.minecraft.server.%s.MinecraftKey", ReflectionUtils.NMS)); minecraftKeyClass = Class.forName(String.format("net.minecraft.server.%s.MinecraftKey",
ReflectionUtils.NMS));
fields = getAllFields(minecraftKeyClass, fields = getAllFields(minecraftKeyClass,
fieldOf("a", max(13)), fieldOf("a", max(13)),
fieldOf("namespace", min(14))); fieldOf("namespace", min(14)));
@ -29,6 +31,12 @@ public class RMinecraftKey {
} }
} }
/**
* Retrieves the namespace of the specified MinecraftKey instance.
* @param instance The MinecraftKey instance.
* @return The namespace.
* @throws IllegalAccessException When prohibited access to the field.
*/
public static String getNameSpace(Object instance) throws IllegalAccessException { public static String getNameSpace(Object instance) throws IllegalAccessException {
if (ReflectionUtils.MINOR <= 13) { if (ReflectionUtils.MINOR <= 13) {
return (String) get(fields, instance, "a"); return (String) get(fields, instance, "a");
@ -41,6 +49,12 @@ public class RMinecraftKey {
return namespace.equalsIgnoreCase(getNameSpace(instance)); return namespace.equalsIgnoreCase(getNameSpace(instance));
} }
/**
* Creates a predicate which returns true if a MinecraftKey instance comes from the specified plugin.
* @param errorThrown Requires an atomicboolean to ensure an exception is only thrown once, if any.
* @param plugin The plugin to match the MinecraftKey instance with.
* @return The predicate.
*/
public static Predicate<Object> matchingPluginPredicate(AtomicBoolean errorThrown, Plugin plugin) { public static Predicate<Object> matchingPluginPredicate(AtomicBoolean errorThrown, Plugin plugin) {
return o -> { return o -> {
try { try {

View file

@ -1,12 +1,12 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.lang.reflect.Method;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import java.lang.reflect.Method;
import java.util.Map;
public class RMinecraftServer { public class RMinecraftServer {
private static Class<?> minecraftServerClass; private static Class<?> minecraftServerClass;
@ -14,7 +14,8 @@ public class RMinecraftServer {
static { static {
try { try {
minecraftServerClass = Class.forName(String.format("net.minecraft.server.%s.MinecraftServer", ReflectionUtils.NMS)); minecraftServerClass = Class.forName(String.format("net.minecraft.server.%s.MinecraftServer",
ReflectionUtils.NMS));
methods = getAllMethods(minecraftServerClass, methods = getAllMethods(minecraftServerClass,
methodOf("getServer", ALL_VERSIONS), methodOf("getServer", ALL_VERSIONS),
methodOf("getCraftingManager", ALL_VERSIONS)); methodOf("getCraftingManager", ALL_VERSIONS));

View file

@ -1,12 +1,12 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.lang.reflect.Method;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import java.lang.reflect.Method;
import java.util.Map;
public class ROptionSet { public class ROptionSet {
private static Class<?> optionSetClass; private static Class<?> optionSetClass;

View file

@ -1,12 +1,12 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.lang.reflect.Method;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import java.lang.reflect.Method;
import java.util.Map;
public class RPlayerList { public class RPlayerList {
private static Class<?> playerListClass; private static Class<?> playerListClass;

View file

@ -1,17 +1,18 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import org.bukkit.plugin.Plugin; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getDeclaredMethod;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File; import java.io.File;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getDeclaredMethod; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
public class RPlugin { public class RPlugin {
private static Method getFile; private static Method getFile;
static { static {
try { try {
getFile = getDeclaredMethod(JavaPlugin.class, "getFile"); getFile = getDeclaredMethod(JavaPlugin.class, "getFile");

View file

@ -1,15 +1,15 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.io.IOException;
import java.lang.reflect.*;
import java.net.URLClassLoader;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.set; import static net.frankheijden.serverutils.reflection.ReflectionUtils.set;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLClassLoader;
import java.util.Map;
public class RPluginClassLoader { public class RPluginClassLoader {
private static Class<?> pluginClassLoaderClass; private static Class<?> pluginClassLoaderClass;
@ -30,17 +30,32 @@ public class RPluginClassLoader {
return pluginClassLoaderClass.isInstance(obj); return pluginClassLoaderClass.isInstance(obj);
} }
/**
* Clears and closes the provided classloader.
* Remov
* @param loader The classloader instance.
* @throws IOException When closing the loader failed.
* @throws IllegalAccessException When prohibited access to the field.
*/
public static void clearClassLoader(ClassLoader loader) throws IOException, IllegalAccessException { public static void clearClassLoader(ClassLoader loader) throws IOException, IllegalAccessException {
if (loader == null) return; if (loader == null) return;
if (isInstance(loader)) { if (isInstance(loader)) {
clearURLClassLoader((URLClassLoader) loader); clearUrlClassLoader(loader);
}
if (loader instanceof URLClassLoader) {
((URLClassLoader) loader).close();
} }
} }
public static void clearURLClassLoader(URLClassLoader loader) throws IllegalAccessException, IOException { /**
if (loader == null) return; * Clears the plugin fields from the specified PluginClassLoader.
set(fields, loader, "plugin", null); * @param pluginLoader The plugin loader instance.
set(fields, loader, "pluginInit", null); * @throws IllegalAccessException When prohibited access to the field.
loader.close(); */
public static void clearUrlClassLoader(Object pluginLoader) throws IllegalAccessException {
if (pluginLoader == null) return;
set(fields, pluginLoader, "plugin", null);
set(fields, pluginLoader, "pluginInit", null);
} }
} }

View file

@ -1,12 +1,12 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import java.lang.reflect.Method;
import java.util.Map;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.MethodParam.methodOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllMethods;
import java.lang.reflect.Method;
import java.util.Map;
public class RPropertyManager { public class RPropertyManager {
private static Class<?> propertyManagerClass; private static Class<?> propertyManagerClass;
@ -14,7 +14,8 @@ public class RPropertyManager {
static { static {
try { try {
propertyManagerClass = Class.forName(String.format("net.minecraft.server.%s.PropertyManager", ReflectionUtils.NMS)); propertyManagerClass = Class.forName(String.format("net.minecraft.server.%s.PropertyManager",
ReflectionUtils.NMS));
methods = getAllMethods(propertyManagerClass, methods = getAllMethods(propertyManagerClass,
methodOf("getBoolean", ALL_VERSIONS, String.class, boolean.class), methodOf("getBoolean", ALL_VERSIONS, String.class, boolean.class),
methodOf("getString", ALL_VERSIONS, String.class, String.class)); methodOf("getString", ALL_VERSIONS, String.class, String.class));
@ -23,7 +24,7 @@ public class RPropertyManager {
} }
} }
public static Object newInstance(Object options) throws Exception { public static Object newInstance(Object options) throws ReflectiveOperationException {
return propertyManagerClass.getDeclaredConstructor(Class.forName("joptsimple.OptionSet")).newInstance(options); return propertyManagerClass.getDeclaredConstructor(Class.forName("joptsimple.OptionSet")).newInstance(options);
} }

View file

@ -1,17 +1,17 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import net.frankheijden.serverutils.utils.MapUtils;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get; import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import net.frankheijden.serverutils.utils.MapUtils;
import org.bukkit.plugin.Plugin;
public class RRegistryMaterials { public class RRegistryMaterials {
private static Class<?> registryMaterialsClass; private static Class<?> registryMaterialsClass;
@ -20,7 +20,8 @@ public class RRegistryMaterials {
static { static {
try { try {
registryMaterialsClass = Class.forName(String.format("net.minecraft.server.%s.RegistryMaterials", ReflectionUtils.NMS)); registryMaterialsClass = Class.forName(String.format("net.minecraft.server.%s.RegistryMaterials",
ReflectionUtils.NMS));
fields = getAllFields(registryMaterialsClass, fields = getAllFields(registryMaterialsClass,
fieldOf("b", ALL_VERSIONS)); fieldOf("b", ALL_VERSIONS));
} catch (Exception ex) { } catch (Exception ex) {
@ -28,6 +29,12 @@ public class RRegistryMaterials {
} }
} }
/**
* Removes all registered keys from an instance associated to the specified plugin.
* @param instance The RegistryMaterials instance.
* @param plugin The plugin to remove keys for.
* @throws IllegalAccessException When prohibited access to the field.
*/
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static void removeKeysFor(Object instance, Plugin plugin) throws IllegalAccessException { public static void removeKeysFor(Object instance, Plugin plugin) throws IllegalAccessException {
Map map = (Map) get(fields, instance, "b"); Map map = (Map) get(fields, instance, "b");

View file

@ -1,17 +1,17 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import net.frankheijden.serverutils.utils.MapUtils;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get; import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import net.frankheijden.serverutils.utils.MapUtils;
import org.bukkit.plugin.Plugin;
public class RRegistrySimple { public class RRegistrySimple {
private static Class<?> registrySimpleClass; private static Class<?> registrySimpleClass;
@ -19,7 +19,8 @@ public class RRegistrySimple {
static { static {
try { try {
registrySimpleClass = Class.forName(String.format("net.minecraft.server.%s.RegistrySimple", ReflectionUtils.NMS)); registrySimpleClass = Class.forName(String.format("net.minecraft.server.%s.RegistrySimple",
ReflectionUtils.NMS));
fields = getAllFields(registrySimpleClass, fields = getAllFields(registrySimpleClass,
fieldOf("c", ALL_VERSIONS)); fieldOf("c", ALL_VERSIONS));
} catch (Exception ex) { } catch (Exception ex) {
@ -27,6 +28,12 @@ public class RRegistrySimple {
} }
} }
/**
* Removes all registered MinecraftKey's from an instance associated to the specified plugin.
* @param instance The RegistrySimple instance.
* @param plugin The plugin to remove keys for.
* @throws IllegalAccessException When prohibited access to the field.
*/
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static void removeKeyFor(Object instance, Plugin plugin) throws IllegalAccessException { public static void removeKeyFor(Object instance, Plugin plugin) throws IllegalAccessException {
Map map = (Map) get(fields, instance, "c"); Map map = (Map) get(fields, instance, "c");

View file

@ -1,16 +1,20 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import org.bukkit.plugin.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Pattern;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf; import static net.frankheijden.serverutils.reflection.ReflectionUtils.FieldParam.fieldOf;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS; import static net.frankheijden.serverutils.reflection.ReflectionUtils.VersionParam.ALL_VERSIONS;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.get; import static net.frankheijden.serverutils.reflection.ReflectionUtils.get;
import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields; import static net.frankheijden.serverutils.reflection.ReflectionUtils.getAllFields;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.SimplePluginManager;
public class RSimplePluginManager { public class RSimplePluginManager {
private static Class<?> simplePluginManagerClass; private static Class<?> simplePluginManagerClass;
@ -38,6 +42,13 @@ public class RSimplePluginManager {
return (List<Plugin>) get(fields, manager, "plugins"); return (List<Plugin>) get(fields, manager, "plugins");
} }
/**
* Removes the lookup name of the plugin.
* This ensures the plugin cannot be found anymore in Bukkit#getPlugin(String name).
* @param manager The SimplePluginManager instance to remove the lookup name from.
* @param name The name of the plugin to remove.
* @throws IllegalAccessException When prohibited access to the field.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void removeLookupName(Object manager, String name) throws IllegalAccessException { public static void removeLookupName(Object manager, String name) throws IllegalAccessException {
Map<String, Plugin> lookupNames = (Map<String, Plugin>) get(fields, manager, "lookupNames"); Map<String, Plugin> lookupNames = (Map<String, Plugin>) get(fields, manager, "lookupNames");

View file

@ -1,9 +1,12 @@
package net.frankheijden.serverutils.reflection; package net.frankheijden.serverutils.reflection;
import org.bukkit.Bukkit; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.lang.reflect.*; import org.bukkit.Bukkit;
import java.util.*;
public class ReflectionUtils { public class ReflectionUtils {
@ -11,6 +14,7 @@ public class ReflectionUtils {
public static int MAJOR; public static int MAJOR;
public static int MINOR; public static int MINOR;
public static int PATCH; public static int PATCH;
static { static {
String bukkitPackage = Bukkit.getServer().getClass().getPackage().getName(); String bukkitPackage = Bukkit.getServer().getClass().getPackage().getName();
NMS = bukkitPackage.substring(bukkitPackage.lastIndexOf('.') + 1); NMS = bukkitPackage.substring(bukkitPackage.lastIndexOf('.') + 1);
@ -21,33 +25,71 @@ public class ReflectionUtils {
PATCH = Integer.parseInt(split[2].substring(1, 2)); PATCH = Integer.parseInt(split[2].substring(1, 2));
} }
/**
* Retrieves a declared field from a class and makes it accessible.
* @param clazz The class of the method.
* @param field The field name.
* @return The specified field.
* @throws NoSuchFieldException iff field doesn't exist.
*/
public static Field getDeclaredField(Class<?> clazz, String field) throws NoSuchFieldException { public static Field getDeclaredField(Class<?> clazz, String field) throws NoSuchFieldException {
Field f = clazz.getDeclaredField(field); Field f = clazz.getDeclaredField(field);
f.setAccessible(true); f.setAccessible(true);
return f; return f;
} }
/**
* Retrieves a field from a class and makes it accessible.
* @param clazz The class of the method.
* @param field The field name.
* @return The specified field.
* @throws NoSuchFieldException iff field doesn't exist.
*/
public static Field getField(Class<?> clazz, String field) throws NoSuchFieldException { public static Field getField(Class<?> clazz, String field) throws NoSuchFieldException {
Field f = clazz.getField(field); Field f = clazz.getField(field);
f.setAccessible(true); f.setAccessible(true);
return f; return f;
} }
public static Method getDeclaredMethod(Class<?> clazz, String method, Class<?>... params) throws NoSuchMethodException { /**
* Retrieves a declared method from a class and makes it accessible.
* @param clazz The class of the method.
* @param method The method name.
* @param params The parameters of the method.
* @return The specified method.
* @throws NoSuchMethodException iff method doesn't exist.
*/
public static Method getDeclaredMethod(Class<?> clazz, String method, Class<?>... params)
throws NoSuchMethodException {
Method m = clazz.getDeclaredMethod(method, params); Method m = clazz.getDeclaredMethod(method, params);
m.setAccessible(true); m.setAccessible(true);
return m; return m;
} }
public static Method getMethod(Class<?> clazz, String method, Class<?>... params) throws NoSuchMethodException { /**
* Retrieves a method from a class and makes it accessible.
* @param clazz The class of the method.
* @param method The method name.
* @param params The parameters of the method.
* @return The specified method.
* @throws NoSuchMethodException iff method doesn't exist.
*/
public static Method getMethod(Class<?> clazz, String method, Class<?>... params)
throws NoSuchMethodException {
Method m = clazz.getMethod(method, params); Method m = clazz.getMethod(method, params);
m.setAccessible(true); m.setAccessible(true);
return m; return m;
} }
public static Map<String, Field> getAllFields(Class<?> clazz, FieldParam... fields) { /**
* Retrieves fields from a class based on the specified FieldParams.
* @param clazz The class of the fields.
* @param fieldParams The fields which will be collected.
* @return A map with key the field name and value the actual field.
*/
public static Map<String, Field> getAllFields(Class<?> clazz, FieldParam... fieldParams) {
Map<String, Field> map = new HashMap<>(); Map<String, Field> map = new HashMap<>();
for (FieldParam fieldParam : fields) { for (FieldParam fieldParam : fieldParams) {
if (!fieldParam.versionParam.isCompatible()) continue; if (!fieldParam.versionParam.isCompatible()) continue;
try { try {
map.put(fieldParam.field, getDeclaredField(clazz, fieldParam.field)); map.put(fieldParam.field, getDeclaredField(clazz, fieldParam.field));
@ -62,6 +104,12 @@ public class ReflectionUtils {
return map; return map;
} }
/**
* Retrieves methods from a class based on the specified MethodParams.
* @param clazz The class of the methods.
* @param methodParams The methods which will be collected.
* @return A map with key the method name and value the actual method.
*/
public static Map<String, Method> getAllMethods(Class<?> clazz, MethodParam... methodParams) { public static Map<String, Method> getAllMethods(Class<?> clazz, MethodParam... methodParams) {
Map<String, Method> map = new HashMap<>(); Map<String, Method> map = new HashMap<>();
for (MethodParam methodParam : methodParams) { for (MethodParam methodParam : methodParams) {
@ -79,19 +127,49 @@ public class ReflectionUtils {
return map; return map;
} }
public static Object invoke(Map<String, Method> map, Object instance, String methodName, Object... params) throws InvocationTargetException, IllegalAccessException { /**
* Invokes a method on an instance.
* Will return null if method not present in map.
* @param map The map with methods.
* @param instance The instance of the class.
* @param methodName The name of the method.
* @param params The parameters of the method.
* @return The object returned by the method, or null if not present in map.
* @throws InvocationTargetException If the method call produced an exception.
* @throws IllegalAccessException When prohibited access to the method.
*/
public static Object invoke(Map<String, Method> map, Object instance, String methodName, Object... params)
throws InvocationTargetException, IllegalAccessException {
Method method = map.get(methodName); Method method = map.get(methodName);
if (method == null) return null; if (method == null) return null;
return method.invoke(instance, params); return method.invoke(instance, params);
} }
/**
* Retrieves the specified field from an object instance.
* Returns null if the field is not in the map.
* @param map The map with fields.
* @param instance The instance of the class.
* @param fieldName The field name.
* @throws IllegalAccessException When prohibited access to the field.
*/
public static Object get(Map<String, Field> map, Object instance, String fieldName) throws IllegalAccessException { public static Object get(Map<String, Field> map, Object instance, String fieldName) throws IllegalAccessException {
Field field = map.get(fieldName); Field field = map.get(fieldName);
if (field == null) return null; if (field == null) return null;
return field.get(instance); return field.get(instance);
} }
public static void set(Map<String, Field> map, Object instance, String fieldName, Object value) throws IllegalAccessException { /**
* Sets the specified field to the specified value.
* Will silently fail if the field is not in the map.
* @param map The map with fields.
* @param instance The instance of the class.
* @param fieldName The field name.
* @param value The value to set the field to.
* @throws IllegalAccessException When prohibited access to the field.
*/
public static void set(Map<String, Field> map, Object instance, String fieldName, Object value)
throws IllegalAccessException {
Field field = map.get(fieldName); Field field = map.get(fieldName);
if (field == null) return; if (field == null) return;
field.set(instance, value); field.set(instance, value);

View file

@ -1,10 +1,32 @@
package net.frankheijden.serverutils.tasks; package net.frankheijden.serverutils.tasks;
import com.google.gson.*; import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import net.frankheijden.serverutils.ServerUtils; import net.frankheijden.serverutils.ServerUtils;
import net.frankheijden.serverutils.config.Config; import net.frankheijden.serverutils.config.Config;
import net.frankheijden.serverutils.config.Messenger; import net.frankheijden.serverutils.config.Messenger;
import net.frankheijden.serverutils.managers.*; import net.frankheijden.serverutils.managers.VersionManager;
import net.frankheijden.serverutils.utils.VersionUtils; import net.frankheijden.serverutils.utils.VersionUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -12,14 +34,6 @@ import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException; import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.io.*;
import java.lang.reflect.Method;
import java.net.*;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
public class UpdateCheckerTask implements Runnable { public class UpdateCheckerTask implements Runnable {
private static final ServerUtils plugin = ServerUtils.getInstance(); private static final ServerUtils plugin = ServerUtils.getInstance();
@ -29,6 +43,19 @@ public class UpdateCheckerTask implements Runnable {
private final boolean startup; private final boolean startup;
private static final String GITHUB_LINK = "https://api.github.com/repos/FrankHeijden/ServerUtils/releases/latest"; private static final String GITHUB_LINK = "https://api.github.com/repos/FrankHeijden/ServerUtils/releases/latest";
private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0)"
+ "Gecko/20100101"
+ "Firefox/77.0";
private static final String UPDATE_CHECK_START = "Checking for updates...";
private static final String GENERAL_ERROR = "Error fetching new version of ServerUtils";
private static final String CONNECTION_ERROR = GENERAL_ERROR + ": (%s) %s (maybe check your connection?)";
private static final String UNAVAILABLE = GENERAL_ERROR + ": (%s) %s (no update available)";
private static final String UPDATE_AVAILABLE = "ServerUtils %s is available!";
private static final String DOWNLOAD_START = "Started downloading from \"%s\"...";
private static final String DOWNLOAD_ERROR = "Error downloading a new version of ServerUtils";
private static final String UPGRADE_SUCCESS = "Successfully upgraded ServerUtils to v%s!";
private static final String DOWNLOADED_RESTART = "Downloaded ServerUtils version v%s. Restarting plugin now...";
private UpdateCheckerTask(CommandSender sender, boolean startup) { private UpdateCheckerTask(CommandSender sender, boolean startup) {
this.sender = sender; this.sender = sender;
@ -52,22 +79,20 @@ public class UpdateCheckerTask implements Runnable {
@Override @Override
public void run() { public void run() {
if (isStartupCheck()) { if (isStartupCheck()) {
plugin.getLogger().info("Checking for updates..."); plugin.getLogger().info(UPDATE_CHECK_START);
} }
JsonObject jsonObject; JsonObject jsonObject;
try { try {
jsonObject = readJsonFromURL(GITHUB_LINK).getAsJsonObject(); jsonObject = readJsonFromUrl(GITHUB_LINK).getAsJsonObject();
} catch (ConnectException | UnknownHostException | SocketTimeoutException ex) { } catch (ConnectException | UnknownHostException | SocketTimeoutException ex) {
plugin.getLogger().severe(String.format("Error fetching new version of ServerUtils: (%s) %s (maybe check your connection?)", plugin.getLogger().severe(String.format(CONNECTION_ERROR, ex.getClass().getSimpleName(), ex.getMessage()));
ex.getClass().getSimpleName(), ex.getMessage()));
return; return;
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
plugin.getLogger().severe(String.format("Error fetching new version of ServerUtils: (%s) %s (no update available)", plugin.getLogger().severe(String.format(UNAVAILABLE, ex.getClass().getSimpleName(), ex.getMessage()));
ex.getClass().getSimpleName(), ex.getMessage()));
return; return;
} catch (IOException ex) { } catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, ex, () -> "Error fetching new version of ServerUtils"); plugin.getLogger().log(Level.SEVERE, ex, () -> GENERAL_ERROR);
return; return;
} }
String githubVersion = jsonObject.getAsJsonPrimitive("tag_name").getAsString(); String githubVersion = jsonObject.getAsJsonPrimitive("tag_name").getAsString();
@ -84,12 +109,12 @@ public class UpdateCheckerTask implements Runnable {
} }
if (VersionUtils.isNewVersion(currentVersion, githubVersion)) { if (VersionUtils.isNewVersion(currentVersion, githubVersion)) {
if (isStartupCheck()) { if (isStartupCheck()) {
plugin.getLogger().info(String.format("ServerUtils %s is available!", githubVersion)); plugin.getLogger().info(String.format(UPDATE_AVAILABLE, githubVersion));
plugin.getLogger().info("Release info: " + body); plugin.getLogger().info("Release info: " + body);
} }
if (canDownloadPlugin()) { if (canDownloadPlugin()) {
if (isStartupCheck()) { if (isStartupCheck()) {
plugin.getLogger().info("Started downloading from \"" + downloadLink + "\"..."); plugin.getLogger().info(String.format(DOWNLOAD_START, downloadLink));
} else { } else {
Messenger.sendMessage(sender, "serverutils.update.downloading", Messenger.sendMessage(sender, "serverutils.update.downloading",
"%old%", currentVersion, "%old%", currentVersion,
@ -131,11 +156,11 @@ public class UpdateCheckerTask implements Runnable {
download(downloadLink, getPluginFile()); download(downloadLink, getPluginFile());
} catch (IOException ex) { } catch (IOException ex) {
broadcastDownloadStatus(githubVersion, true); broadcastDownloadStatus(githubVersion, true);
throw new RuntimeException("Error downloading a new version of ServerUtils", ex); throw new RuntimeException(DOWNLOAD_ERROR, ex);
} }
if (isStartupCheck()) { if (isStartupCheck()) {
plugin.getLogger().info(String.format("Downloaded ServerUtils version v%s. Restarting plugin now...", githubVersion)); plugin.getLogger().info(String.format(DOWNLOADED_RESTART, githubVersion));
Bukkit.getPluginManager().disablePlugin(plugin); Bukkit.getPluginManager().disablePlugin(plugin);
try { try {
Bukkit.getPluginManager().enablePlugin(Bukkit.getPluginManager().loadPlugin(getPluginFile())); Bukkit.getPluginManager().enablePlugin(Bukkit.getPluginManager().loadPlugin(getPluginFile()));
@ -143,7 +168,7 @@ public class UpdateCheckerTask implements Runnable {
ex.printStackTrace(); ex.printStackTrace();
return; return;
} }
plugin.getLogger().info(String.format("Successfully upgraded ServerUtils to v%s!", githubVersion)); plugin.getLogger().info(String.format(UPGRADE_SUCCESS, githubVersion));
} else { } else {
versionManager.setDownloadedVersion(githubVersion); versionManager.setDownloadedVersion(githubVersion);
broadcastDownloadStatus(githubVersion, false); broadcastDownloadStatus(githubVersion, false);
@ -186,7 +211,7 @@ public class UpdateCheckerTask implements Runnable {
return sb.toString(); return sb.toString();
} }
private JsonElement readJsonFromURL(String url) throws IOException { private JsonElement readJsonFromUrl(String url) throws IOException {
try (InputStream is = stream(url)) { try (InputStream is = stream(url)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String jsonText = readAll(reader); String jsonText = readAll(reader);
@ -196,7 +221,7 @@ public class UpdateCheckerTask implements Runnable {
private InputStream stream(String url) throws IOException { private InputStream stream(String url) throws IOException {
URLConnection conn = new URL(url).openConnection(); URLConnection conn = new URL(url).openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0"); conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setConnectTimeout(10000); conn.setConnectTimeout(10000);
return conn.getInputStream(); return conn.getInputStream();
} }

View file

@ -1,11 +1,11 @@
package net.frankheijden.serverutils.utils; package net.frankheijden.serverutils.utils;
import net.frankheijden.serverutils.config.Messenger;
import org.bukkit.command.CommandSender;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.frankheijden.serverutils.config.Messenger;
import org.bukkit.command.CommandSender;
public class FormatBuilder { public class FormatBuilder {
private final String format; private final String format;
@ -39,6 +39,10 @@ public class FormatBuilder {
return this; return this;
} }
/**
* Builds the format and sends it to the CommandSender.
* @param sender The receiver of the list.
*/
public void sendTo(CommandSender sender) { public void sendTo(CommandSender sender) {
valueList.forEach(values -> { valueList.forEach(values -> {
int length = Math.min(values.length, orderedKeys.length); int length = Math.min(values.length, orderedKeys.length);

View file

@ -1,14 +1,19 @@
package net.frankheijden.serverutils.utils; package net.frankheijden.serverutils.utils;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.logging.*;
public class ForwardFilter extends PredicateFilter { public class ForwardFilter extends PredicateFilter {
private boolean warnings; private boolean warnings;
/**
* Creates a filter which forwards all output to the sender.
* @param sender The sender to forward logs to.
*/
public ForwardFilter(CommandSender sender) { public ForwardFilter(CommandSender sender) {
this.warnings = false; this.warnings = false;

View file

@ -17,6 +17,11 @@ public class ListBuilder<T> {
return new ListBuilder<>(collection); return new ListBuilder<>(collection);
} }
/**
* Creates a pre-defined ListBuilder with type String.
* @param collection The collection to be used.
* @return The ListBuilder.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static ListBuilder<String> createStrings(Collection<? extends String> collection) { public static ListBuilder<String> createStrings(Collection<? extends String> collection) {
ListBuilder<String> builder = create((Collection<String>) collection); ListBuilder<String> builder = create((Collection<String>) collection);

View file

@ -1,10 +1,17 @@
package net.frankheijden.serverutils.utils; package net.frankheijden.serverutils.utils;
import java.util.*; import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate; import java.util.function.Predicate;
public class MapUtils { public class MapUtils {
/**
* Removes keys from a map using a predicate.
* @param map The map.
* @param predicate The predicate used to test removal.
*/
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
public static void removeKeys(Map map, Predicate<Object> predicate) { public static void removeKeys(Map map, Predicate<Object> predicate) {
Set<Object> keysToRemove = new HashSet<>(); Set<Object> keysToRemove = new HashSet<>();
@ -16,6 +23,11 @@ public class MapUtils {
keysToRemove.forEach(map::remove); keysToRemove.forEach(map::remove);
} }
/**
* Removes values from a map using a predicate.
* @param map The map.
* @param predicate The predicate used to test removal.
*/
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
public static void removeValues(Map map, Predicate<Object> predicate) { public static void removeValues(Map map, Predicate<Object> predicate) {
Set<Object> keysToRemove = new HashSet<>(); Set<Object> keysToRemove = new HashSet<>();

View file

@ -1,7 +1,9 @@
package net.frankheijden.serverutils.utils; package net.frankheijden.serverutils.utils;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.logging.*; import java.util.logging.Filter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class PredicateFilter implements Filter { public class PredicateFilter implements Filter {

View file

@ -2,6 +2,13 @@ package net.frankheijden.serverutils.utils;
public class VersionUtils { public class VersionUtils {
/**
* Compares two versions in X.X.X format.
* Returns true if version is newer than the old one.
* @param oldVersion The old version.
* @param newVersion The new version.
* @return true iff new version is newer than old version.
*/
public static boolean isNewVersion(String oldVersion, String newVersion) { public static boolean isNewVersion(String oldVersion, String newVersion) {
String[] oldVersionSplit = oldVersion.split("\\."); String[] oldVersionSplit = oldVersion.split("\\.");
String[] newVersionSplit = newVersion.split("\\."); String[] newVersionSplit = newVersion.split("\\.");

View file

@ -0,0 +1,51 @@
package net.frankheijden.serverutils.utils;
import java.io.File;
import java.io.IOException;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.YamlConfiguration;
public class YamlUtils {
public static void addDefaults(MemorySection defaults, YamlConfiguration yml) {
addDefaults(defaults, yml, "");
}
private static void addDefaults(MemorySection defaults, YamlConfiguration yml, String root) {
MemorySection section = (MemorySection) defaults.get(root);
if (section == null) return;
for (String key : section.getKeys(false)) {
String newKey = (root.isEmpty() ? "" : root + ".") + key;
Object value = defaults.get(key);
if (value instanceof MemorySection) {
addDefaults((MemorySection) value, yml, newKey);
} else if (yml.get(key) == null) {
yml.set(key, value);
}
}
}
/**
* Initiates a YamlConfiguration from a file with associated defaults.
* @param file The yml file.
* @param def The default YamlConfiguration to be applied.
* @return The loaded YamlConfiguration of the file with defaults.
*/
public static YamlConfiguration init(File file, YamlConfiguration def) {
YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
YamlUtils.addDefaults(def, yml);
try {
// Idk somehow the order messes up
// of the messages if we don't do this
file.delete();
file.createNewFile();
yml.save(file);
} catch (IOException ex) {
ex.printStackTrace();
}
return yml;
}
}

View file

@ -1 +1,5 @@
{} settings:
disable-plugins-command: false
check-updates: true
download-updates: false
download-at-startup-and-update: false

View file

@ -1 +1,56 @@
{} serverutils:
success: "&3Successfully %action%ed &b%what%&3!"
warning: "&3Successfully %action%ed &b%what%&3, but with warnings."
error: "&cAn error occurred while %action%ing &4%what%&c, please check the console!"
not_exists: "&cAn error occurred while %action%ing &4%what%&c, plugin does not exist!"
not_enabled: "&cAn error occurred while %action%ing &4%what%&c, plugin is not enabled!"
already_loaded: "&cAn error occurred while %action%ing &4%what%&c, plugin is already loaded!"
already_enabled: "&cAn error occurred while %action%ing &4%what%&c, plugin is already enabled!"
already_disabled: "&cAn error occurred while %action%ing &4%what%&c, plugin is already disabled!"
file_changed: "&cAccessing the jar file while %action%ing &4%what%&c went wrong, please load the plugin manually!"
invalid_description: "&cAn error occurred while %action%ing &4%what%&c, plugin doesn't have a valid description!"
invalid_plugin: "&cAn error occurred while %action%ing &4%what%&c, plugin is invalid!"
unknown_dependency: "&cAn error occurred while %action%ing &4%what%&c, plugin has a dependeny which is not loaded: &4%arg%"
update:
available: |-
&8&m------------=&r&8[ &b&lServerUtils Update&r &8]&m=--------------
&3Current version: &b%old%
&3New version: &b%new%
&3Release info: &b%info%
&8&m-------------------------------------------------
downloading: |-
&8&m------------=&r&8[ &b&lServerUtils Update&r &8]&m=--------------
&3A new version of ServerUtils will be downloaded and installed after a restart!
&3Current version: &b%old%
&3New version: &b%new%
&3Release info: &b%info%
&8&m-------------------------------------------------
download_failed: "&cFailed to download version %new% of ServerUtils. Please update manually."
download_success: "&3ServerUtils has been downloaded and will be installed on the next restart."
help:
header: "&8&m-------------=&r&8[ &b&lServerUtils Help&r &8]&m=---------------"
format: "&8/&3%command%&b%subcommand% &f(&7%help%&f)"
footer: "&8&m-------------------------------------------------"
plugins:
header: "&8&m------------=&r&8[ &b&lServerUtils Plugins&r &8]&m=-------------"
format: "&3%plugin%"
format_disabled: "&c%plugin%"
seperator: "&b, "
last_seperator: " &band "
version: " &8(&a%version%&8)"
footer: "&8&m-------------------------------------------------"
plugininfo:
header: "&8&m-----------=&r&8[ &b&lServerUtils PluginInfo&r &8]&m=-----------"
format: " &3%key%&8: &b%value%"
list_format: "&b%value%"
seperator: "&8, "
last_seperator: " &8and "
footer: "&8&m-------------------------------------------------"
commandinfo:
header: "&8&m-----------=&r&8[ &b&lServerUtils CommandInfo&r &8]&m=----------"
format: " &3%key%&8: &b%value%"
list_format: "&b%value%"
seperator: "&8, "
last_seperator: " &8and "
footer: "&8&m-------------------------------------------------"
not_exists: "&cThat command is not a valid registered command."