Merge branch 'master' of https://github.com/AuthMe-Team/AuthMeReloaded into playerjoin-listener-cleanup

This commit is contained in:
ljacqu 2016-05-30 17:53:42 +02:00
commit f5b4071abf
23 changed files with 148 additions and 87 deletions

View File

@ -29,7 +29,21 @@ public class AccountsCommand implements ExecutableCommand {
final String playerName = arguments.isEmpty() ? sender.getName() : arguments.get(0); final String playerName = arguments.isEmpty() ? sender.getName() : arguments.get(0);
// Assumption: a player name cannot contain '.' // Assumption: a player name cannot contain '.'
if (!playerName.contains(".")) { if (playerName.contains(".")) {
bukkitService.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
List<String> accountList = dataSource.getAllAuthsByIp(playerName);
if (accountList.isEmpty()) {
sender.sendMessage("[AuthMe] This IP does not exist in the database.");
} else if (accountList.size() == 1) {
sender.sendMessage("[AuthMe] " + playerName + " is a single account player");
} else {
outputAccountsList(sender, playerName, accountList);
}
}
});
} else {
bukkitService.runTaskAsynchronously(new Runnable() { bukkitService.runTaskAsynchronously(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -49,20 +63,6 @@ public class AccountsCommand implements ExecutableCommand {
} }
} }
}); });
} else {
bukkitService.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
List<String> accountList = dataSource.getAllAuthsByIp(playerName);
if (accountList.isEmpty()) {
sender.sendMessage("[AuthMe] This IP does not exist in the database.");
} else if (accountList.size() == 1) {
sender.sendMessage("[AuthMe] " + playerName + " is a single account player");
} else {
outputAccountsList(sender, playerName, accountList);
}
}
});
} }
} }

View File

@ -66,11 +66,11 @@ public class ChangePasswordAdminCommand implements ExecutableCommand {
HashedPassword hashedPassword = passwordSecurity.computeHash(playerPass, playerNameLowerCase); HashedPassword hashedPassword = passwordSecurity.computeHash(playerPass, playerNameLowerCase);
auth.setPassword(hashedPassword); auth.setPassword(hashedPassword);
if (!dataSource.updatePassword(auth)) { if (dataSource.updatePassword(auth)) {
commandService.send(sender, MessageKey.ERROR);
} else {
commandService.send(sender, MessageKey.PASSWORD_CHANGED_SUCCESS); commandService.send(sender, MessageKey.PASSWORD_CHANGED_SUCCESS);
ConsoleLogger.info(playerNameLowerCase + "'s password changed"); ConsoleLogger.info(playerNameLowerCase + "'s password changed");
} else {
commandService.send(sender, MessageKey.ERROR);
} }
} }

View File

@ -18,10 +18,10 @@ public class FirstSpawnCommand extends PlayerCommand {
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
if (spawnLoader.getFirstSpawn() != null) { if (spawnLoader.getFirstSpawn() == null) {
player.teleport(spawnLoader.getFirstSpawn());
} else {
player.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn"); player.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn");
} else {
player.teleport(spawnLoader.getFirstSpawn());
} }
} }
} }

View File

@ -15,10 +15,10 @@ public class SpawnCommand extends PlayerCommand {
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
if (spawnLoader.getSpawn() != null) { if (spawnLoader.getSpawn() == null) {
player.teleport(spawnLoader.getSpawn());
} else {
player.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn"); player.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn");
} else {
player.teleport(spawnLoader.getSpawn());
} }
} }
} }

View File

