From 07367427c80862f29dd8f0ca40b10f4cce17fc2f Mon Sep 17 00:00:00 2001 From: "selcarpa@gmail.com" Date: Tue, 5 Jan 2021 10:04:53 +0800 Subject: [PATCH] pre-release --- .../java/cn/aethli/mineauth/Mineauth.java | 5 +- .../mineauth/annotation/MetadataScan.java | 12 -- .../aethli/mineauth/command/BaseCommand.java | 25 +---- .../aethli/mineauth/command/LoginCommand.java | 3 + .../mineauth/command/RegisterCommand.java | 5 +- .../common/converter/BooleanConverter.java | 2 +- .../mineauth/common/converter/Converter.java | 3 +- .../mineauth/common/model/EntityMapper.java | 2 +- .../mineauth/common/utils/MessageUtils.java | 65 ++++++++++- .../mineauth/common/utils/MetadataUtils.java | 104 +----------------- .../cn/aethli/test/mineauth/DataBaseTest.java | 13 +-- 11 files changed, 79 insertions(+), 160 deletions(-) delete mode 100644 src/main/java/cn/aethli/mineauth/annotation/MetadataScan.java diff --git a/src/main/java/cn/aethli/mineauth/Mineauth.java b/src/main/java/cn/aethli/mineauth/Mineauth.java index 33dc6c2..144ef03 100644 --- a/src/main/java/cn/aethli/mineauth/Mineauth.java +++ b/src/main/java/cn/aethli/mineauth/Mineauth.java @@ -1,6 +1,5 @@ package cn.aethli.mineauth; -import cn.aethli.mineauth.annotation.MetadataScan; import cn.aethli.mineauth.command.*; import cn.aethli.mineauth.common.model.PlayerPreparation; import cn.aethli.mineauth.common.utils.I18nUtils; @@ -51,7 +50,6 @@ import static net.minecraftforge.fml.loading.LogMarkers.FORGEMOD; @Mod("mineauth") -@MetadataScan(packageName = ("cn.aethli.mineauth.entity")) public class Mineauth { public static final String DEFAULT_H2_DATABASE_FILE_RESOURCE_PATH = @@ -68,9 +66,8 @@ public class Mineauth { * register this mod and initial some database entity metadata * * @throws IOException when some jdk internal class exception - * @throws ClassNotFoundException when some jdk internal class exception */ - public Mineauth() throws IOException, ClassNotFoundException { + public Mineauth() throws IOException { initialInternalDatabase(DEFAULT_H2_DATABASE_FILE_RESOURCE_PATH); MetadataUtils.initMetadata(); ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, MineauthConfig.FORGE_CONFIG_SPEC); diff --git a/src/main/java/cn/aethli/mineauth/annotation/MetadataScan.java b/src/main/java/cn/aethli/mineauth/annotation/MetadataScan.java deleted file mode 100644 index 7ee60cd..0000000 --- a/src/main/java/cn/aethli/mineauth/annotation/MetadataScan.java +++ /dev/null @@ -1,12 +0,0 @@ -package cn.aethli.mineauth.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(value = ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface MetadataScan { - String[] packageName(); -} diff --git a/src/main/java/cn/aethli/mineauth/command/BaseCommand.java b/src/main/java/cn/aethli/mineauth/command/BaseCommand.java index 4c22def..eff391a 100644 --- a/src/main/java/cn/aethli/mineauth/command/BaseCommand.java +++ b/src/main/java/cn/aethli/mineauth/command/BaseCommand.java @@ -8,7 +8,6 @@ import net.minecraft.command.CommandSource; import net.minecraft.command.Commands; -import java.util.Iterator; import java.util.List; public abstract class BaseCommand implements Command { @@ -19,34 +18,18 @@ public BaseCommand(String command, List parameters) { if (null != parameters && !parameters.isEmpty()) { builder.then(getArgument(parameters)); -// RequiredArgumentBuilder firstArgument = -// Commands.argument(parameters.get(0), StringArgumentType.string()); -// parameters.remove(0); -// if (parameters.isEmpty()) { -// builder = builder.then(firstArgument.executes(this)); -// }else { -// RequiredArgumentBuilder lastArgument = firstArgument; -// for (Iterator iterator = parameters.iterator(); iterator.hasNext(); ) { -// String parameter = iterator.next(); -// lastArgument = -// lastArgument.then( -// iterator.hasNext() -// ? Commands.argument(parameter, StringArgumentType.string()) -// : Commands.argument(parameter, StringArgumentType.string()).executes(this)); -// } -// builder.then(firstArgument); -// } } else { builder.executes(this); } } - private RequiredArgumentBuilder getArgument(List parameters){ + private RequiredArgumentBuilder getArgument(List parameters) { String parameter = parameters.get(0); if (parameters.size() > 1) { parameters.remove(0); - return Commands.argument(parameter, StringArgumentType.string()).then(getArgument(parameters)); - }else { + return Commands.argument(parameter, StringArgumentType.string()) + .then(getArgument(parameters)); + } else { return Commands.argument(parameter, StringArgumentType.string()).executes(this); } } diff --git a/src/main/java/cn/aethli/mineauth/command/LoginCommand.java b/src/main/java/cn/aethli/mineauth/command/LoginCommand.java index 91ae3c7..003f70c 100644 --- a/src/main/java/cn/aethli/mineauth/command/LoginCommand.java +++ b/src/main/java/cn/aethli/mineauth/command/LoginCommand.java @@ -37,6 +37,9 @@ public int run(CommandContext context) throws CommandSyntaxExcept if (authPlayer == null) { msgToOnePlayerByI18n(player, "login_not_found"); } else { + if (authPlayer.getBanned()) { + msgToOnePlayerByI18n(player,"banned"); + } String password = StringArgumentType.getString(context, "password"); String digestedPassword = DigestUtils.md5Hex(password); if (authPlayer.getPassword().equals(digestedPassword)) { diff --git a/src/main/java/cn/aethli/mineauth/command/RegisterCommand.java b/src/main/java/cn/aethli/mineauth/command/RegisterCommand.java index 7385b40..620c7d3 100644 --- a/src/main/java/cn/aethli/mineauth/command/RegisterCommand.java +++ b/src/main/java/cn/aethli/mineauth/command/RegisterCommand.java @@ -28,6 +28,7 @@ public class RegisterCommand extends BaseCommand { private static final Logger LOGGER = LogManager.getLogger(RegisterCommand.class); private static final String REGEX = "^[A-Za-z0-9!#$%]+$"; private static final Integer PASSWORD_ALLOW_LENGTH = 16; + private static final Gson GSON = new Gson(); static { parameters.add("password"); @@ -63,13 +64,15 @@ public int run(CommandContext context) throws CommandSyntaxExcept String digestedPassword = DigestUtils.md5Hex(password); authPlayer.setPassword(digestedPassword); authPlayer.setLastLogin(LocalDateTime.now()); + authPlayer.setBanned(false); + authPlayer.setUsername(player.getScoreboardName()); boolean b = DataUtils.insertOne(authPlayer); if (b) { Mineauth.addToAuthPlayerMap(player.getUniqueID().toString(), authPlayer); msgToOnePlayerByI18n(player, "register_success"); } else { msgToOnePlayerByI18n(player, "error"); - LOGGER.error("Database insert error,{}", new Gson().toJson(authPlayer)); + LOGGER.error("Database insert error,{}", GSON.toJson(authPlayer)); } return 1; } else { diff --git a/src/main/java/cn/aethli/mineauth/common/converter/BooleanConverter.java b/src/main/java/cn/aethli/mineauth/common/converter/BooleanConverter.java index 2391b2f..84f4001 100644 --- a/src/main/java/cn/aethli/mineauth/common/converter/BooleanConverter.java +++ b/src/main/java/cn/aethli/mineauth/common/converter/BooleanConverter.java @@ -1,6 +1,6 @@ package cn.aethli.mineauth.common.converter; -/** @author 93162 */ +/** @author SelcaNyan */ public class BooleanConverter implements Converter { @Override public Boolean valueOf(String src) { diff --git a/src/main/java/cn/aethli/mineauth/common/converter/Converter.java b/src/main/java/cn/aethli/mineauth/common/converter/Converter.java index 6187027..cc7184f 100644 --- a/src/main/java/cn/aethli/mineauth/common/converter/Converter.java +++ b/src/main/java/cn/aethli/mineauth/common/converter/Converter.java @@ -1,9 +1,8 @@ package cn.aethli.mineauth.common.converter; -/** @author 93162 */ +/** @author SelcaNyan */ public interface Converter { T valueOf(String src); - // never used String parse(Object o); } diff --git a/src/main/java/cn/aethli/mineauth/common/model/EntityMapper.java b/src/main/java/cn/aethli/mineauth/common/model/EntityMapper.java index 37da7e4..b742c91 100644 --- a/src/main/java/cn/aethli/mineauth/common/model/EntityMapper.java +++ b/src/main/java/cn/aethli/mineauth/common/model/EntityMapper.java @@ -3,7 +3,7 @@ import java.lang.reflect.Field; import java.util.Set; -/** @author 93162 */ +/** @author SelcaNyan */ public class EntityMapper { private Set tableColumns; private Set fields; diff --git a/src/main/java/cn/aethli/mineauth/common/utils/MessageUtils.java b/src/main/java/cn/aethli/mineauth/common/utils/MessageUtils.java index 15da8c7..2a54fb4 100644 --- a/src/main/java/cn/aethli/mineauth/common/utils/MessageUtils.java +++ b/src/main/java/cn/aethli/mineauth/common/utils/MessageUtils.java @@ -3,13 +3,72 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.text.StringTextComponent; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.MissingFormatArgumentException; public class MessageUtils { - public static void msgToOnePlayer(PlayerEntity playerEntity, String content) { + private static final Logger LOGGER = LogManager.getLogger(); + + public static void msgToOnePlayer(final PlayerEntity playerEntity, final String content) { playerEntity.sendMessage(new StringTextComponent(content), playerEntity.getUniqueID()); } - public static void msgToOnePlayerByI18n(PlayerEntity playerEntity, String key) { - playerEntity.sendMessage(new StringTextComponent(StringUtils.stripToEmpty(I18nUtils.getTranslateContent(key))),playerEntity.getUniqueID()); + public static void msgToOnePlayerByI18n( + final PlayerEntity playerEntity, final String key, final Object... args) { + try { + msgToOnePlayer( + playerEntity, + String.format(StringUtils.stripToEmpty(I18nUtils.getTranslateContent(key)), args)); + } catch (MissingFormatArgumentException e) { + LOGGER.error(e.getMessage(), e); + msgToOnePlayer( + playerEntity, + formatString(StringUtils.stripToEmpty(I18nUtils.getTranslateContent(key)), args)); + } + } + + /** + * Way to format String and avoid MissingFormatArgumentException + * + * @param stringToFormat origin string + * @param args argument to replace format specifier + * @return string + */ + public static String formatString(final String stringToFormat, final Object... args) { + if (stringToFormat == null || stringToFormat.length() == 0) return stringToFormat; + int specifiersCount = 0; + final int argsCount = args == null ? 0 : args.length; + final StringBuilder sb = new StringBuilder(stringToFormat.length()); + for (int i = 0; i < stringToFormat.length(); ++i) { + char c = stringToFormat.charAt(i); + if (c != '%') sb.append(c); + else { + final char nextChar = stringToFormat.charAt(i + 1); + if (nextChar == '%' || nextChar == 'n') { + ++i; + sb.append(c); + sb.append(nextChar); + continue; + } + // found a specifier + ++specifiersCount; + if (specifiersCount <= argsCount) sb.append(c); + else + while (true) { + ++i; + c = stringToFormat.charAt(i); + // find the end of the converter, to ignore it all + if (c == 't' || c == 'T') { + // time prefix and then a character, so skip it + ++i; + break; + } + if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') break; + } + } + } + return String.format(sb.toString(), args); } } diff --git a/src/main/java/cn/aethli/mineauth/common/utils/MetadataUtils.java b/src/main/java/cn/aethli/mineauth/common/utils/MetadataUtils.java index 7b7cb2c..964e38c 100644 --- a/src/main/java/cn/aethli/mineauth/common/utils/MetadataUtils.java +++ b/src/main/java/cn/aethli/mineauth/common/utils/MetadataUtils.java @@ -18,50 +18,12 @@ public class MetadataUtils { private static final Map ENTITY_MAPPER_MAP = new ConcurrentHashMap<>(); private static final AtomicBoolean initFlag = new AtomicBoolean(false); - private static final Logger LOGGER = LogManager.getLogger(); - /** - * init metadata, to cache entity-field map exclude abstract class and non-extends BaseEntity - * - * @see cn.aethli.mineauth.entity.BaseEntity - * @param packageName packageName to scan - * @throws ClassNotFoundException if the class cannot be located - * @throws IOException If I/O errors occur - */ - public static void initMetadata(String packageName) throws IOException, ClassNotFoundException { - List> classes = getClasses(packageName); - System.out.println("-----------------------------"); - classes.forEach(a -> System.out.println(a.getName())); - Field[] baseEntityFields = BaseEntity.class.getDeclaredFields(); - classes.forEach( - aClass -> { - if (!Modifier.isAbstract(aClass.getModifiers()) - && BaseEntity.class.isAssignableFrom(aClass)) { - Set fields = new HashSet<>(Arrays.asList(aClass.getDeclaredFields())); - fields.addAll(Arrays.asList(baseEntityFields)); - EntityMapper entityMapper = ENTITY_MAPPER_MAP.get(aClass.getTypeName()); - if (entityMapper == null) { - entityMapper = new EntityMapper(); - entityMapper.setClassName(aClass.getTypeName()); - entityMapper.setFields(fields); - ENTITY_MAPPER_MAP.put(aClass.getTypeName(), entityMapper); - } - } - }); - } - - public static void initMetadata() throws IOException, ClassNotFoundException { + public static void initMetadata() { synchronized (initFlag) { if (initFlag.get()) { return; } - // Class mineauthClass = Mineauth.class; - // if (mineauthClass.isAnnotationPresent(MetadataScan.class)) { - // MetadataScan metadataScan = mineauthClass.getAnnotation(MetadataScan.class); - // for (String packageName : metadataScan.packageName()) { - // MetadataUtils.initMetadata(packageName); - // } - // } Field[] baseEntityFields = BaseEntity.class.getDeclaredFields(); HashSet fields = new HashSet<>(Arrays.asList(AuthPlayer.class.getDeclaredFields())); fields.addAll(Arrays.asList(baseEntityFields)); @@ -85,68 +47,4 @@ public static void initMetadata() throws IOException, ClassNotFoundException { public static EntityMapper getEntityMapperByTypeName(String typeName) { return ENTITY_MAPPER_MAP.get(typeName); } - - /** - * Scans all classes accessible from the context class loader which belong to the given package. - * - * @param packageName The base package - * @return The classes - * @throws ClassNotFoundException if the class cannot be located - * @throws IOException If I/O errors occur - */ - private static List> getClasses(String packageName) - throws ClassNotFoundException, IOException { - // both not works with java -jar - // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - // ClassPath classpath = ClassPath.from(classLoader); // scans the class path used by - // classloader - // ImmutableSet topLevelClasses = - // classpath.getTopLevelClasses(packageName); - // List> collect = - // topLevelClasses.stream().map(ClassPath.ClassInfo::load).collect(Collectors.toList()); - // return (List>) collect; - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - String path = packageName.replace('.', '/'); - Enumeration resources = classLoader.getResources(path); - List dirs = new ArrayList<>(); - while (resources.hasMoreElements()) { - URL resource = resources.nextElement(); - dirs.add(new File(resource.getFile())); - } - ArrayList> classes = new ArrayList<>(); - for (File directory : dirs) { - classes.addAll(findClasses(directory, packageName)); - } - return classes; - } - - /** - * Recursive method used to find all classes in a given directory. - * - * @param directory The base directory - * @param packageName The package name for classes found inside the base directory - * @return The classes - * @throws ClassNotFoundException if the class cannot be located - */ - private static List> findClasses( - File directory, String packageName) throws ClassNotFoundException { - List> classes = new ArrayList<>(); - if (!directory.exists()) { - return classes; - } - File[] files = directory.listFiles(); - if (files != null) { - for (File file : files) { - if (!file.isDirectory() && file.getName().endsWith(".class")) { - classes.add( - (Class) - Class.forName( - packageName - + '.' - + file.getName().substring(0, file.getName().length() - 6))); - } - } - } - return classes; - } } diff --git a/src/test/java/cn/aethli/test/mineauth/DataBaseTest.java b/src/test/java/cn/aethli/test/mineauth/DataBaseTest.java index cc2c2d6..9095982 100644 --- a/src/test/java/cn/aethli/test/mineauth/DataBaseTest.java +++ b/src/test/java/cn/aethli/test/mineauth/DataBaseTest.java @@ -1,7 +1,6 @@ package cn.aethli.test.mineauth; import cn.aethli.mineauth.Mineauth; -import cn.aethli.mineauth.annotation.MetadataScan; import cn.aethli.mineauth.common.utils.DataUtils; import cn.aethli.mineauth.common.utils.MetadataUtils; import cn.aethli.mineauth.datasource.ExpansionAbleConnectionPool; @@ -10,6 +9,7 @@ import com.google.gson.Gson; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.*; import java.io.File; @@ -23,7 +23,6 @@ import java.util.List; import java.util.UUID; -@MetadataScan(packageName = ("cn.aethli.mineauth.entity")) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class DataBaseTest { @@ -40,7 +39,6 @@ public void databaseInit() throws SQLException, IOException, ClassNotFoundExcept "root", "admin", 2); -// metadataInit(); MetadataUtils.initMetadata(); DataUtils.DatabaseInit(); } @@ -80,15 +78,6 @@ public void copyDatabase() throws IOException { } } - public void metadataInit() throws IOException, ClassNotFoundException { - Class mineauthClass = Mineauth.class; - if (mineauthClass.isAnnotationPresent(MetadataScan.class)) { - MetadataScan metadataScan = mineauthClass.getAnnotation(MetadataScan.class); - for (String packageName : metadataScan.packageName()) { - MetadataUtils.initMetadata(packageName); - } - } - } @Test @DisplayName("insertOnePlayer")