Add: a switch for printing to standard output

This commit is contained in:
33 committed 2022-11-24 21:42:45 +08:00
1 parent e94f4b0e99
commit 63251c9f5e
4 files changed
+185 -110

No files matched your search

@@ -42,12 +42,13 @@ public class CustomSkinLoader {
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static final Logger logger = initLogger();
public static final Config config = Config.loadConfig0();
public static final Config config = initConfig();
private static final ProfileCache profileCache = new ProfileCache();
private static final DynamicSkullManager dynamicSkullManager = new DynamicSkullManager();
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(
config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
//Correct thread name in thread pool
private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@@ -68,7 +69,8 @@ public class CustomSkinLoader {
THREAD_POOL.execute(runnable);
}
public static void loadProfileLazily(GameProfile gameProfile, Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> consumer) {
public static void loadProfileLazily(
GameProfile gameProfile, Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> consumer) {
String username = gameProfile.getName();
String credential = MinecraftUtil.getCredential(gameProfile);
// Fix: http://hopper.minecraft.net/crashes/minecraft/MCX-2773713
@@ -190,7 +192,8 @@ public class CustomSkinLoader {
}
//For Skull
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadProfileFromCache(final GameProfile gameProfile) {
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadProfileFromCache(
final GameProfile gameProfile) {
String username = gameProfile.getName();
String credential = MinecraftUtil.getCredential(gameProfile);
@@ -224,10 +227,25 @@ public class CustomSkinLoader {
Logger logger = new Logger(LOG_FILE);
logger.info("CustomSkinLoader " + CustomSkinLoader_FULL_VERSION);
logger.info("DataDir: " + DATA_DIR.getAbsolutePath());
logger.info("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"));
logger.info("Java Version: " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor"));
logger.info("Java VM Version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"));
logger.info("Operating System: " + System.getProperty("os.name") +
" (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"));
logger.info("Java Version: " + System.getProperty("java.version") +
", " + System.getProperty("java.vendor"));
logger.info("Java VM Version: " + System.getProperty("java.vm.name") +
" (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"));
logger.info("Minecraft: " + MinecraftUtil.getMinecraftMainVersion());
return logger;
}
/**
* Create <code>Config</code> object.
* To use <code>logger</code>, please make sure call this function after <code>initLogger</code>.
*
* @return <code>Config</code>
*/
private static Config initConfig() {
Config config = Config.loadConfig0();
logger.enableLogStdOut = config.enableLogStdOut;
return config;
}
}
+82 -38
View File
@@ -2,60 +2,81 @@ package customskinloader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class Logger {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public enum Level{
DEBUG("DEBUG",false),
INFO("INFO",true),
WARNING("WARNING",true);
String name;
boolean display;
Level(String name,boolean display){
this.name=name;
this.display=display;
/**
* A copy of <code>Config.enableLogStdOut</code>.
* Because <code>Config.loadConfig0()</code> will use <code>Logger.log()</code>,
* which means cannot access <code>CustomSkinLoader.config</code> here.
*
* @see customskinloader.config.Config#enableLogStdOut
* @since 14.15
*/
public boolean enableLogStdOut = false;
public enum Level {
DEBUG("DEBUG", false),
INFO("INFO", true),
WARNING("WARNING", true);
final String name;
final boolean display;
Level(String name, boolean display) {
this.name = name;
this.display = display;
}
public String getName(){
public String getName() {
return name;
}
public boolean display(){
public boolean display() {
return display;
}
}
private BufferedWriter writer=null;
public Logger(){
private BufferedWriter writer = null;
public Logger() {
//Logger isn't created.
}
public Logger(String logFile) {
this(new File(logFile));
}
public Logger(File logFile){
public Logger(File logFile) {
try {
if(!logFile.getParentFile().exists()){
if (!logFile.getParentFile().exists()) {
logFile.getParentFile().mkdirs();
}
if(!logFile.exists())
if (!logFile.exists()) {
logFile.createNewFile();
}
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logFile), "UTF-8"));
Files.newOutputStream(logFile.toPath()), StandardCharsets.UTF_8));
System.out.println("Log Path: " + logFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public void close(){
if(writer!=null){
public void close() {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
@@ -63,15 +84,31 @@ public class Logger {
}
}
}
public void log(Level level,String msg){
if(!level.display()&&writer==null)
/**
* Judge if a level can be printed to standard output(System.out) with config.
*
* @param level log level
* @return true - print
*/
private boolean canPrintToStdOut(Level level) {
return level.display() && enableLogStdOut;
}
public void log(Level level, String msg) {
//When it neither be printed to standard output nor write to file
if (!canPrintToStdOut(level) && writer == null) {
return;
}
//Format, print and write
String sb = String.format("[%s %s] %s", Thread.currentThread().getName(), level.getName(), msg);
if(level.display())
if (canPrintToStdOut(level)) {
System.out.println(sb);
if(writer==null)
}
if (writer == null) {
return;
}
try {
String sb2 = String.format("[%s] %s\r\n", DATE_FORMAT.format(new Date()), sb);
writer.write(sb2);
@@ -80,27 +117,34 @@ public class Logger {
e.printStackTrace();
}
}
public void debug(String msg){
log(Level.DEBUG,msg);
public void debug(String msg) {
log(Level.DEBUG, msg);
}
public void debug(String format, Object... objs) {
debug(String.format(format, objs));
}
public void info(String msg){
log(Level.INFO,msg);
public void info(String msg) {
log(Level.INFO, msg);
}
public void info(String format, Object... objs){
public void info(String format, Object... objs) {
info(String.format(format, objs));
}
public void warning(String msg){
log(Level.WARNING,msg);
public void warning(String msg) {
log(Level.WARNING, msg);
}
public void warning(String format, Object... objs){
public void warning(String format, Object... objs) {
warning(String.format(format, objs));
}
public void warning(Throwable e){
public void warning(Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log(Level.WARNING,"Exception: "+sw.toString());
log(Level.WARNING, "Exception: " + sw);
}
}
@@ -26,21 +26,29 @@ public class Config {
public List<SkinSiteProfile> loadlist;
//Function
public boolean enableDynamicSkull=true;
public boolean enableTransparentSkin=true;
public boolean enableDynamicSkull = true;
public boolean enableTransparentSkin = true;
public boolean forceIgnoreHttpsCertificate = false;
public boolean forceLoadAllTextures=false;
public boolean forceLoadAllTextures = false;
public boolean enableCape = true;
public int threadPoolSize = 3;
public int retryTime = 1;
/**
* Can logger write message to standard output(System.out).
* Because standard output won't write to latest.log after Forge 1.17,
* printing to standard output is meaningless,
* which makes this switch default value is <code>false</code>.
* @since 14.15
*/
public boolean enableLogStdOut = false;
//Profile Cache
public int cacheExpiry=30;
public int cacheExpiry = 30;
public boolean forceUpdateSkull = false;
public boolean enableLocalProfileCache=false;
public boolean enableLocalProfileCache = false;
//Network Cache
public boolean enableCacheAutoClean=false;
public boolean enableCacheAutoClean = false;
public boolean forceDisableCache = false;
// Used by Gson to create an instance with default value.
@@ -49,21 +57,21 @@ public class Config {
}
//Init config
public Config(List<SkinSiteProfile> loadlist){
this.version=CustomSkinLoader.CustomSkinLoader_VERSION;
this.buildNumber=CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER;
this.loadlist=loadlist;
public Config(List<SkinSiteProfile> loadlist) {
this.version = CustomSkinLoader.CustomSkinLoader_VERSION;
this.buildNumber = CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER;
this.loadlist = loadlist;
}
public static Config loadConfig0() {
Config config=loadConfig();
Config config = loadConfig();
//LoadList null checker
if(config.loadlist==null){
config.loadlist=new ArrayList<SkinSiteProfile>();
}else{
for(int i=0;i<config.loadlist.size();i++){
if(config.loadlist.get(i)==null)
if (config.loadlist == null) {
config.loadlist = new ArrayList<>();
} else {
for (int i = 0; i < config.loadlist.size(); i++) {
if (config.loadlist.get(i) == null)
config.loadlist.remove(i--);
}
}
@@ -74,24 +82,25 @@ public class Config {
config.initLocalFolder();
config.threadPoolSize = Math.max(config.threadPoolSize, 1);
config.retryTime = Math.max(config.retryTime, 0);
if(config.forceIgnoreHttpsCertificate)
if (config.forceIgnoreHttpsCertificate)
HttpUtil0.ignoreHttpsCertificate();
if(config.enableCacheAutoClean && !config.enableLocalProfileCache){
try{
if (config.enableCacheAutoClean && !config.enableLocalProfileCache) {
try {
FileUtils.deleteDirectory(HttpRequestUtil.CACHE_DIR);
FileUtils.deleteDirectory(HttpTextureUtil.getCacheDir());
CustomSkinLoader.logger.info("Successfully cleaned cache.");
}catch(Exception e){
CustomSkinLoader.logger.warning("Exception occurs while cleaning cache: "+e.toString());
} catch (Exception e) {
CustomSkinLoader.logger.warning("Exception occurs while cleaning cache: " + e);
}
}
//Check config version
Version configVersion = Version.of(config.version);
if (CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER == 0 // Custom builds
|| configVersion.compareTo(CustomSkinLoader.CustomSkinLoader_VERSION) < 0
|| config.buildNumber < CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER) {
CustomSkinLoader.logger.info("Config File is out of date: " + config.version + ", build number: " + config.buildNumber);
|| configVersion.compareTo(CustomSkinLoader.CustomSkinLoader_VERSION) < 0
|| config.buildNumber < CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER) {
CustomSkinLoader.logger.info("Config File is out of date: " + config.version +
", build number: " + config.buildNumber);
config.version = CustomSkinLoader.CustomSkinLoader_VERSION;
config.buildNumber = CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER;
}
@@ -102,51 +111,53 @@ public class Config {
try {
Object value = field.get(config);
CustomSkinLoader.logger.info(field.getName() + " : " + value);
} catch (Exception ignored) { }
} catch (Exception ignored) {
}
}
return config;
}
private static Config loadConfig() {
CustomSkinLoader.logger.info("Config File: "+CustomSkinLoader.CONFIG_FILE.getAbsolutePath());
if(!CustomSkinLoader.CONFIG_FILE.exists()){
CustomSkinLoader.logger.info("Config File: " + CustomSkinLoader.CONFIG_FILE.getAbsolutePath());
if (!CustomSkinLoader.CONFIG_FILE.exists()) {
CustomSkinLoader.logger.info("Config file not found, use default instead.");
return initConfig();
}
try {
CustomSkinLoader.logger.info("Try to load config.");
String json=FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE, "UTF-8");
Config config=Objects.requireNonNull(CustomSkinLoader.GSON.fromJson(json, Config.class));
String json = FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE, "UTF-8");
Config config = Objects.requireNonNull(CustomSkinLoader.GSON.fromJson(json, Config.class));
CustomSkinLoader.logger.info("Successfully load config.");
return config;
}catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load config, use default instead.("+e.toString()+")");
} catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load config, use default instead.(" + e + ")");
createBrokenFile(CustomSkinLoader.CONFIG_FILE);
return initConfig();
}
}
private void loadExtraList(){
File listAddition=new File(CustomSkinLoader.DATA_DIR,"ExtraList");
if(!listAddition.isDirectory()){
private void loadExtraList() {
File listAddition = new File(CustomSkinLoader.DATA_DIR, "ExtraList");
if (!listAddition.isDirectory()) {
listAddition.mkdirs();
return;
}
List<SkinSiteProfile> adds=new ArrayList<SkinSiteProfile>();
File[] files=listAddition.listFiles();
for(File file: files != null ? files : new File[0]){
if(!file.getName().toLowerCase().endsWith(".json")&&!file.getName().toLowerCase().endsWith(".txt"))
List<SkinSiteProfile> adds = new ArrayList<>();
File[] files = listAddition.listFiles();
for (File file : files != null ? files : new File[0]) {
if (!file.getName().toLowerCase().endsWith(".json") && !file.getName().toLowerCase().endsWith(".txt"))
continue;
try {
CustomSkinLoader.logger.info("Try to load Extra List.("+file.getName()+")");
String json=FileUtils.readFileToString(file, "UTF-8");
SkinSiteProfile ssp=CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class);
CustomSkinLoader.logger.info("Try to load Extra List.(" + file.getName() + ")");
String json = FileUtils.readFileToString(file, "UTF-8");
SkinSiteProfile ssp = CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class);
CustomSkinLoader.logger.info("Successfully load Extra List.");
if (ssp.type != null) {
ProfileLoader.IProfileLoader loader = ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if (loader == null) {
CustomSkinLoader.logger.info("Extra List will be ignored: Type '" + ssp.type + "' is not defined.");
CustomSkinLoader.logger.info("Extra List will be ignored: Type '" + ssp.type +
"' is not defined.");
continue;
}
boolean duplicate = false;
@@ -166,36 +177,37 @@ public class Config {
}
file.delete();
} else {
CustomSkinLoader.logger.info("Extra List is invalid: Type is not defined.(" + file.getName() + ")");
CustomSkinLoader.logger.info("Extra List is invalid: Type is not defined.(" +
file.getName() + ")");
createBrokenFile(file);
}
}catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load Extra List.("+e.toString()+")");
} catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load Extra List.(" + e + ")");
createBrokenFile(file);
}
}
if(adds.size()!=0){
if (adds.size() != 0) {
adds.addAll(this.loadlist);
this.loadlist=adds;
this.loadlist = adds;
}
}
private void updateLoadlist() {
PluginLoader.PLUGINS.stream()
.map(ICustomSkinLoaderPlugin::getDefaultProfiles)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.forEach(profile -> this.loadlist.stream()
.filter(ssp -> profile.getName().equals(ssp.name))
.forEach(profile::updateSkinSiteProfile));
.map(ICustomSkinLoaderPlugin::getDefaultProfiles)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.forEach(profile -> this.loadlist.stream()
.filter(ssp -> profile.getName().equals(ssp.name))
.forEach(profile::updateSkinSiteProfile));
}
private void initLocalFolder(){
for(SkinSiteProfile ssp:this.loadlist){
if(ssp.type==null)
private void initLocalFolder() {
for (SkinSiteProfile ssp : this.loadlist) {
if (ssp.type == null)
continue;
ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if(loader==null)
ProfileLoader.IProfileLoader loader = ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if (loader == null)
continue;
loader.init(ssp);
}
@@ -237,16 +249,17 @@ public class Config {
writeConfig(config, false);
return config;
}
private static void writeConfig(Config config, boolean update){
String json=CustomSkinLoader.GSON.toJson(config);
if(CustomSkinLoader.CONFIG_FILE.exists())
private static void writeConfig(Config config, boolean update) {
String json = CustomSkinLoader.GSON.toJson(config);
if (CustomSkinLoader.CONFIG_FILE.exists())
CustomSkinLoader.CONFIG_FILE.delete();
try {
CustomSkinLoader.CONFIG_FILE.createNewFile();
FileUtils.write(CustomSkinLoader.CONFIG_FILE, json, "UTF-8");
CustomSkinLoader.logger.info("Successfully "+(update?"update":"create")+" config.");
CustomSkinLoader.logger.info("Successfully " + (update ? "update" : "create") + " config.");
} catch (Exception e) {
CustomSkinLoader.logger.info("Failed to "+(update?"update":"create")+" config.("+e.toString()+")");
CustomSkinLoader.logger.info("Failed to " + (update ? "update" : "create") + " config.(" + e + ")");
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
name=CustomSkinLoader
group=customskinloader
version=14.14
version=14.15
dev_version=
#RELEASE: snapshot=0
snapshot=0
snapshot=1