@ -181,15 +181,15 @@ public class AuthMeServiceInitializer {
Class<?>[] annotations = injection.getDependencyAnnotations(); Class<?>[] annotations = injection.getDependencyAnnotations();
Object[] values = new Object[dependencies.length]; Object[] values = new Object[dependencies.length];
for (int i = 0; i < dependencies.length; ++i) { for (int i = 0; i < dependencies.length; ++i) {
if (annotations[i] != null) { if (annotations[i] == null) {
values[i] = get(dependencies[i], traversedClasses);
} else {
Object value = objects.get(annotations[i]); Object value = objects.get(annotations[i]);
if (value == null) { if (value == null) {
throw new IllegalStateException("Value for field with @" + annotations[i].getSimpleName() throw new IllegalStateException("Value for field with @" + annotations[i].getSimpleName()
+ " must be registered beforehand"); + " must be registered beforehand");
} }
values[i] = value; values[i] = value;
} else {
values[i] = get(dependencies[i], traversedClasses);
} }
} }
return values; return values;

View File

@ -68,12 +68,12 @@ public class AsynchronousLogin implements AsynchronousProcess {
private boolean needsCaptcha(Player player) { private boolean needsCaptcha(Player player) {
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
if (service.getProperty(SecuritySettings.USE_CAPTCHA)) { if (service.getProperty(SecuritySettings.USE_CAPTCHA)) {
if (!plugin.captcha.containsKey(name)) { if (plugin.captcha.containsKey(name)) {
plugin.captcha.putIfAbsent(name, 1);
} else {
int i = plugin.captcha.get(name) + 1; int i = plugin.captcha.get(name) + 1;
plugin.captcha.remove(name); plugin.captcha.remove(name);
plugin.captcha.putIfAbsent(name, i); plugin.captcha.putIfAbsent(name, i);
} else {
plugin.captcha.putIfAbsent(name, 1);
} }
if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) > Settings.maxLoginTry) { if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) > Settings.maxLoginTry) {
plugin.cap.putIfAbsent(name, RandomString.generate(Settings.captchaLength)); plugin.cap.putIfAbsent(name, RandomString.generate(Settings.captchaLength));

View File

@ -1,7 +1,3 @@
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
package fr.xephi.authme.security.crypts; package fr.xephi.authme.security.crypts;
import fr.xephi.authme.security.HashUtils; import fr.xephi.authme.security.HashUtils;
@ -24,7 +20,7 @@ public class PHPBB extends HexSaltedMethod {
byte[] hash = md5er.digest(bytes); byte[] hash = md5er.digest(bytes);
return bytes2hex(hash); return bytes2hex(hash);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); throw new UnsupportedOperationException(e);
} }
} }

View File

@ -24,7 +24,7 @@ class EnumProperty<E extends Enum<E>> extends Property<E> {
return getDefaultValue(); return getDefaultValue();
} }
E mappedValue = mapToEnum(textValue); E mappedValue = mapToEnum(textValue);
return mappedValue != null ? mappedValue : getDefaultValue(); return mappedValue == null ? getDefaultValue() : mappedValue;
} }
@Override @Override

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.settings.domain;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@ -33,6 +34,17 @@ public abstract class Property<T> {
return new StringListProperty(path, defaultValues); return new StringListProperty(path, defaultValues);
} }
/**
* Create a new String list property where all values are lowercase.
*
* @param path The property's path
* @param defaultValues The items in the default list
* @return The created list property
*/
public static Property<List<String>> newLowercaseListProperty(String path, String... defaultValues) {
return new LowercaseStringListProperty(path, defaultValues);
}
/** /**
* Create a new enum property. * Create a new enum property.
* *
@ -165,7 +177,7 @@ public abstract class Property<T> {
/** /**
* String list property. * String list property.
*/ */
private static final class StringListProperty extends Property<List<String>> { private static class StringListProperty extends Property<List<String>> {
public StringListProperty(String path, String[] defaultValues) { public StringListProperty(String path, String[] defaultValues) {
super(path, Arrays.asList(defaultValues)); super(path, Arrays.asList(defaultValues));
@ -196,4 +208,28 @@ public abstract class Property<T> {
} }
} }
/**
* Lowercase String list property.
*/
private static final class LowercaseStringListProperty extends StringListProperty {
public LowercaseStringListProperty(String path, String[] defaultValues) {
super(path, defaultValues);
}
@Override
public List<String> getFromFile(FileConfiguration configuration) {
if (!configuration.isList(getPath())) {
return getDefaultValue();
}
// make sure all elements are lowercase
List<String> lowercaseList = new ArrayList<>();
for (String element : configuration.getStringList(getPath())) {
lowercaseList.add(element.toLowerCase());
}
return lowercaseList;
}
}
} }

View File

