From 32a664ef59edb61ae2dca51666859a8941c49c41 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 23 Mar 2017 10:34:28 +0100 Subject: [PATCH] Update checkstyle config and CodeClimate exclusions - Add new checkstyle checks: require Javadoc on large private methods, default in switch, declaration order & others - Update path exclusions in CodeClimate config to match newly renamed classes (e.g. PHPBB -> PhpBB) - Create consistency check testing that excluded paths exist as classes - Fix some trivial violations --- .checkstyle.xml | 20 +++++++- .codeclimate.yml | 6 +-- src/main/java/fr/xephi/authme/api/NewAPI.java | 3 +- .../authme/command/CommandInitializer.java | 4 ++ .../executable/authme/VersionCommand.java | 6 +-- .../authme/debug/TestEmailSender.java | 10 ++-- .../command/help/HelpMessagesService.java | 4 +- .../fr/xephi/authme/datasource/MySQL.java | 32 ++++++------ .../converter/RakamakConverter.java | 6 +-- .../fr/xephi/authme/mail/EmailService.java | 16 +++--- .../{SendMailSSL.java => SendMailSsl.java} | 4 +- .../authme/permission/AuthGroupHandler.java | 4 +- .../authme/permission/PermissionsManager.java | 11 +++- .../handlers/PermissionHandler.java | 8 +-- .../process/login/AsynchronousLogin.java | 1 + .../AbstractPasswordRegisterExecutor.java | 2 + .../executors/RegistrationExecutor.java | 2 + .../executors/RegistrationMethod.java | 2 + .../xephi/authme/service/BukkitService.java | 7 +-- .../authme/settings/EnumSetProperty.java | 2 + .../authme/util/expiring/TimedCounter.java | 5 +- .../xephi/authme/CodeClimateConfigTest.java | 51 +++++++++++++++++++ .../command/executable/HelpCommandTest.java | 2 +- .../debug/DebugSectionConsistencyTest.java | 5 +- .../xephi/authme/mail/EmailServiceTest.java | 48 ++++++++--------- ...dMailSSLTest.java => SendMailSslTest.java} | 14 ++--- .../settings/SettingsConsistencyTest.java | 3 +- 27 files changed, 185 insertions(+), 93 deletions(-) rename src/main/java/fr/xephi/authme/mail/{SendMailSSL.java => SendMailSsl.java} (98%) create mode 100644 src/test/java/fr/xephi/authme/CodeClimateConfigTest.java rename src/test/java/fr/xephi/authme/mail/{SendMailSSLTest.java => SendMailSslTest.java} (94%) diff --git a/.checkstyle.xml b/.checkstyle.xml index 8b8b4969..00141bd6 100644 --- a/.checkstyle.xml +++ b/.checkstyle.xml @@ -55,7 +55,9 @@ + + @@ -111,9 +113,11 @@ + + @@ -145,9 +149,21 @@ - - + + + + + + + + + arguments) { - if (!sendMailSSL.hasAllInformation()) { + if (!sendMailSsl.hasAllInformation()) { sender.sendMessage(ChatColor.RED + "You haven't set all required configurations in config.yml " + "for sending emails. Please check your config.yml"); return; @@ -87,7 +87,7 @@ class TestEmailSender implements DebugSection { private boolean sendTestEmail(String email) { HtmlEmail htmlEmail; try { - htmlEmail = sendMailSSL.initializeMail(email); + htmlEmail = sendMailSsl.initializeMail(email); } catch (EmailException e) { ConsoleLogger.logException("Failed to create email for sample email:", e); return false; @@ -96,6 +96,6 @@ class TestEmailSender implements DebugSection { htmlEmail.setSubject("AuthMe test email"); String message = "Hello there!
This is a sample email sent to you from a Minecraft server (" + server.getName() + ") via /authme debug mail. If you're seeing this, sending emails should be fine."; - return sendMailSSL.sendEmail(message, htmlEmail); + return sendMailSsl.sendEmail(message, htmlEmail); } } diff --git a/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java b/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java index c2cbaff9..7058c0cb 100644 --- a/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java +++ b/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java @@ -81,8 +81,8 @@ public class HelpMessagesService implements Reloadable { public String getMessage(DefaultPermission defaultPermission) { // e.g. {default_permissions_path}.opOnly for DefaultPermission.OP_ONLY - String path = DEFAULT_PERMISSIONS_PATH + - CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, defaultPermission.name()); + String path = DEFAULT_PERMISSIONS_PATH + + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, defaultPermission.name()); return messageFileHandler.getMessage(path); } diff --git a/src/main/java/fr/xephi/authme/datasource/MySQL.java b/src/main/java/fr/xephi/authme/datasource/MySQL.java index 4e6937d4..6e09b585 100644 --- a/src/main/java/fr/xephi/authme/datasource/MySQL.java +++ b/src/main/java/fr/xephi/authme/datasource/MySQL.java @@ -31,7 +31,7 @@ import java.util.Set; public class MySQL implements DataSource { - private boolean useSSL; + private boolean useSsl; private String host; private String port; private String username; @@ -45,10 +45,10 @@ public class MySQL implements DataSource { private HikariDataSource ds; private String phpBbPrefix; - private String IPBPrefix; + private String ipbPrefix; private int phpBbGroup; - private int IPBGroup; - private int XFGroup; + private int ipbGroup; + private int xfGroup; private String wordpressPrefix; public MySQL(Settings settings) throws ClassNotFoundException, SQLException { @@ -99,15 +99,15 @@ public class MySQL implements DataSource { this.hashAlgorithm = settings.getProperty(SecuritySettings.PASSWORD_HASH); this.phpBbPrefix = settings.getProperty(HooksSettings.PHPBB_TABLE_PREFIX); this.phpBbGroup = settings.getProperty(HooksSettings.PHPBB_ACTIVATED_GROUP_ID); - this.IPBPrefix = settings.getProperty(HooksSettings.IPB_TABLE_PREFIX); - this.IPBGroup = settings.getProperty(HooksSettings.IPB_ACTIVATED_GROUP_ID); - this.XFGroup = settings.getProperty(HooksSettings.XF_ACTIVATED_GROUP_ID); + this.ipbPrefix = settings.getProperty(HooksSettings.IPB_TABLE_PREFIX); + this.ipbGroup = settings.getProperty(HooksSettings.IPB_ACTIVATED_GROUP_ID); + this.xfGroup = settings.getProperty(HooksSettings.XF_ACTIVATED_GROUP_ID); this.wordpressPrefix = settings.getProperty(HooksSettings.WORDPRESS_TABLE_PREFIX); this.poolSize = settings.getProperty(DatabaseSettings.MYSQL_POOL_SIZE); if (poolSize == -1) { poolSize = Utils.getCoreCount()*3; } - this.useSSL = settings.getProperty(DatabaseSettings.MYSQL_USE_SSL); + this.useSsl = settings.getProperty(DatabaseSettings.MYSQL_USE_SSL); } private void setConnectionArguments() { @@ -125,7 +125,7 @@ public class MySQL implements DataSource { ds.setPassword(this.password); // Request mysql over SSL - ds.addDataSourceProperty("useSSL", useSSL); + ds.addDataSourceProperty("useSSL", useSsl); // Encoding ds.addDataSourceProperty("characterEncoding", "utf8"); @@ -347,23 +347,23 @@ public class MySQL implements DataSource { rs = pst.executeQuery(); if (rs.next()){ // Update player group in core_members - sql = "UPDATE " + IPBPrefix + tableName + " SET "+ tableName + ".member_group_id=? WHERE " + col.NAME + "=?;"; + sql = "UPDATE " + ipbPrefix + tableName + " SET "+ tableName + ".member_group_id=? WHERE " + col.NAME + "=?;"; pst2 = con.prepareStatement(sql); - pst2.setInt(1, IPBGroup); + pst2.setInt(1, ipbGroup); pst2.setString(2, auth.getNickname()); pst2.executeUpdate(); pst2.close(); // Get current time without ms long time = System.currentTimeMillis() / 1000; // update joined date - sql = "UPDATE " + IPBPrefix + tableName + " SET "+ tableName + ".joined=? WHERE " + col.NAME + "=?;"; + sql = "UPDATE " + ipbPrefix + tableName + " SET "+ tableName + ".joined=? WHERE " + col.NAME + "=?;"; pst2 = con.prepareStatement(sql); pst2.setLong(1, time); pst2.setString(2, auth.getNickname()); pst2.executeUpdate(); pst2.close(); // Update last_visit - sql = "UPDATE " + IPBPrefix + tableName + " SET " + tableName + ".last_visit=? WHERE " + col.NAME + "=?;"; + sql = "UPDATE " + ipbPrefix + tableName + " SET " + tableName + ".last_visit=? WHERE " + col.NAME + "=?;"; pst2 = con.prepareStatement(sql); pst2.setLong(1, time); pst2.setString(2, auth.getNickname()); @@ -531,14 +531,14 @@ public class MySQL implements DataSource { // Update player group in xf_users sql = "UPDATE " + tableName + " SET "+ tableName + ".user_group_id=? WHERE " + col.NAME + "=?;"; pst2 = con.prepareStatement(sql); - pst2.setInt(1, XFGroup); + pst2.setInt(1, xfGroup); pst2.setString(2, auth.getNickname()); pst2.executeUpdate(); pst2.close(); // Update player permission combination in xf_users sql = "UPDATE " + tableName + " SET "+ tableName + ".permission_combination_id=? WHERE " + col.NAME + "=?;"; pst2 = con.prepareStatement(sql); - pst2.setInt(1, XFGroup); + pst2.setInt(1, xfGroup); pst2.setString(2, auth.getNickname()); pst2.executeUpdate(); pst2.close(); @@ -557,7 +557,7 @@ public class MySQL implements DataSource { sql = "INSERT INTO xf_user_group_relation (user_id, user_group_id, is_primary) VALUES (?,?,?)"; pst2 = con.prepareStatement(sql); pst2.setInt(1, id); - pst2.setInt(2, XFGroup); + pst2.setInt(2, xfGroup); pst2.setString(3, "1"); pst2.executeUpdate(); pst2.close(); diff --git a/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java b/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java index 42a8ecf1..4257f0aa 100644 --- a/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java +++ b/src/main/java/fr/xephi/authme/datasource/converter/RakamakConverter.java @@ -46,7 +46,7 @@ public class RakamakConverter implements Converter { String ipFileName = settings.getProperty(ConverterSettings.RAKAMAK_IP_FILE_NAME); File source = new File(pluginFolder, fileName); File ipFiles = new File(pluginFolder, ipFileName); - Map playerIP = new HashMap<>(); + Map playerIp = new HashMap<>(); Map playerPassword = new HashMap<>(); try { BufferedReader ipFile = new BufferedReader(new FileReader(ipFiles)); @@ -56,7 +56,7 @@ public class RakamakConverter implements Converter { while ((tempLine = ipFile.readLine()) != null) { if (tempLine.contains("=")) { String[] args = tempLine.split("="); - playerIP.put(args[0], args[1]); + playerIp.put(args[0], args[1]); } } } @@ -75,7 +75,7 @@ public class RakamakConverter implements Converter { for (Entry m : playerPassword.entrySet()) { String playerName = m.getKey(); HashedPassword psw = playerPassword.get(playerName); - String ip = useIp ? playerIP.get(playerName) : "127.0.0.1"; + String ip = useIp ? playerIp.get(playerName) : "127.0.0.1"; PlayerAuth auth = PlayerAuth.builder() .name(playerName) .realName(playerName) diff --git a/src/main/java/fr/xephi/authme/mail/EmailService.java b/src/main/java/fr/xephi/authme/mail/EmailService.java index cb7c86de..5eb588d1 100644 --- a/src/main/java/fr/xephi/authme/mail/EmailService.java +++ b/src/main/java/fr/xephi/authme/mail/EmailService.java @@ -25,18 +25,18 @@ public class EmailService { private final File dataFolder; private final String serverName; private final Settings settings; - private final SendMailSSL sendMailSSL; + private final SendMailSsl sendMailSsl; @Inject - EmailService(@DataFolder File dataFolder, Server server, Settings settings, SendMailSSL sendMailSSL) { + EmailService(@DataFolder File dataFolder, Server server, Settings settings, SendMailSsl sendMailSsl) { this.dataFolder = dataFolder; this.serverName = server.getServerName(); this.settings = settings; - this.sendMailSSL = sendMailSSL; + this.sendMailSsl = sendMailSsl; } public boolean hasAllInformation() { - return sendMailSSL.hasAllInformation(); + return sendMailSsl.hasAllInformation(); } @@ -56,7 +56,7 @@ public class EmailService { HtmlEmail email; try { - email = sendMailSSL.initializeMail(mailAddress); + email = sendMailSsl.initializeMail(mailAddress); } catch (EmailException e) { ConsoleLogger.logException("Failed to create email with the given settings:", e); return false; @@ -75,7 +75,7 @@ public class EmailService { } } - boolean couldSendEmail = sendMailSSL.sendEmail(mailText, email); + boolean couldSendEmail = sendMailSsl.sendEmail(mailText, email); FileUtils.delete(file); return couldSendEmail; } @@ -83,7 +83,7 @@ public class EmailService { public boolean sendRecoveryCode(String name, String email, String code) { HtmlEmail htmlEmail; try { - htmlEmail = sendMailSSL.initializeMail(email); + htmlEmail = sendMailSsl.initializeMail(email); } catch (EmailException e) { ConsoleLogger.logException("Failed to create email for recovery code:", e); return false; @@ -91,7 +91,7 @@ public class EmailService { String message = replaceTagsForRecoveryCodeMail(settings.getRecoveryCodeEmailMessage(), name, code, settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)); - return sendMailSSL.sendEmail(message, htmlEmail); + return sendMailSsl.sendEmail(message, htmlEmail); } private File generateImage(String name, String newPass) throws IOException { diff --git a/src/main/java/fr/xephi/authme/mail/SendMailSSL.java b/src/main/java/fr/xephi/authme/mail/SendMailSsl.java similarity index 98% rename from src/main/java/fr/xephi/authme/mail/SendMailSSL.java rename to src/main/java/fr/xephi/authme/mail/SendMailSsl.java index ece40900..34011595 100644 --- a/src/main/java/fr/xephi/authme/mail/SendMailSSL.java +++ b/src/main/java/fr/xephi/authme/mail/SendMailSsl.java @@ -24,7 +24,7 @@ import static fr.xephi.authme.settings.properties.EmailSettings.MAIL_PASSWORD; /** * Sends emails to players on behalf of the server. */ -public class SendMailSSL { +public class SendMailSsl { @Inject private Settings settings; @@ -67,7 +67,7 @@ public class SendMailSSL { } public boolean sendEmail(String content, HtmlEmail email) { - Thread.currentThread().setContextClassLoader(SendMailSSL.class.getClassLoader()); + Thread.currentThread().setContextClassLoader(SendMailSsl.class.getClassLoader()); // Issue #999: Prevent UnsupportedDataTypeException: no object DCH for MIME type multipart/alternative // cf. http://stackoverflow.com/questions/21856211/unsupporteddatatypeexception-no-object-dch-for-mime-type MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); diff --git a/src/main/java/fr/xephi/authme/permission/AuthGroupHandler.java b/src/main/java/fr/xephi/authme/permission/AuthGroupHandler.java index 5019d316..2759b636 100644 --- a/src/main/java/fr/xephi/authme/permission/AuthGroupHandler.java +++ b/src/main/java/fr/xephi/authme/permission/AuthGroupHandler.java @@ -79,8 +79,8 @@ public class AuthGroupHandler implements Reloadable { throw new IllegalStateException("Encountered unhandled auth group type '" + groupType + "'"); } - ConsoleLogger.debug( - () -> player.getName() + " changed to " + groupType + ": has groups " + permissionsManager.getGroups(player)); + ConsoleLogger.debug(() -> player.getName() + " changed to " + + groupType + ": has groups " + permissionsManager.getGroups(player)); } /** diff --git a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java index 497c99ab..aac2f4bb 100644 --- a/src/main/java/fr/xephi/authme/permission/PermissionsManager.java +++ b/src/main/java/fr/xephi/authme/permission/PermissionsManager.java @@ -74,7 +74,7 @@ public class PermissionsManager implements Reloadable { // Loop through all the available permissions system types for (PermissionsSystemType type : PermissionsSystemType.values()) { try { - PermissionHandler handler = getPermissionHandler(type); + PermissionHandler handler = createPermissionHandler(type); if (handler != null) { // Show a success message and return this.handler = handler; @@ -91,7 +91,14 @@ public class PermissionsManager implements Reloadable { ConsoleLogger.info("No supported permissions system found! Permissions are disabled!"); } - private PermissionHandler getPermissionHandler(PermissionsSystemType type) throws PermissionHandlerException { + /** + * Creates a permission handler for the provided permission systems if possible. + * + * @param type the permission systems type for which to create a corresponding permission handler + * @return the permission handler, or {@code null} if not possible + * @throws PermissionHandlerException during initialization of the permission handler + */ + private PermissionHandler createPermissionHandler(PermissionsSystemType type) throws PermissionHandlerException { // Try to find the plugin for the current permissions system Plugin plugin = pluginManager.getPlugin(type.getPluginName()); diff --git a/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java b/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java index 36f6497c..50816ce0 100644 --- a/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java +++ b/src/main/java/fr/xephi/authme/permission/handlers/PermissionHandler.java @@ -17,7 +17,7 @@ public interface PermissionHandler { * @param group The name of the group. * * @return True if succeed, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ boolean addToGroup(Player player, String group); @@ -47,7 +47,7 @@ public interface PermissionHandler { * @param group The group name. * * @return True if the player is in the specified group, false otherwise. - * False is also returned if groups aren't supported by the used permissions system. + * False is also returned if groups aren't supported by the used permissions system. */ default boolean isInGroup(Player player, String group) { return getGroups(player).contains(group); @@ -60,7 +60,7 @@ public interface PermissionHandler { * @param group The name of the group. * * @return True if succeed, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ boolean removeFromGroup(Player player, String group); @@ -72,7 +72,7 @@ public interface PermissionHandler { * @param group The name of the group. * * @return True if succeed, false otherwise. - * False is also returned if this feature isn't supported for the current permissions system. + * False is also returned if this feature isn't supported for the current permissions system. */ boolean setGroup(Player player, String group); diff --git a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java index b246bf59..7df346e4 100644 --- a/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java +++ b/src/main/java/fr/xephi/authme/process/login/AsynchronousLogin.java @@ -96,6 +96,7 @@ public class AsynchronousLogin implements AsynchronousProcess { * Checks the precondition for authentication (like user known) and returns * the player's {@link PlayerAuth} object. * + * @param player the player to check * @return the PlayerAuth object, or {@code null} if the player doesn't exist or may not log in * (e.g. because he is already logged in) */ diff --git a/src/main/java/fr/xephi/authme/process/register/executors/AbstractPasswordRegisterExecutor.java b/src/main/java/fr/xephi/authme/process/register/executors/AbstractPasswordRegisterExecutor.java index 9f0ee724..179aa59d 100644 --- a/src/main/java/fr/xephi/authme/process/register/executors/AbstractPasswordRegisterExecutor.java +++ b/src/main/java/fr/xephi/authme/process/register/executors/AbstractPasswordRegisterExecutor.java @@ -17,6 +17,8 @@ import javax.inject.Inject; /** * Registration executor for registration methods where the password * is supplied by the user. + * + * @param

the parameters type */ abstract class AbstractPasswordRegisterExecutor

implements RegistrationExecutor

{ diff --git a/src/main/java/fr/xephi/authme/process/register/executors/RegistrationExecutor.java b/src/main/java/fr/xephi/authme/process/register/executors/RegistrationExecutor.java index ad18bf92..32bfd951 100644 --- a/src/main/java/fr/xephi/authme/process/register/executors/RegistrationExecutor.java +++ b/src/main/java/fr/xephi/authme/process/register/executors/RegistrationExecutor.java @@ -4,6 +4,8 @@ import fr.xephi.authme.data.auth.PlayerAuth; /** * Performs the registration action. + * + * @param

the registration parameters type */ public interface RegistrationExecutor

{ diff --git a/src/main/java/fr/xephi/authme/process/register/executors/RegistrationMethod.java b/src/main/java/fr/xephi/authme/process/register/executors/RegistrationMethod.java index 9232332e..f5f38b86 100644 --- a/src/main/java/fr/xephi/authme/process/register/executors/RegistrationMethod.java +++ b/src/main/java/fr/xephi/authme/process/register/executors/RegistrationMethod.java @@ -8,6 +8,8 @@ package fr.xephi.authme.process.register.executors; * classes which perform this registration method. This is essentially a typed enum * as passing a constant of this class along with a parameters object to a method can * be restricted to the correct parameters type. + * + * @param

the registration parameters type the method uses */ public final class RegistrationMethod

{ diff --git a/src/main/java/fr/xephi/authme/service/BukkitService.java b/src/main/java/fr/xephi/authme/service/BukkitService.java index e945cebd..4d94b62d 100644 --- a/src/main/java/fr/xephi/authme/service/BukkitService.java +++ b/src/main/java/fr/xephi/authme/service/BukkitService.java @@ -44,7 +44,7 @@ public class BukkitService implements SettingsDependent { @Inject BukkitService(AuthMe authMe, Settings settings) { this.authMe = authMe; - getOnlinePlayersIsCollection = initializeOnlinePlayersIsCollectionField(); + getOnlinePlayersIsCollection = doesOnlinePlayersMethodReturnCollection(); reload(settings); } @@ -301,11 +301,12 @@ public class BukkitService implements SettingsDependent { /** * Method run upon initialization to verify whether or not the Bukkit implementation - * returns the online players as a Collection. + * returns the online players as a {@link Collection}. * + * @return true if a collection is returned by the bukkit implementation, false otherwise * @see #getOnlinePlayers() */ - private static boolean initializeOnlinePlayersIsCollectionField() { + private static boolean doesOnlinePlayersMethodReturnCollection() { try { Method method = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); return method.getReturnType() == Collection.class; diff --git a/src/main/java/fr/xephi/authme/settings/EnumSetProperty.java b/src/main/java/fr/xephi/authme/settings/EnumSetProperty.java index 37ebba81..901c9fc1 100644 --- a/src/main/java/fr/xephi/authme/settings/EnumSetProperty.java +++ b/src/main/java/fr/xephi/authme/settings/EnumSetProperty.java @@ -12,6 +12,8 @@ import static com.google.common.collect.Sets.newHashSet; /** * Property whose value is a set of entries of a given enum. + * + * @param the enum type */ public class EnumSetProperty> extends Property> { diff --git a/src/main/java/fr/xephi/authme/util/expiring/TimedCounter.java b/src/main/java/fr/xephi/authme/util/expiring/TimedCounter.java index 2e19b5a2..e5ef899d 100644 --- a/src/main/java/fr/xephi/authme/util/expiring/TimedCounter.java +++ b/src/main/java/fr/xephi/authme/util/expiring/TimedCounter.java @@ -7,6 +7,8 @@ import java.util.concurrent.TimeUnit; *

* Once the expiration of an entry has been reached, the counter resets * to 0. The counter returns 0 rather than {@code null} for any given key. + * + * @param the type of the key */ public class TimedCounter extends ExpiringMap { @@ -47,8 +49,7 @@ public class TimedCounter extends ExpiringMap { if (e != null) { if (e.getValue() <= 0) { remove(key); - } - else { + } else { entries.put(key, new ExpiringEntry<>(e.getValue() - 1, e.getExpiration())); } } diff --git a/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java b/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java new file mode 100644 index 00000000..928ad2a9 --- /dev/null +++ b/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java @@ -0,0 +1,51 @@ +package fr.xephi.authme; + +import fr.xephi.authme.util.Utils; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + +/** + * Consistency test for the CodeClimate configuration file. + */ +public class CodeClimateConfigTest { + + private static final String CONFIG_FILE = ".codeclimate.yml"; + + @Test + public void shouldHaveExistingClassesInExclusions() { + // given + FileConfiguration configuration = YamlConfiguration.loadConfiguration(new File(CONFIG_FILE)); + List excludePaths = configuration.getStringList("exclude_paths"); + + // when / then + assertThat(excludePaths, not(empty())); + for (String path : excludePaths) { + String className = convertPathToQualifiedClassName(path); + assertThat("No class corresponds to excluded path '" + path + "'", + Utils.isClassLoaded(className), equalTo(true)); + } + } + + private static String convertPathToQualifiedClassName(String path) { + // Note ljacqu 20170323: In the future, we could have legitimate exclusions that don't fulfill these checks, + // in which case this test needs to be adapted accordingly. + if (!path.startsWith(TestHelper.SOURCES_FOLDER)) { + throw new IllegalArgumentException("Unexpected path '" + path + "': expected to start with sources folder"); + } else if (!path.endsWith(".java")) { + throw new IllegalArgumentException("Expected path '" + path + "' to end with '.java'"); + } + + return path.substring(0, path.length() - ".java".length()) // strip ending .java + .substring(TestHelper.SOURCES_FOLDER.length()) // strip starting src/main/java + .replace('/', '.'); // replace '/' to '.' + } +} diff --git a/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java index 271f1174..bb5694e9 100644 --- a/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/HelpCommandTest.java @@ -26,7 +26,7 @@ import static fr.xephi.authme.command.help.HelpProvider.SHOW_COMMAND; import static fr.xephi.authme.command.help.HelpProvider.SHOW_DESCRIPTION; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java index 18ab9fd2..c0e35b80 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionConsistencyTest.java @@ -1,6 +1,7 @@ package fr.xephi.authme.command.executable.authme.debug; import fr.xephi.authme.ClassCollector; +import fr.xephi.authme.TestHelper; import org.junit.BeforeClass; import org.junit.Test; @@ -22,8 +23,8 @@ public class DebugSectionConsistencyTest { @BeforeClass public static void collectClasses() { - debugClasses = new ClassCollector("src/main/java", "fr/xephi/authme/command/executable/authme/debug") - .collectClasses(); + debugClasses = new ClassCollector( + TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT + "command/executable/authme/debug").collectClasses(); } @Test diff --git a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java index 9feb9423..43cbaa61 100644 --- a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java +++ b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java @@ -48,7 +48,7 @@ public class EmailServiceTest { @Mock private Server server; @Mock - private SendMailSSL sendMailSSL; + private SendMailSsl sendMailSsl; @DataFolder private File dataFolder; @@ -66,7 +66,7 @@ public class EmailServiceTest { given(server.getServerName()).willReturn("serverName"); given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("mail@example.org"); given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); - given(sendMailSSL.hasAllInformation()).willReturn(true); + given(sendMailSsl.hasAllInformation()).willReturn(true); } @Test @@ -82,17 +82,17 @@ public class EmailServiceTest { .willReturn("Hi , your new password for is "); given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false); HtmlEmail email = mock(HtmlEmail.class); - given(sendMailSSL.initializeMail(anyString())).willReturn(email); - given(sendMailSSL.sendEmail(anyString(), eq(email))).willReturn(true); + given(sendMailSsl.initializeMail(anyString())).willReturn(email); + given(sendMailSsl.sendEmail(anyString(), eq(email))).willReturn(true); // when boolean result = emailService.sendPasswordMail("Player", "user@example.com", "new_password"); // then assertThat(result, equalTo(true)); - verify(sendMailSSL).initializeMail("user@example.com"); + verify(sendMailSsl).initializeMail("user@example.com"); ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); - verify(sendMailSSL).sendEmail(messageCaptor.capture(), eq(email)); + verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); assertThat(messageCaptor.getValue(), equalTo("Hi Player, your new password for serverName is new_password")); } @@ -100,15 +100,15 @@ public class EmailServiceTest { @Test public void shouldHandleMailCreationError() throws EmailException { // given - doThrow(EmailException.class).when(sendMailSSL).initializeMail(anyString()); + doThrow(EmailException.class).when(sendMailSsl).initializeMail(anyString()); // when boolean result = emailService.sendPasswordMail("Player", "user@example.com", "new_password"); // then assertThat(result, equalTo(false)); - verify(sendMailSSL).initializeMail("user@example.com"); - verify(sendMailSSL, never()).sendEmail(anyString(), any(HtmlEmail.class)); + verify(sendMailSsl).initializeMail("user@example.com"); + verify(sendMailSsl, never()).sendEmail(anyString(), any(HtmlEmail.class)); } @Test @@ -117,17 +117,17 @@ public class EmailServiceTest { given(settings.getPasswordEmailMessage()).willReturn("Hi , your new pass is "); given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false); HtmlEmail email = mock(HtmlEmail.class); - given(sendMailSSL.initializeMail(anyString())).willReturn(email); - given(sendMailSSL.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false); + given(sendMailSsl.initializeMail(anyString())).willReturn(email); + given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false); // when boolean result = emailService.sendPasswordMail("bobby", "user@example.com", "myPassw0rd"); // then assertThat(result, equalTo(false)); - verify(sendMailSSL).initializeMail("user@example.com"); + verify(sendMailSsl).initializeMail("user@example.com"); ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); - verify(sendMailSSL).sendEmail(messageCaptor.capture(), eq(email)); + verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); assertThat(messageCaptor.getValue(), equalTo("Hi bobby, your new pass is myPassw0rd")); } @@ -138,32 +138,32 @@ public class EmailServiceTest { given(settings.getRecoveryCodeEmailMessage()) .willReturn("Hi , your code on is (valid hours)"); HtmlEmail email = mock(HtmlEmail.class); - given(sendMailSSL.initializeMail(anyString())).willReturn(email); - given(sendMailSSL.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(true); + given(sendMailSsl.initializeMail(anyString())).willReturn(email); + given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(true); // when boolean result = emailService.sendRecoveryCode("Timmy", "tim@example.com", "12C56A"); // then assertThat(result, equalTo(true)); - verify(sendMailSSL).initializeMail("tim@example.com"); + verify(sendMailSsl).initializeMail("tim@example.com"); ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); - verify(sendMailSSL).sendEmail(messageCaptor.capture(), eq(email)); + verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); assertThat(messageCaptor.getValue(), equalTo("Hi Timmy, your code on serverName is 12C56A (valid 7 hours)")); } @Test public void shouldHandleMailCreationErrorForRecoveryCode() throws EmailException { // given - given(sendMailSSL.initializeMail(anyString())).willThrow(EmailException.class); + given(sendMailSsl.initializeMail(anyString())).willThrow(EmailException.class); // when boolean result = emailService.sendRecoveryCode("Player", "player@example.org", "ABC1234"); // then assertThat(result, equalTo(false)); - verify(sendMailSSL).initializeMail("player@example.org"); - verify(sendMailSSL, never()).sendEmail(anyString(), any(HtmlEmail.class)); + verify(sendMailSsl).initializeMail("player@example.org"); + verify(sendMailSsl, never()).sendEmail(anyString(), any(HtmlEmail.class)); } @Test @@ -173,17 +173,17 @@ public class EmailServiceTest { given(settings.getRecoveryCodeEmailMessage()).willReturn("Hi , your code is "); EmailService sendMailSpy = spy(emailService); HtmlEmail email = mock(HtmlEmail.class); - given(sendMailSSL.initializeMail(anyString())).willReturn(email); - given(sendMailSSL.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false); + given(sendMailSsl.initializeMail(anyString())).willReturn(email); + given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false); // when boolean result = sendMailSpy.sendRecoveryCode("John", "user@example.com", "1DEF77"); // then assertThat(result, equalTo(false)); - verify(sendMailSSL).initializeMail("user@example.com"); + verify(sendMailSsl).initializeMail("user@example.com"); ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); - verify(sendMailSSL).sendEmail(messageCaptor.capture(), eq(email)); + verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); assertThat(messageCaptor.getValue(), equalTo("Hi John, your code is 1DEF77")); } diff --git a/src/test/java/fr/xephi/authme/mail/SendMailSSLTest.java b/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java similarity index 94% rename from src/test/java/fr/xephi/authme/mail/SendMailSSLTest.java rename to src/test/java/fr/xephi/authme/mail/SendMailSslTest.java index 74318498..cd5b2152 100644 --- a/src/test/java/fr/xephi/authme/mail/SendMailSSLTest.java +++ b/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java @@ -28,13 +28,13 @@ import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; /** - * Test for {@link SendMailSSL}. + * Test for {@link SendMailSsl}. */ @RunWith(DelayedInjectionRunner.class) -public class SendMailSSLTest { +public class SendMailSslTest { @InjectDelayed - private SendMailSSL sendMailSSL; + private SendMailSsl sendMailSsl; @Mock private Settings settings; @@ -57,7 +57,7 @@ public class SendMailSSLTest { @Test public void shouldHaveAllInformation() { // given / when / then - assertThat(sendMailSSL.hasAllInformation(), equalTo(true)); + assertThat(sendMailSsl.hasAllInformation(), equalTo(true)); } @Test @@ -73,7 +73,7 @@ public class SendMailSSLTest { given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.DEBUG); // when - HtmlEmail email = sendMailSSL.initializeMail("recipient@example.com"); + HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); // then assertThat(email, not(nullValue())); @@ -99,7 +99,7 @@ public class SendMailSSLTest { given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName); // when - HtmlEmail email = sendMailSSL.initializeMail("recipient@example.com"); + HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); // then assertThat(email, not(nullValue())); @@ -122,7 +122,7 @@ public class SendMailSSLTest { given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderMail); // when - HtmlEmail email = sendMailSSL.initializeMail("recipient@example.com"); + HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); // then assertThat(email, not(nullValue())); diff --git a/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java b/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java index cddc0cab..c3648a7f 100644 --- a/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java @@ -9,6 +9,7 @@ import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Multimap; import fr.xephi.authme.ClassCollector; import fr.xephi.authme.ReflectionTestUtils; +import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSourceType; import fr.xephi.authme.settings.properties.AuthMeSettingsRetriever; import fr.xephi.authme.settings.properties.DatabaseSettings; @@ -126,7 +127,7 @@ public class SettingsConsistencyTest { private List getSectionCommentMethods() { // Find all SettingsHolder classes List> settingsClasses = - new ClassCollector("src/main/java", "fr/xephi/authme/settings/properties/") + new ClassCollector(TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT + "settings/properties/") .collectClasses(SettingsHolder.class); checkArgument(!settingsClasses.isEmpty(), "Could not find any SettingsHolder classes");