Skip to content

Commit

Permalink
pre-release
Browse files Browse the repository at this point in the history
  • Loading branch information
selcarpa committed Jan 5, 2021
1 parent 87270e3 commit 0736742
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 160 deletions.
5 changes: 1 addition & 4 deletions src/main/java/cn/aethli/mineauth/Mineauth.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 =
Expand All @@ -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);
Expand Down
12 changes: 0 additions & 12 deletions src/main/java/cn/aethli/mineauth/annotation/MetadataScan.java

This file was deleted.

25 changes: 4 additions & 21 deletions src/main/java/cn/aethli/mineauth/command/BaseCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends BaseEntity> implements Command<CommandSource> {
Expand All @@ -19,34 +18,18 @@ public BaseCommand(String command, List<String> parameters) {

if (null != parameters && !parameters.isEmpty()) {
builder.then(getArgument(parameters));
// RequiredArgumentBuilder<CommandSource, String> firstArgument =
// Commands.argument(parameters.get(0), StringArgumentType.string());
// parameters.remove(0);
// if (parameters.isEmpty()) {
// builder = builder.then(firstArgument.executes(this));
// }else {
// RequiredArgumentBuilder<CommandSource, String> lastArgument = firstArgument;
// for (Iterator<String> 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<CommandSource,String> getArgument(List<String> parameters){
private RequiredArgumentBuilder<CommandSource, String> getArgument(List<String> 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);
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/cn/aethli/mineauth/command/LoginCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ public int run(CommandContext<CommandSource> 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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public class RegisterCommand extends BaseCommand<AuthPlayer> {
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");
Expand Down Expand Up @@ -63,13 +64,15 @@ public int run(CommandContext<CommandSource> 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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package cn.aethli.mineauth.common.converter;

/** @author 93162 */
/** @author SelcaNyan */
public class BooleanConverter implements Converter<Boolean> {
@Override
public Boolean valueOf(String src) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package cn.aethli.mineauth.common.converter;

/** @author 93162 */
/** @author SelcaNyan */
public interface Converter<T> {
T valueOf(String src);

// never used
String parse(Object o);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import java.lang.reflect.Field;
import java.util.Set;

/** @author 93162 */
/** @author SelcaNyan */
public class EntityMapper {
private Set<TableColumn> tableColumns;
private Set<Field> fields;
Expand Down
65 changes: 62 additions & 3 deletions src/main/java/cn/aethli/mineauth/common/utils/MessageUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
104 changes: 1 addition & 103 deletions src/main/java/cn/aethli/mineauth/common/utils/MetadataUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,50 +18,12 @@
public class MetadataUtils {
private static final Map<String, EntityMapper> 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<Class<BaseEntity>> 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<Field> 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<Mineauth> 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<Field> fields = new HashSet<>(Arrays.asList(AuthPlayer.class.getDeclaredFields()));
fields.addAll(Arrays.asList(baseEntityFields));
Expand All @@ -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 <T extends BaseEntity> List<Class<T>> 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<ClassPath.ClassInfo> topLevelClasses =
// classpath.getTopLevelClasses(packageName);
// List<? extends Class<?>> collect =
// topLevelClasses.stream().map(ClassPath.ClassInfo::load).collect(Collectors.toList());
// return (List<Class<T>>) collect;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class<T>> 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 <T extends BaseEntity> List<Class<T>> findClasses(
File directory, String packageName) throws ClassNotFoundException {
List<Class<T>> 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<T>)
Class.forName(
packageName
+ '.'
+ file.getName().substring(0, file.getName().length() - 6)));
}
}
}
return classes;
}
}
13 changes: 1 addition & 12 deletions src/test/java/cn/aethli/test/mineauth/DataBaseTest.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand All @@ -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 {

Expand All @@ -40,7 +39,6 @@ public void databaseInit() throws SQLException, IOException, ClassNotFoundExcept
"root",
"admin",
2);
// metadataInit();
MetadataUtils.initMetadata();
DataUtils.DatabaseInit();
}
Expand Down Expand Up @@ -80,15 +78,6 @@ public void copyDatabase() throws IOException {
}
}

public void metadataInit() throws IOException, ClassNotFoundException {
Class<Mineauth> 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")
Expand Down

0 comments on commit 0736742

Please sign in to comment.