@ -7,6 +7,7 @@ import fr.xephi.authme.settings.domain.SettingsClass;
import java.util.List; import java.util.List;
import static fr.xephi.authme.settings.domain.Property.newListProperty; import static fr.xephi.authme.settings.domain.Property.newListProperty;
import static fr.xephi.authme.settings.domain.Property.newLowercaseListProperty;
import static fr.xephi.authme.settings.domain.Property.newProperty; import static fr.xephi.authme.settings.domain.Property.newProperty;
public class RestrictionSettings implements SettingsClass { public class RestrictionSettings implements SettingsClass {
@ -24,7 +25,7 @@ public class RestrictionSettings implements SettingsClass {
@Comment("Allowed commands for unauthenticated players") @Comment("Allowed commands for unauthenticated players")
public static final Property<List<String>> ALLOW_COMMANDS = public static final Property<List<String>> ALLOW_COMMANDS =
newListProperty("settings.restrictions.allowCommands", newLowercaseListProperty("settings.restrictions.allowCommands",
"/login", "/register", "/l", "/reg", "/email", "/captcha"); "/login", "/register", "/l", "/reg", "/email", "/captcha");
@Comment({ @Comment({
@ -81,7 +82,7 @@ public class RestrictionSettings implements SettingsClass {
" AllowedRestrictedUser:", " AllowedRestrictedUser:",
" - playername;127.0.0.1"}) " - playername;127.0.0.1"})
public static final Property<List<String>> ALLOWED_RESTRICTED_USERS = public static final Property<List<String>> ALLOWED_RESTRICTED_USERS =
newListProperty("settings.restrictions.AllowedRestrictedUser"); newLowercaseListProperty("settings.restrictions.AllowedRestrictedUser");
@Comment("Should unregistered players be kicked immediately?") @Comment("Should unregistered players be kicked immediately?")
public static final Property<Boolean> KICK_NON_REGISTERED = public static final Property<Boolean> KICK_NON_REGISTERED =
@ -188,7 +189,7 @@ public class RestrictionSettings implements SettingsClass {
"It is case-sensitive!" "It is case-sensitive!"
}) })
public static final Property<List<String>> UNRESTRICTED_NAMES = public static final Property<List<String>> UNRESTRICTED_NAMES =
newListProperty("settings.unrestrictions.UnrestrictedName"); newLowercaseListProperty("settings.unrestrictions.UnrestrictedName");
private RestrictionSettings() { private RestrictionSettings() {

View File

@ -8,6 +8,7 @@ import fr.xephi.authme.settings.domain.SettingsClass;
import java.util.List; import java.util.List;
import static fr.xephi.authme.settings.domain.Property.newListProperty; import static fr.xephi.authme.settings.domain.Property.newListProperty;
import static fr.xephi.authme.settings.domain.Property.newLowercaseListProperty;
import static fr.xephi.authme.settings.domain.Property.newProperty; import static fr.xephi.authme.settings.domain.Property.newProperty;
public class SecuritySettings implements SettingsClass { public class SecuritySettings implements SettingsClass {
@ -98,7 +99,7 @@ public class SecuritySettings implements SettingsClass {
"- '123456'", "- '123456'",
"- 'password'"}) "- 'password'"})
public static final Property<List<String>> UNSAFE_PASSWORDS = public static final Property<List<String>> UNSAFE_PASSWORDS =
newListProperty("settings.security.unsafePasswords", "123456", "password", "qwerty", "12345", "54321"); newLowercaseListProperty("settings.security.unsafePasswords", "123456", "password", "qwerty", "12345", "54321");
private SecuritySettings() { private SecuritySettings() {
} }

View File

@ -158,7 +158,7 @@ public class BukkitService {
} else if (obj instanceof Player[]) { } else if (obj instanceof Player[]) {
return Arrays.asList((Player[]) obj); return Arrays.asList((Player[]) obj);
} else { } else {
String type = (obj != null) ? obj.getClass().getName() : "null"; String type = (obj == null) ? "null" : obj.getClass().getName();
ConsoleLogger.showError("Unknown list of online players of type " + type); ConsoleLogger.showError("Unknown list of online players of type " + type);
} }
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {

View File

@ -27,7 +27,7 @@ public final class ReflectionTestUtils {
Field field = getField(clazz, instance, fieldName); Field field = getField(clazz, instance, fieldName);
field.set(instance, value); field.set(instance, value);
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException( throw new UnsupportedOperationException(
format("Could not set value to field '%s' for instance '%s' of class '%s'", format("Could not set value to field '%s' for instance '%s' of class '%s'",
fieldName, instance, clazz.getName()), e); fieldName, instance, clazz.getName()), e);
} }
@ -39,7 +39,7 @@ public final class ReflectionTestUtils {
field.setAccessible(true); field.setAccessible(true);
return field; return field;
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
throw new RuntimeException(format("Could not get field '%s' for instance '%s' of class '%s'", throw new UnsupportedOperationException(format("Could not get field '%s' for instance '%s' of class '%s'",
fieldName, instance, clazz.getName()), e); fieldName, instance, clazz.getName()), e);
} }
} }
@ -50,7 +50,7 @@ public final class ReflectionTestUtils {
try { try {
return field.get(instance); return field.get(instance);
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException("Could not get value of field '" + fieldName + "'"); throw new UnsupportedOperationException("Could not get value of field '" + fieldName + "'");
} }
} }
@ -69,7 +69,7 @@ public final class ReflectionTestUtils {
method.setAccessible(true); method.setAccessible(true);
return method; return method;
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
throw new RuntimeException("Could not retrieve method '" + methodName + "' from class '" throw new UnsupportedOperationException("Could not retrieve method '" + methodName + "' from class '"
+ clazz.getName() + "'"); + clazz.getName() + "'");
} }
} }

View File

@ -22,6 +22,7 @@ import static fr.xephi.authme.permission.DefaultPermission.OP_ONLY;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
@ -187,12 +188,12 @@ public class CommandInitializerTest {
assertThat(command.getExecutableCommand(), not(nullValue())); assertThat(command.getExecutableCommand(), not(nullValue()));
ExecutableCommand commandExec = command.getExecutableCommand(); ExecutableCommand commandExec = command.getExecutableCommand();
ExecutableCommand storedExec = implementations.get(command.getExecutableCommand().getClass()); ExecutableCommand storedExec = implementations.get(command.getExecutableCommand().getClass());
if (storedExec != null) { if (storedExec == null) {
assertThat("has same implementation of '" + storedExec.getClass().getName() + "' for command with "
+ "parent " + (command.getParent() == null ? "null" : command.getParent().getLabels()),
storedExec == commandExec, equalTo(true));
} else {
implementations.put(commandExec.getClass(), commandExec); implementations.put(commandExec.getClass(), commandExec);
} else {
assertSame("has same implementation of '" + storedExec.getClass().getName() + "' for command with "
+ "parent " + (command.getParent() == null ? "null" : command.getParent().getLabels()),
storedExec, commandExec);
} }
} }
}; };
@ -211,7 +212,7 @@ public class CommandInitializerTest {
for (CommandArgumentDescription argument : command.getArguments()) { for (CommandArgumentDescription argument : command.getArguments()) {
if (argument.isOptional()) { if (argument.isOptional()) {
encounteredOptionalArg = true; encounteredOptionalArg = true;
} else if (!argument.isOptional() && encounteredOptionalArg) { } else if (encounteredOptionalArg) {
fail("Mandatory arguments should come before optional ones for command with labels '" fail("Mandatory arguments should come before optional ones for command with labels '"
+ command.getLabels() + "'"); + command.getLabels() + "'");
} }
@ -256,11 +257,10 @@ public class CommandInitializerTest {
@Override @Override
public void accept(CommandDescription command, int depth) { public void accept(CommandDescription command, int depth) {
CommandPermissions permissions = command.getCommandPermissions(); CommandPermissions permissions = command.getCommandPermissions();
if (permissions != null && OP_ONLY.equals(permissions.getDefaultPermission())) { if (permissions != null && OP_ONLY.equals(permissions.getDefaultPermission())
if (!hasAdminNode(permissions)) { && !hasAdminNode(permissions)) {
fail("The command with labels " + command.getLabels() + " has OP_ONLY default " fail("The command with labels " + command.getLabels() + " has OP_ONLY default "
+ "permission but no permission node on admin level"); + "permission but no permission node on admin level");
}
} }
} }
@ -298,13 +298,13 @@ public class CommandInitializerTest {
Map<Class<? extends ExecutableCommand>, Integer> collection) { Map<Class<? extends ExecutableCommand>, Integer> collection) {
final Class<? extends ExecutableCommand> clazz = command.getExecutableCommand().getClass(); final Class<? extends ExecutableCommand> clazz = command.getExecutableCommand().getClass();
Integer existingCount = collection.get(clazz); Integer existingCount = collection.get(clazz);
if (existingCount != null) { if (existingCount == null) {
collection.put(clazz, argCount);
} else {
String commandDescription = "Command with label '" + command.getLabels().get(0) + "' and parent '" String commandDescription = "Command with label '" + command.getLabels().get(0) + "' and parent '"
+ (command.getParent() != null ? command.getLabels().get(0) : "null") + "' "; + (command.getParent() == null ? "null" : command.getLabels().get(0)) + "' ";
assertThat(commandDescription + "should point to " + clazz + " with arguments consistent to others", assertThat(commandDescription + "should point to " + clazz + " with arguments consistent to others",
argCount, equalTo(existingCount)); argCount, equalTo(existingCount));
} else {
collection.put(clazz, argCount);
} }
} }
}; };

View File

@ -6,7 +6,6 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -52,7 +51,7 @@ public class CommandMapperTest {
@Test @Test
public void shouldMapPartsToLoginChildCommand() { public void shouldMapPartsToLoginChildCommand() {
// given // given
List<String> parts = Arrays.asList("authme", "login", "test1"); List<String> parts = asList("authme", "login", "test1");
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true); given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true);
@ -71,7 +70,7 @@ public class CommandMapperTest {
@Test @Test
public void shouldMapPartsToCommandWithNoCaseSensitivity() { public void shouldMapPartsToCommandWithNoCaseSensitivity() {
// given // given
List<String> parts = Arrays.asList("Authme", "REG", "arg1", "arg2"); List<String> parts = asList("Authme", "REG", "arg1", "arg2");
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true); given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true);
@ -89,7 +88,7 @@ public class CommandMapperTest {
@Test @Test
public void shouldRejectCommandWithTooManyArguments() { public void shouldRejectCommandWithTooManyArguments() {
// given // given
List<String> parts = Arrays.asList("authme", "register", "pass123", "pass123", "pass123"); List<String> parts = asList("authme", "register", "pass123", "pass123", "pass123");
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true); given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true);
@ -107,7 +106,7 @@ public class CommandMapperTest {
@Test @Test
public void shouldRejectCommandWithTooFewArguments() { public void shouldRejectCommandWithTooFewArguments() {
// given // given
List<String> parts = Arrays.asList("authme", "Reg"); List<String> parts = asList("authme", "Reg");
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true); given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true);
@ -125,7 +124,7 @@ public class CommandMapperTest {
@Test @Test
public void shouldSuggestCommandWithSimilarLabel() { public void shouldSuggestCommandWithSimilarLabel() {
// given // given
List<String> parts = Arrays.asList("authme", "reh", "pass123", "pass123"); List<String> parts = asList("authme", "reh", "pass123", "pass123");
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true); given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true);
@ -144,7 +143,7 @@ public class CommandMapperTest {
@Test @Test
public void shouldSuggestMostSimilarCommand() { public void shouldSuggestMostSimilarCommand() {
// given // given
List<String> parts = Arrays.asList("authme", "asdfawetawty4asdca"); List<String> parts = asList("authme", "asdfawetawty4asdca");
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true); given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(true);
@ -259,7 +258,7 @@ public class CommandMapperTest {
@Test @Test
public void shouldRecognizeMissingPermissionForCommand() { public void shouldRecognizeMissingPermissionForCommand() {
// given // given
List<String> parts = Arrays.asList("authme", "login", "test1"); List<String> parts = asList("authme", "login", "test1");
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(false); given(permissionsManager.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(false);

View File

@ -85,11 +85,11 @@ public final class TestCommandsUtil {
private static CommandDescription createCommand(PermissionNode permission, CommandDescription parent, private static CommandDescription createCommand(PermissionNode permission, CommandDescription parent,
List<String> labels, CommandArgumentDescription... arguments) { List<String> labels, CommandArgumentDescription... arguments) {
PermissionNode[] notNullPermission; PermissionNode[] notNullPermission;
if (permission != null) { if (permission == null) {
notNullPermission = new PermissionNode[0];
} else {
notNullPermission = new PermissionNode[1]; notNullPermission = new PermissionNode[1];
notNullPermission[0] = permission; notNullPermission[0] = permission;
} else {
notNullPermission = new PermissionNode[0];
} }
CommandDescription.CommandBuilder command = CommandDescription.builder() CommandDescription.CommandBuilder command = CommandDescription.builder()

View File

@ -73,13 +73,13 @@ public class PasswordSecurityTest {
Object[] arguments = invocation.getArguments(); Object[] arguments = invocation.getArguments();
if (arguments[0] instanceof PasswordEncryptionEvent) { if (arguments[0] instanceof PasswordEncryptionEvent) {
PasswordEncryptionEvent event = (PasswordEncryptionEvent) arguments[0]; PasswordEncryptionEvent event = (PasswordEncryptionEvent) arguments[0];
caughtClassInEvent = event.getMethod() != null ? event.getMethod().getClass() : null; caughtClassInEvent = event.getMethod() == null ? null : event.getMethod().getClass();
event.setMethod(method); event.setMethod(method);
} }
return null; return null;
} }
}).when(pluginManager).callEvent(any(Event.class)); }).when(pluginManager).callEvent(any(Event.class));
initializer = new AuthMeServiceInitializer(new String[]{}); initializer = new AuthMeServiceInitializer();
initializer.register(NewSetting.class, settings); initializer.register(NewSetting.class, settings);
initializer.register(DataSource.class, dataSource); initializer.register(DataSource.class, dataSource);
initializer.register(PluginManager.class, pluginManager); initializer.register(PluginManager.class, pluginManager);

View File

@ -152,7 +152,7 @@ public abstract class AbstractEncryptionMethodTest {
* *
* @param method The method to create a test class for * @param method The method to create a test class for
*/ */
static void generateTest(EncryptionMethod method) { protected static void generateTest(EncryptionMethod method) {
String className = method.getClass().getSimpleName(); String className = method.getClass().getSimpleName();
// Create javadoc and "public class extends" and the constructor call "super(new Class()," // Create javadoc and "public class extends" and the constructor call "super(new Class(),"
System.out.println("/**\n * Test for {@link " + className + "}.\n */"); System.out.println("/**\n * Test for {@link " + className + "}.\n */");

View File

@ -38,6 +38,9 @@ public class PropertyTest {
when(configuration.isList("list.path.test")).thenReturn(true); when(configuration.isList("list.path.test")).thenReturn(true);
when(configuration.getStringList("list.path.test")).thenReturn(Arrays.asList("test1", "Test2", "3rd test")); when(configuration.getStringList("list.path.test")).thenReturn(Arrays.asList("test1", "Test2", "3rd test"));
when(configuration.isList("list.path.wrong")).thenReturn(false); when(configuration.isList("list.path.wrong")).thenReturn(false);
when(configuration.isList("lowercaselist.path.test")).thenReturn(true);
when(configuration.getStringList("lowercaselist.path.test")).thenReturn(Arrays.asList("test1", "Test2", "3rd test"));
when(configuration.isList("lowercaselist.path.wrong")).thenReturn(false);
} }
/* Boolean */ /* Boolean */
@ -141,4 +144,29 @@ public class PropertyTest {
assertThat(result, contains("default", "list", "elements")); assertThat(result, contains("default", "list", "elements"));
} }
/* Lowercase String list */
@Test
public void shouldGetLowercaseStringListValue() {
// given
Property<List<String>> property = Property.newLowercaseListProperty("lowercaselist.path.test", "1", "b");
// when
List<String> result = property.getFromFile(configuration);
// then
assertThat(result, contains("test1", "test2", "3rd test"));
}
@Test
public void shouldGetLowercaseStringListDefault() {
// given
Property<List<String>> property =
Property.newLowercaseListProperty("lowercaselist.path.wrong", "default", "list", "elements");
// when
List<String> result = property.getFromFile(configuration);
// then
assertThat(result, contains("default", "list", "elements"));
}
} }

View File

@ -62,10 +62,10 @@ public final class ToolsRunner {
ToolTask task = tasks.get(taskName); ToolTask task = tasks.get(taskName);
if (task == null) { if (task == null) {
System.out.format("Unknown task '%s'%n", taskName); System.out.format("Unknown task '%s'%n", taskName);
} else if (!(task instanceof AutoToolTask)) { } else if (task instanceof AutoToolTask) {
System.out.format("Task '%s' cannot be run on command line%n", taskName);
} else {
((AutoToolTask) task).executeDefault(); ((AutoToolTask) task).executeDefault();
} else {
System.out.format("Task '%s' cannot be run on command line%n", taskName);
} }
} }
} }

View File

@ -133,7 +133,7 @@ public final class VerifyMessagesTask implements ToolTask {
File folder = new File(MESSAGES_FOLDER); File folder = new File(MESSAGES_FOLDER);
File[] files = folder.listFiles(); File[] files = folder.listFiles();
if (files == null) { if (files == null) {
throw new RuntimeException("Could not read files from folder '" + folder.getName() + "'"); throw new IllegalStateException("Could not read files from folder '" + folder.getName() + "'");
} }
List<File> messageFiles = new ArrayList<>(); List<File> messageFiles = new ArrayList<>();
@ -143,7 +143,7 @@ public final class VerifyMessagesTask implements ToolTask {
} }
} }
if (messageFiles.isEmpty()) { if (messageFiles.isEmpty()) {
throw new RuntimeException("Error getting message files: list of files is empty"); throw new IllegalStateException("Error getting message files: list of files is empty");
} }
return messageFiles; return messageFiles;
} }

View File

@ -27,7 +27,7 @@ public final class FileUtils {
try { try {
Files.write(Paths.get(outputFile), contents.getBytes()); Files.write(Paths.get(outputFile), contents.getBytes());
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to write to file '" + outputFile + "'", e); throw new UnsupportedOperationException("Failed to write to file '" + outputFile + "'", e);
} }
} }
@ -35,7 +35,7 @@ public final class FileUtils {
try { try {
Files.write(Paths.get(outputFile), contents.getBytes(), StandardOpenOption.APPEND); Files.write(Paths.get(outputFile), contents.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to append to file '" + outputFile + "'", e); throw new UnsupportedOperationException("Failed to append to file '" + outputFile + "'", e);
} }
} }
@ -43,7 +43,7 @@ public final class FileUtils {
try { try {
return new String(Files.readAllBytes(Paths.get(file)), CHARSET); return new String(Files.readAllBytes(Paths.get(file)), CHARSET);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Could not read from file '" + file + "'", e); throw new UnsupportedOperationException("Could not read from file '" + file + "'", e);
} }
} }
@ -51,7 +51,7 @@ public final class FileUtils {
try { try {
return Files.readAllLines(Paths.get(file), CHARSET); return Files.readAllLines(Paths.get(file), CHARSET);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Could not read from file '" + file + "'", e); throw new UnsupportedOperationException("Could not read from file '" + file + "'", e);
} }
} }

View File

@ -5,9 +5,6 @@ package tools.utils;
*/ */
public final class ToolsConstants { public final class ToolsConstants {
private ToolsConstants() {
}
public static final String MAIN_SOURCE_ROOT = "src/main/java/"; public static final String MAIN_SOURCE_ROOT = "src/main/java/";
public static final String MAIN_RESOURCES_ROOT = "src/main/resources/"; public static final String MAIN_RESOURCES_ROOT = "src/main/resources/";
@ -21,4 +18,7 @@ public final class ToolsConstants {
public static final String DOCS_FOLDER_URL = "https://github.com/AuthMe-Team/AuthMeReloaded/tree/master/docs/"; public static final String DOCS_FOLDER_URL = "https://github.com/AuthMe-Team/AuthMeReloaded/tree/master/docs/";
private ToolsConstants() {
}
} }