This commit is contained in:
huanghongxun
2015-11-17 12:51:04 +08:00
parent 39b6d68006
commit 159a992081
243 changed files with 2990 additions and 2836 deletions

View File

@@ -53,10 +53,14 @@ public final class Launcher {
ArrayList<String> cmdList = new ArrayList<>(); ArrayList<String> cmdList = new ArrayList<>();
for (String s : args) for (String s : args)
if (s.startsWith("-cp=")) classPath = classPath.concat(s.substring("-cp=".length())); if (s.startsWith("-cp="))
else if (s.startsWith("-mainClass=")) mainClass = s.substring("-mainClass=".length()); classPath = classPath.concat(s.substring("-cp=".length()));
else if (s.equals("-debug")) showInfo = true; else if (s.startsWith("-mainClass="))
else cmdList.add(s); mainClass = s.substring("-mainClass=".length());
else if (s.equals("-debug"))
showInfo = true;
else
cmdList.add(s);
String[] tokenized = StrUtils.tokenize(classPath, File.pathSeparator); String[] tokenized = StrUtils.tokenize(classPath, File.pathSeparator);
int len = tokenized.length; int len = tokenized.length;
@@ -65,7 +69,8 @@ public final class Launcher {
LogWindow.instance.setTerminateGame(() -> Utils.shutdownForcely(1)); LogWindow.instance.setTerminateGame(() -> Utils.shutdownForcely(1));
try { try {
File logFile = new File("hmclmc.log"); File logFile = new File("hmclmc.log");
if (!logFile.exists()) logFile.createNewFile(); if (!logFile.exists())
logFile.createNewFile();
FileOutputStream tc = new FileOutputStream(logFile); FileOutputStream tc = new FileOutputStream(logFile);
DoubleOutputStream out = new DoubleOutputStream(tc, System.out); DoubleOutputStream out = new DoubleOutputStream(tc, System.out);
System.setOut(new LauncherPrintStream(out)); System.setOut(new LauncherPrintStream(out));
@@ -112,7 +117,7 @@ public final class Launcher {
int flag = 0; int flag = 0;
try { try {
minecraftMain.invoke(null, new Object[]{(String[]) cmdList.toArray(new String[cmdList.size()])}); minecraftMain.invoke(null, new Object[] {(String[]) cmdList.toArray(new String[cmdList.size()])});
} catch (Throwable throwable) { } catch (Throwable throwable) {
String trace = StrUtils.getStackTrace(throwable); String trace = StrUtils.getStackTrace(throwable);
final String advice = MinecraftCrashAdvicer.getAdvice(trace); final String advice = MinecraftCrashAdvicer.getAdvice(trace);

View File

@@ -91,7 +91,7 @@ public final class Main implements Runnable {
try { try {
sslContext = SSLContext.getInstance("TLS"); sslContext = SSLContext.getInstance("TLS");
X509TrustManager[] xtmArray = new X509TrustManager[]{XTM}; X509TrustManager[] xtmArray = new X509TrustManager[] {XTM};
sslContext.init(null, xtmArray, new java.security.SecureRandom()); sslContext.init(null, xtmArray, new java.security.SecureRandom());
} catch (GeneralSecurityException gse) { } catch (GeneralSecurityException gse) {
} }
@@ -143,9 +143,9 @@ public final class Main implements Runnable {
if (mainClass != null) { if (mainClass != null) {
ArrayList<String> al = new ArrayList<>(Arrays.asList(args)); ArrayList<String> al = new ArrayList<>(Arrays.asList(args));
al.add("notfound"); al.add("notfound");
new URLClassLoader(new URL[]{jar.toURI().toURL()}, new URLClassLoader(new URL[] {jar.toURI().toURL()},
URLClassLoader.getSystemClassLoader().getParent()).loadClass(mainClass) URLClassLoader.getSystemClassLoader().getParent()).loadClass(mainClass)
.getMethod("main", String[].class).invoke(null, new Object[]{al.toArray(new String[0])}); .getMethod("main", String[].class).invoke(null, new Object[] {al.toArray(new String[0])});
return; return;
} }
} }
@@ -216,22 +216,23 @@ public final class Main implements Runnable {
if (map != null && map.containsKey("pack")) if (map != null && map.containsKey("pack"))
try { try {
if (TaskWindow.getInstance().addTask(new Upgrader(map.get("pack"), Settings.UPDATE_CHECKER.versionString)).start()) { if (TaskWindow.getInstance().addTask(new Upgrader(map.get("pack"), Settings.UPDATE_CHECKER.versionString)).start()) {
new ProcessBuilder(new String[]{IOUtils.getJavaDir(), "-jar", Upgrader.getSelf(Settings.UPDATE_CHECKER.versionString).getAbsolutePath()}).directory(new File(".")).start(); new ProcessBuilder(new String[] {IOUtils.getJavaDir(), "-jar", Upgrader.getSelf(Settings.UPDATE_CHECKER.versionString).getAbsolutePath()}).directory(new File(".")).start();
System.exit(0); System.exit(0);
} }
} catch (IOException ex) { } catch (IOException ex) {
HMCLog.warn("Failed to create upgrader", ex); HMCLog.warn("Failed to create upgrader", ex);
} }
if (MessageBox.Show(C.i18n("update.newest_version") + Settings.UPDATE_CHECKER.getNewVersion().firstVer + "." + Settings.UPDATE_CHECKER.getNewVersion().secondVer + "." + Settings.UPDATE_CHECKER.getNewVersion().thirdVer + "\n" if (MessageBox.Show(C.i18n("update.newest_version") + Settings.UPDATE_CHECKER.getNewVersion().firstVer + "." + Settings.UPDATE_CHECKER.getNewVersion().secondVer + "." + Settings.UPDATE_CHECKER.getNewVersion().thirdVer + "\n"
+ C.i18n("update.should_open_link"), + C.i18n("update.should_open_link"),
MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) { MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
String url = C.URL_PUBLISH; String url = C.URL_PUBLISH;
if (map != null) if (map != null)
if (map.containsKey(OS.os().checked_name)) if (map.containsKey(OS.os().checked_name))
url = map.get(OS.os().checked_name); url = map.get(OS.os().checked_name);
else if (map.containsKey(OS.UNKOWN.checked_name)) else if (map.containsKey(OS.UNKOWN.checked_name))
url = map.get(OS.UNKOWN.checked_name); url = map.get(OS.UNKOWN.checked_name);
if (url == null) url = C.URL_PUBLISH; if (url == null)
url = C.URL_PUBLISH;
try { try {
java.awt.Desktop.getDesktop().browse(new URI(url)); java.awt.Desktop.getDesktop().browse(new URI(url));
} catch (URISyntaxException | IOException e) { } catch (URISyntaxException | IOException e) {

View File

@@ -58,7 +58,7 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
HMCLog.log("On making head command."); HMCLog.log("On making head command.");
String str = v.getJavaDir(); String str = v.getJavaDir();
if(!v.getJavaDirFile().exists()) { if (!v.getJavaDirFile().exists()) {
MessageBox.Show(C.i18n("launch.wrong_javadir")); MessageBox.Show(C.i18n("launch.wrong_javadir"));
v.setJava(null); v.setJava(null);
str = v.getJavaDir(); str = v.getJavaDir();
@@ -66,14 +66,15 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
JdkVersion jv = new JdkVersion(str); JdkVersion jv = new JdkVersion(str);
if (Settings.getInstance().getJava().contains(jv)) if (Settings.getInstance().getJava().contains(jv))
jv = Settings.getInstance().getJava().get(Settings.getInstance().getJava().indexOf(jv)); jv = Settings.getInstance().getJava().get(Settings.getInstance().getJava().indexOf(jv));
else try { else
jv = JdkVersion.getJavaVersionFromExecutable(str); try {
Settings.getInstance().getJava().add(jv); jv = JdkVersion.getJavaVersionFromExecutable(str);
Settings.save(); Settings.getInstance().getJava().add(jv);
} catch (IOException ex) { Settings.save();
HMCLog.warn("Failed to get java version", ex); } catch (IOException ex) {
jv = null; HMCLog.warn("Failed to get java version", ex);
} jv = null;
}
res.add(str); res.add(str);
if (v.hasJavaArgs()) if (v.hasJavaArgs())
@@ -119,7 +120,8 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
MessageBox.Show(C.i18n("launch.too_big_memory_alloc_free_space_too_low", a)); MessageBox.Show(C.i18n("launch.too_big_memory_alloc_free_space_too_low", a));
} }
String a = "-Xmx" + v.getMaxMemory(); String a = "-Xmx" + v.getMaxMemory();
if (MathUtils.canParseInt(v.getMaxMemory())) a += "m"; if (MathUtils.canParseInt(v.getMaxMemory()))
a += "m";
res.add(a); res.add(a);
} }
@@ -164,9 +166,11 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
res.add(args.length > 1 ? args[1] : "25565"); res.add(args.length > 1 ? args[1] : "25565");
} }
if (v.isFullscreen()) res.add("--fullscreen"); if (v.isFullscreen())
res.add("--fullscreen");
if (v.isDebug() && !v.isCanceledWrapper()) res.add("-debug"); if (v.isDebug() && !v.isCanceledWrapper())
res.add("-debug");
if (StrUtils.isNotBlank(v.getMinecraftArgs())) if (StrUtils.isNotBlank(v.getMinecraftArgs()))
res.addAll(Arrays.asList(v.getMinecraftArgs().split(" "))); res.addAll(Arrays.asList(v.getMinecraftArgs().split(" ")));

View File

@@ -49,13 +49,15 @@ public class DefaultGameLauncher extends GameLauncher {
parallelTask.addDependsTask(new LibraryDownloadTask(s)); parallelTask.addDependsTask(new LibraryDownloadTask(s));
dw.addTask(parallelTask); dw.addTask(parallelTask);
boolean flag = true; boolean flag = true;
if (t.size() > 0) flag = dw.start(); if (t.size() > 0)
flag = dw.start();
if (!flag && MessageBox.Show(C.i18n("launch.not_finished_downloading_libraries"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) if (!flag && MessageBox.Show(C.i18n("launch.not_finished_downloading_libraries"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
flag = true; flag = true;
return flag; return flag;
}); });
decompressNativesEvent.register((sender, value) -> { decompressNativesEvent.register((sender, value) -> {
if (value == null) return false; if (value == null)
return false;
for (int i = 0; i < value.decompressFiles.length; i++) for (int i = 0; i < value.decompressFiles.length; i++)
try { try {
Compressor.unzip(value.decompressFiles[i], value.decompressTo, value.extractRules[i]); Compressor.unzip(value.decompressFiles[i], value.decompressTo, value.extractRules[i]);

View File

@@ -154,8 +154,10 @@ public class GameLauncher {
* According to the name... * According to the name...
* *
* @param launcherName the name of launch bat/sh * @param launcherName the name of launch bat/sh
* @param str launch command * @param str launch command
*
* @return launcher location * @return launcher location
*
* @throws java.io.IOException write contents failed. * @throws java.io.IOException write contents failed.
*/ */
public File makeLauncher(String launcherName, List str) throws IOException { public File makeLauncher(String launcherName, List str) throws IOException {

View File

@@ -27,6 +27,7 @@ import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion;
/** /**
* Provide everything of the Minecraft of a Profile. * Provide everything of the Minecraft of a Profile.
*
* @see org.jackhuang.hellominecraft.launcher.version.MinecraftVersionManager * @see org.jackhuang.hellominecraft.launcher.version.MinecraftVersionManager
* @author huangyuhui * @author huangyuhui
*/ */
@@ -40,14 +41,18 @@ public abstract class IMinecraftProvider {
/** /**
* Get the run directory of given version. * Get the run directory of given version.
*
* @param id the given version name * @param id the given version name
*
* @return the run directory * @return the run directory
*/ */
public abstract File getRunDirectory(String id); public abstract File getRunDirectory(String id);
/** /**
* Get the libraries that need to download. * Get the libraries that need to download.
*
* @param type where to download * @param type where to download
*
* @return the library collection * @return the library collection
*/ */
public abstract List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType type); public abstract List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType type);
@@ -62,6 +67,7 @@ public abstract class IMinecraftProvider {
/** /**
* Returns the thing like ".minecraft/resourcepacks". * Returns the thing like ".minecraft/resourcepacks".
*
* @return the thing * @return the thing
*/ */
public abstract File getResourcePacks(); public abstract File getResourcePacks();
@@ -84,63 +90,78 @@ public abstract class IMinecraftProvider {
* Provide the Minecraft Loader to generate the launching command. * Provide the Minecraft Loader to generate the launching command.
* *
* @see org.jackhuang.hellominecraft.launcher.launch.IMinecraftLoader * @see org.jackhuang.hellominecraft.launcher.launch.IMinecraftLoader
* @param p player informations, including username & auth_token * @param p player informations, including username & auth_token
* @param type where to download * @param type where to download
*
* @return what you want * @return what you want
*
* @throws IllegalStateException circular denpendency versions * @throws IllegalStateException circular denpendency versions
*/ */
public abstract IMinecraftLoader provideMinecraftLoader(UserProfileProvider p, DownloadType type) throws IllegalStateException; public abstract IMinecraftLoader provideMinecraftLoader(UserProfileProvider p, DownloadType type) throws IllegalStateException;
/** /**
* Rename version * Rename version
*
* @param from The old name * @param from The old name
* @param to The new name * @param to The new name
*
* @return Is the action successful? * @return Is the action successful?
*/ */
public abstract boolean renameVersion(String from, String to); public abstract boolean renameVersion(String from, String to);
/** /**
* Remove the given version from disk. * Remove the given version from disk.
*
* @param a the version name * @param a the version name
*
* @return Is the action successful? * @return Is the action successful?
*/ */
public abstract boolean removeVersionFromDisk(String a); public abstract boolean removeVersionFromDisk(String a);
/** /**
* Redownload the Minecraft json of the given version. * Redownload the Minecraft json of the given version.
*
* @param a the given version name * @param a the given version name
*
* @return Is the action successful? * @return Is the action successful?
*/ */
public abstract boolean refreshJson(String a); public abstract boolean refreshJson(String a);
/** /**
* Redownload the Asset index json of the given version. * Redownload the Asset index json of the given version.
*
* @param a the given version name * @param a the given version name
*
* @return Is the action successful? * @return Is the action successful?
*/ */
public abstract boolean refreshAssetsIndex(String a); public abstract boolean refreshAssetsIndex(String a);
/** /**
* Choose a version randomly. * Choose a version randomly.
*
* @return the version * @return the version
*/ */
public abstract MinecraftVersion getOneVersion(); public abstract MinecraftVersion getOneVersion();
/** /**
* All Minecraft version in this profile. * All Minecraft version in this profile.
*
* @return the collection of all Minecraft version * @return the collection of all Minecraft version
*/ */
public abstract Collection<MinecraftVersion> getVersions(); public abstract Collection<MinecraftVersion> getVersions();
/** /**
* Get the Minecraft json instance of given version. * Get the Minecraft json instance of given version.
*
* @param id the given version name * @param id the given version name
*
* @return the Minecraft json instance * @return the Minecraft json instance
*/ */
public abstract MinecraftVersion getVersionById(String id); public abstract MinecraftVersion getVersionById(String id);
/** /**
* getVersions().size() * getVersions().size()
*
* @return getVersions().size() * @return getVersions().size()
*/ */
public abstract int getVersionCount(); public abstract int getVersionCount();
@@ -152,8 +173,10 @@ public abstract class IMinecraftProvider {
/** /**
* Install a new version to this profile. * Install a new version to this profile.
*
* @param version the new version name * @param version the new version name
* @param type where to download * @param type where to download
*
* @return Is the action successful? * @return Is the action successful?
*/ */
public abstract boolean install(String version, DownloadType type); public abstract boolean install(String version, DownloadType type);

View File

@@ -36,7 +36,8 @@ public class LaunchScriptFinisher implements Event<List<String>> {
boolean flag = false; boolean flag = false;
try { try {
String s = JOptionPane.showInputDialog(C.i18n("mainwindow.enter_script_name")); String s = JOptionPane.showInputDialog(C.i18n("mainwindow.enter_script_name"));
if (s != null) MessageBox.Show(C.i18n("mainwindow.make_launch_succeed") + " " + ((GameLauncher) sender).makeLauncher(s, str).getAbsolutePath()); if (s != null)
MessageBox.Show(C.i18n("mainwindow.make_launch_succeed") + " " + ((GameLauncher) sender).makeLauncher(s, str).getAbsolutePath());
flag = true; flag = true;
} catch (IOException ex) { } catch (IOException ex) {
MessageBox.Show(C.i18n("mainwindow.make_launch_script_failed")); MessageBox.Show(C.i18n("mainwindow.make_launch_script_failed"));

View File

@@ -79,7 +79,7 @@ public class LibraryDownloadTask extends FileDownloadTask {
} }
public static void unpackLibrary(File output, File input) public static void unpackLibrary(File output, File input)
throws IOException { throws IOException {
HMCLog.log("Unpacking " + input); HMCLog.log("Unpacking " + input);
if (output.exists()) if (output.exists())
output.delete(); output.delete();

View File

@@ -67,7 +67,8 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
} }
library += IOUtils.tryGetCanonicalFilePath(provider.getMinecraftJar()) + File.pathSeparator; library += IOUtils.tryGetCanonicalFilePath(provider.getMinecraftJar()) + File.pathSeparator;
library = library.substring(0, library.length() - File.pathSeparator.length()); library = library.substring(0, library.length() - File.pathSeparator.length());
if (v.isCanceledWrapper()) res.add("-cp"); if (v.isCanceledWrapper())
res.add("-cp");
res.add(library); res.add(library);
String mainClass = version.mainClass; String mainClass = version.mainClass;
res.add((v.isCanceledWrapper() ? "" : "-mainClass=") + mainClass); res.add((v.isCanceledWrapper() ? "" : "-mainClass=") + mainClass);
@@ -76,12 +77,11 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
String[] splitted = org.jackhuang.hellominecraft.utils.StrUtils.tokenize(arg); String[] splitted = org.jackhuang.hellominecraft.utils.StrUtils.tokenize(arg);
if (!checkAssetsExist()) if (!checkAssetsExist())
if (MessageBox.Show(C.i18n("assets.no_assets"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) { if (MessageBox.Show(C.i18n("assets.no_assets"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
IAssetsHandler.ASSETS_HANDLER.getList(version, provider, (value) -> { IAssetsHandler.ASSETS_HANDLER.getList(version, provider, (value) -> {
if (value != null) if (value != null)
TaskWindow.getInstance().addTask(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(dt.getProvider())).start(); TaskWindow.getInstance().addTask(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(dt.getProvider())).start();
}); });
}
String game_assets = reconstructAssets().getAbsolutePath(); String game_assets = reconstructAssets().getAbsolutePath();
@@ -133,7 +133,8 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
try { try {
AssetsIndex index = (AssetsIndex) C.gson.fromJson(FileUtils.readFileToString(indexFile, "UTF-8"), AssetsIndex.class); AssetsIndex index = (AssetsIndex) C.gson.fromJson(FileUtils.readFileToString(indexFile, "UTF-8"), AssetsIndex.class);
if (index == null) return false; if (index == null)
return false;
for (Map.Entry entry : index.getFileMap().entrySet()) for (Map.Entry entry : index.getFileMap().entrySet())
if (!new File(new File(objectDir, ((AssetsObject) entry.getValue()).getHash().substring(0, 2)), ((AssetsObject) entry.getValue()).getHash()).exists()) if (!new File(new File(objectDir, ((AssetsObject) entry.getValue()).getHash().substring(0, 2)), ((AssetsObject) entry.getValue()).getHash()).exists())
return false; return false;
@@ -159,7 +160,8 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
try { try {
AssetsIndex index = (AssetsIndex) C.gson.fromJson(FileUtils.readFileToString(indexFile, "UTF-8"), AssetsIndex.class); AssetsIndex index = (AssetsIndex) C.gson.fromJson(FileUtils.readFileToString(indexFile, "UTF-8"), AssetsIndex.class);
if (index == null) return assetsDir; if (index == null)
return assetsDir;
if (index.isVirtual()) { if (index.isVirtual()) {
int cnt = 0; int cnt = 0;
HMCLog.log("Reconstructing virtual assets folder at " + virtualRoot); HMCLog.log("Reconstructing virtual assets folder at " + virtualRoot);
@@ -174,7 +176,8 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
} }
} }
// If the scale new format existent file is lower then 0.1, use the old format. // If the scale new format existent file is lower then 0.1, use the old format.
if (cnt * 10 < tot) return assetsDir; if (cnt * 10 < tot)
return assetsDir;
} }
} catch (IOException | JsonSyntaxException e) { } catch (IOException | JsonSyntaxException e) {
HMCLog.warn("Failed to create virutal assets.", e); HMCLog.warn("Failed to create virutal assets.", e);

View File

@@ -67,7 +67,8 @@ public final class Profile {
public Profile(Profile v) { public Profile(Profile v) {
this(); this();
if (v == null) return; if (v == null)
return;
name = v.name; name = v.name;
gameDir = v.gameDir; gameDir = v.gameDir;
maxMemory = v.maxMemory; maxMemory = v.maxMemory;
@@ -89,25 +90,30 @@ public final class Profile {
} }
public IMinecraftProvider getMinecraftProvider() { public IMinecraftProvider getMinecraftProvider() {
if (minecraftProvider == null) minecraftProvider = new MinecraftVersionManager(this); if (minecraftProvider == null)
minecraftProvider = new MinecraftVersionManager(this);
return minecraftProvider; return minecraftProvider;
} }
public MinecraftVersion getSelectedMinecraftVersion() { public MinecraftVersion getSelectedMinecraftVersion() {
if (StrUtils.isBlank(selectedMinecraftVersion)) { if (StrUtils.isBlank(selectedMinecraftVersion)) {
MinecraftVersion v = getMinecraftProvider().getOneVersion(); MinecraftVersion v = getMinecraftProvider().getOneVersion();
if (v == null) return null; if (v == null)
return null;
selectedMinecraftVersion = v.id; selectedMinecraftVersion = v.id;
return v; return v;
} }
MinecraftVersion v = getMinecraftProvider().getVersionById(selectedMinecraftVersion); MinecraftVersion v = getMinecraftProvider().getVersionById(selectedMinecraftVersion);
if (v == null) v = getMinecraftProvider().getOneVersion(); if (v == null)
if (v != null) setSelectedMinecraftVersion(v.id); v = getMinecraftProvider().getOneVersion();
if (v != null)
setSelectedMinecraftVersion(v.id);
return v; return v;
} }
public String getGameDir() { public String getGameDir() {
if (StrUtils.isBlank(gameDir)) gameDir = MCUtils.getInitGameDir().getPath(); if (StrUtils.isBlank(gameDir))
gameDir = MCUtils.getInitGameDir().getPath();
return IOUtils.addSeparator(gameDir); return IOUtils.addSeparator(gameDir);
} }
@@ -132,8 +138,10 @@ public final class Profile {
public String getJavaDir() { public String getJavaDir() {
Java j = getJava(); Java j = getJava();
if (j.getHome() == null) return javaDir; if (j.getHome() == null)
else return j.getJava(); return javaDir;
else
return j.getJava();
} }
public String getSettingsJavaDir() { public String getSettingsJavaDir() {
@@ -169,14 +177,16 @@ public final class Profile {
this.java = Settings.JAVA.get(0).getName(); this.java = Settings.JAVA.get(0).getName();
else { else {
int idx = Settings.JAVA.indexOf(java); int idx = Settings.JAVA.indexOf(java);
if (idx == -1) return; if (idx == -1)
return;
this.java = java.getName(); this.java = java.getName();
} }
Settings.save(); Settings.save();
} }
public File getFolder(String folder) { public File getFolder(String folder) {
if (getSelectedMinecraftVersion() == null) return new File(getCanonicalGameDirFile(), folder); if (getSelectedMinecraftVersion() == null)
return new File(getCanonicalGameDirFile(), folder);
return new File(getMinecraftProvider().getRunDirectory(getSelectedMinecraftVersion().id), folder); return new File(getMinecraftProvider().getRunDirectory(getSelectedMinecraftVersion().id), folder);
} }
@@ -193,7 +203,8 @@ public final class Profile {
} }
public String getJavaArgs() { public String getJavaArgs() {
if (StrUtils.isBlank(javaArgs)) return ""; if (StrUtils.isBlank(javaArgs))
return "";
return javaArgs; return javaArgs;
} }
@@ -207,7 +218,8 @@ public final class Profile {
} }
public String getMaxMemory() { public String getMaxMemory() {
if (StrUtils.isBlank(maxMemory)) return String.valueOf(Utils.getSuggestedMemorySize()); if (StrUtils.isBlank(maxMemory))
return String.valueOf(Utils.getSuggestedMemorySize());
return maxMemory; return maxMemory;
} }
@@ -217,7 +229,8 @@ public final class Profile {
} }
public String getWidth() { public String getWidth() {
if (StrUtils.isBlank(width)) return "854"; if (StrUtils.isBlank(width))
return "854";
return width; return width;
} }
@@ -226,7 +239,8 @@ public final class Profile {
} }
public String getHeight() { public String getHeight() {
if (StrUtils.isBlank(height)) return "480"; if (StrUtils.isBlank(height))
return "480";
return height; return height;
} }
@@ -236,7 +250,8 @@ public final class Profile {
} }
public String getUserProperties() { public String getUserProperties() {
if (userProperties == null) return ""; if (userProperties == null)
return "";
return userProperties; return userProperties;
} }

View File

@@ -69,7 +69,7 @@ public final class Settings {
e.checkFormat(); e.checkFormat();
UPDATE_CHECKER = new UpdateChecker(new VersionNumber(Main.firstVer, Main.secondVer, Main.thirdVer), UPDATE_CHECKER = new UpdateChecker(new VersionNumber(Main.firstVer, Main.secondVer, Main.thirdVer),
"hmcl", Main::invokeUpdate); "hmcl", Main::invokeUpdate);
List<Java> temp = new ArrayList<>(); List<Java> temp = new ArrayList<>();
temp.add(new Java("Default", System.getProperty("java.home"))); temp.add(new Java("Default", System.getProperty("java.home")));
@@ -90,7 +90,8 @@ public final class Settings {
HMCLog.log("Settings file is empty, use the default settings."); HMCLog.log("Settings file is empty, use the default settings.");
else { else {
Config d = C.gsonPrettyPrinting.fromJson(str, Config.class); Config d = C.gsonPrettyPrinting.fromJson(str, Config.class);
if (d != null) c = d; if (d != null)
c = d;
} }
HMCLog.log("Initialized settings."); HMCLog.log("Initialized settings.");
} catch (IOException | JsonSyntaxException e) { } catch (IOException | JsonSyntaxException e) {

View File

@@ -60,7 +60,7 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
t.printStackTrace(); t.printStackTrace();
} }
return false; return false;
} else if(s.contains("java.lang.NoClassDefFoundError") || s.contains("java.lang.IncompatibleClassChangeError") || s.contains("java.lang.ClassFormatError")) { } else if (s.contains("java.lang.NoClassDefFoundError") || s.contains("java.lang.IncompatibleClassChangeError") || s.contains("java.lang.ClassFormatError")) {
System.out.println(C.i18n("crash.NoClassDefFound")); System.out.println(C.i18n("crash.NoClassDefFound"));
try { try {
MessageBox.Show(C.i18n("crash.NoClassDefFound")); MessageBox.Show(C.i18n("crash.NoClassDefFound"));
@@ -68,7 +68,7 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
t.printStackTrace(); t.printStackTrace();
} }
return false; return false;
} else if(s.contains("java.lang.OutOfMemoryError")) { } else if (s.contains("java.lang.OutOfMemoryError")) {
System.out.println("FUCKING MEMORY LIMIT!"); System.out.println("FUCKING MEMORY LIMIT!");
return false; return false;
} }
@@ -78,7 +78,8 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
@Override @Override
public void uncaughtException(Thread t, Throwable e) { public void uncaughtException(Thread t, Throwable e) {
String s = StrUtils.getStackTrace(e); String s = StrUtils.getStackTrace(e);
if (!s.contains("org.jackhuang.hellominecraft")) return; if (!s.contains("org.jackhuang.hellominecraft"))
return;
try { try {
String text = "\n---- Hello Minecraft! Crash Report ----\n"; String text = "\n---- Hello Minecraft! Crash Report ----\n";
text += " Version: " + Main.makeVersion() + "\n"; text += " Version: " + Main.makeVersion() + "\n";
@@ -90,8 +91,10 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
text += " Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version") + "\n"; text += " Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version") + "\n";
text += " Java Version: " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor") + "\n"; text += " Java Version: " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor") + "\n";
text += " Java VM Version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor") + "\n"; text += " Java VM Version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor") + "\n";
if (enableLogger) HMCLog.err(text); if (enableLogger)
else System.out.println(text); HMCLog.err(text);
else
System.out.println(text);
if (checkThrowable(e)) { if (checkThrowable(e)) {
SwingUtilities.invokeLater(() -> LogWindow.instance.showAsCrashWindow(UpdateChecker.OUT_DATED)); SwingUtilities.invokeLater(() -> LogWindow.instance.showAsCrashWindow(UpdateChecker.OUT_DATED));
@@ -111,7 +114,8 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
private static final HashSet<String> throwableSet = new HashSet<>(); private static final HashSet<String> throwableSet = new HashSet<>();
void reportToServer(String text, String stacktrace) { void reportToServer(String text, String stacktrace) {
if (throwableSet.contains(stacktrace)) return; if (throwableSet.contains(stacktrace))
return;
throwableSet.add(stacktrace); throwableSet.add(stacktrace);
new Thread(() -> { new Thread(() -> {
HashMap<String, String> map = new HashMap<>(); HashMap<String, String> map = new HashMap<>();

View File

@@ -86,7 +86,7 @@ public final class MCUtils {
r.version = ver; r.version = ver;
r.type = file.getEntry("META-INF/MANIFEST.MF") == null r.type = file.getEntry("META-INF/MANIFEST.MF") == null
? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK; ? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r; return r;
} }
@@ -131,12 +131,13 @@ public final class MCUtils {
return r; return r;
} }
int k = i; int k = i;
while (tmp[k] >= 48 && tmp[k] <= 57 || tmp[k] == 46) k--; while (tmp[k] >= 48 && tmp[k] <= 57 || tmp[k] == 46)
k--;
k++; k++;
r.version = new String(tmp, k, i - k + 1); r.version = new String(tmp, k, i - k + 1);
} }
r.type = file.getEntry("META-INF/MANIFEST.MF") == null r.type = file.getEntry("META-INF/MANIFEST.MF") == null
? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK; ? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r; return r;
} }
@@ -158,7 +159,7 @@ public final class MCUtils {
try { try {
localZipFile = new ZipFile(file); localZipFile = new ZipFile(file);
ZipEntry minecraft = localZipFile ZipEntry minecraft = localZipFile
.getEntry("net/minecraft/client/Minecraft.class"); .getEntry("net/minecraft/client/Minecraft.class");
if (minecraft != null) if (minecraft != null)
return getVersionOfOldMinecraft(localZipFile, minecraft); return getVersionOfOldMinecraft(localZipFile, minecraft);
ZipEntry main = localZipFile.getEntry("net/minecraft/client/main/Main.class"); ZipEntry main = localZipFile.getEntry("net/minecraft/client/main/Main.class");
@@ -214,7 +215,8 @@ public final class MCUtils {
} }
public static String minecraft() { public static String minecraft() {
if (OS.os() == OS.OSX) return "minecraft"; if (OS.os() == OS.OSX)
return "minecraft";
return ".minecraft"; return ".minecraft";
} }
@@ -224,7 +226,8 @@ public final class MCUtils {
gameDir = new File(gameDir, MCUtils.minecraft()); gameDir = new File(gameDir, MCUtils.minecraft());
if (!gameDir.exists()) { if (!gameDir.exists()) {
File newFile = MCUtils.getLocation(); File newFile = MCUtils.getLocation();
if (newFile.exists()) gameDir = newFile; if (newFile.exists())
gameDir = newFile;
} }
} }
return gameDir; return gameDir;
@@ -240,13 +243,13 @@ public final class MCUtils {
mvj.delete(); mvj.delete();
if (TaskWindow.getInstance() if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(vurl + id + ".json", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".json")) .addTask(new FileDownloadTask(vurl + id + ".json", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".json"))
.addTask(new FileDownloadTask(vurl + id + ".jar", IOUtils.tryGetCanonicalFile(mvj)).setTag(id + ".jar")) .addTask(new FileDownloadTask(vurl + id + ".jar", IOUtils.tryGetCanonicalFile(mvj)).setTag(id + ".jar"))
.start()) { .start()) {
MinecraftVersion mv; MinecraftVersion mv;
try { try {
mv = C.gson.fromJson(FileUtils.readFileToStringQuietly(mvt), MinecraftVersion.class); mv = C.gson.fromJson(FileUtils.readFileToStringQuietly(mvt), MinecraftVersion.class);
} catch(JsonSyntaxException ex) { } catch (JsonSyntaxException ex) {
HMCLog.err("Failed to parse minecraft version json.", ex); HMCLog.err("Failed to parse minecraft version json.", ex);
mv = null; mv = null;
} }
@@ -266,8 +269,8 @@ public final class MCUtils {
File mvt = new File(vpath, id + ".jar"); File mvt = new File(vpath, id + ".jar");
vpath.mkdirs(); vpath.mkdirs();
if (TaskWindow.getInstance() if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(vurl + id + ".jar", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".jar")) .addTask(new FileDownloadTask(vurl + id + ".jar", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".jar"))
.start()) { .start()) {
if (moved != null) if (moved != null)
moved.delete(); moved.delete();
return true; return true;
@@ -290,8 +293,8 @@ public final class MCUtils {
File mvt = new File(vpath, id + ".json"); File mvt = new File(vpath, id + ".json");
vpath.mkdirs(); vpath.mkdirs();
if (TaskWindow.getInstance() if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(vurl + id + ".json", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".json")) .addTask(new FileDownloadTask(vurl + id + ".json", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".json"))
.start()) { .start()) {
if (moved != null) if (moved != null)
moved.delete(); moved.delete();
return true; return true;
@@ -314,8 +317,8 @@ public final class MCUtils {
assetsIndex.renameTo(renamed); assetsIndex.renameTo(renamed);
} }
if (TaskWindow.getInstance() if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(aurl + assetsId + ".json", IOUtils.tryGetCanonicalFile(assetsIndex)).setTag(assetsId + ".json")) .addTask(new FileDownloadTask(aurl + assetsId + ".json", IOUtils.tryGetCanonicalFile(assetsIndex)).setTag(assetsId + ".json"))
.start()) { .start()) {
if (renamed != null) if (renamed != null)
renamed.delete(); renamed.delete();
return true; return true;

View File

@@ -67,10 +67,12 @@ public class ModInfo implements Comparable<ModInfo> {
} }
public static boolean isFileMod(File file) { public static boolean isFileMod(File file) {
if (file == null) return false; if (file == null)
return false;
String name = file.getName(); String name = file.getName();
boolean disabled = name.endsWith(".disabled"); boolean disabled = name.endsWith(".disabled");
if (disabled) name = name.substring(0, name.length() - ".disabled".length()); if (disabled)
name = name.substring(0, name.length() - ".disabled".length());
return name.endsWith(".zip") || name.endsWith(".jar"); return name.endsWith(".zip") || name.endsWith(".jar");
} }
@@ -80,11 +82,15 @@ public class ModInfo implements Comparable<ModInfo> {
try { try {
ZipFile jar = new ZipFile(f); ZipFile jar = new ZipFile(f);
ZipEntry entry = jar.getEntry("mcmod.info"); ZipEntry entry = jar.getEntry("mcmod.info");
if (entry == null) return i; if (entry == null)
return i;
else { else {
List<ModInfo> m = C.gson.fromJson(new InputStreamReader(jar.getInputStream(entry)), new TypeToken<List<ModInfo>>() { List<ModInfo> m = C.gson.fromJson(new InputStreamReader(jar.getInputStream(entry)), new TypeToken<List<ModInfo>>() {
}.getType()); }.getType());
if (m != null && m.size() > 0) { i = m.get(0); i.location = f; } if (m != null && m.size() > 0) {
i = m.get(0);
i.location = f;
}
} }
jar.close(); jar.close();
return i; return i;

View File

@@ -107,7 +107,8 @@ public class AssetsMojangLoader extends IAssetsHandler {
@Override @Override
public boolean isVersionAllowed(String formattedVersion) { public boolean isVersionAllowed(String formattedVersion) {
VersionNumber ur = VersionNumber.check(formattedVersion); VersionNumber ur = VersionNumber.check(formattedVersion);
if (ur == null) return false; if (ur == null)
return false;
return VersionNumber.check("1.6.0").compareTo(ur) <= 0; return VersionNumber.check("1.6.0").compareTo(ur) <= 0;
} }
} }

View File

@@ -63,9 +63,10 @@ public class AssetsMojangOldLoader extends IAssetsHandler {
@Override @Override
public boolean isVersionAllowed(String formattedVersion) { public boolean isVersionAllowed(String formattedVersion) {
VersionNumber r = VersionNumber.check(formattedVersion); VersionNumber r = VersionNumber.check(formattedVersion);
if (r == null) return false; if (r == null)
return false;
return VersionNumber.check("1.7.2").compareTo(r) >= 0 return VersionNumber.check("1.7.2").compareTo(r) >= 0
&& VersionNumber.check("1.6.0").compareTo(r) <= 0; && VersionNumber.check("1.6.0").compareTo(r) <= 0;
} }
@Override @Override

View File

@@ -38,10 +38,13 @@ public class AssetsObject {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
AssetsObject that = (AssetsObject) o; AssetsObject that = (AssetsObject) o;
if (this.size != that.size) return false; if (this.size != that.size)
return false;
return this.hash.equals(that.hash); return this.hash.equals(that.hash);
} }

View File

@@ -70,7 +70,7 @@ public abstract class IAssetsHandler {
* *
* @param mv The version that needs assets * @param mv The version that needs assets
* @param mp The Minecraft Provider * @param mp The Minecraft Provider
* @param x finished event * @param x finished event
*/ */
public abstract void getList(MinecraftVersion mv, IMinecraftProvider mp, Consumer<String[]> x); public abstract void getList(MinecraftVersion mv, IMinecraftProvider mp, Consumer<String[]> x);
@@ -78,6 +78,7 @@ public abstract class IAssetsHandler {
* Will be invoked when the user invoked "Download all assets". * Will be invoked when the user invoked "Download all assets".
* *
* @param sourceType Download Source * @param sourceType Download Source
*
* @return Download File Task * @return Download File Task
*/ */
public abstract Task getDownloadTask(IDownloadProvider sourceType); public abstract Task getDownloadTask(IDownloadProvider sourceType);
@@ -106,8 +107,10 @@ public abstract class IAssetsHandler {
String mark = assetsDownloadURLs.get(i); String mark = assetsDownloadURLs.get(i);
String url = u + mark; String url = u + mark;
File location = assetsLocalNames.get(i); File location = assetsLocalNames.get(i);
if (!location.getParentFile().exists()) location.getParentFile().mkdirs(); if (!location.getParentFile().exists())
if (location.isDirectory()) continue; location.getParentFile().mkdirs();
if (location.isDirectory())
continue;
boolean need = true; boolean need = true;
try { try {
if (location.exists()) { if (location.exists()) {
@@ -126,7 +129,8 @@ public abstract class IAssetsHandler {
HMCLog.warn("Failed to get hash: " + location, e); HMCLog.warn("Failed to get hash: " + location, e);
need = !location.exists(); need = !location.exists();
} }
if (need) al.add(new FileDownloadTask(url, location).setTag(mark)); if (need)
al.add(new FileDownloadTask(url, location).setTag(mark));
} }
return true; return true;
} }

View File

@@ -42,7 +42,7 @@ public abstract class IAuthenticator {
YGGDRASIL_LOGIN.onLoadSettings(Settings.getInstance().getYggdrasilConfig()); YGGDRASIL_LOGIN.onLoadSettings(Settings.getInstance().getYggdrasilConfig());
Runtime.getRuntime().addShutdownHook(new Thread(() Runtime.getRuntime().addShutdownHook(new Thread(()
-> Settings.getInstance().setYggdrasilConfig(YGGDRASIL_LOGIN.onSaveSettings()) -> Settings.getInstance().setYggdrasilConfig(YGGDRASIL_LOGIN.onSaveSettings())
)); ));
} }
@@ -56,6 +56,7 @@ public abstract class IAuthenticator {
* Login Method * Login Method
* *
* @param info username & password * @param info username & password
*
* @return login result * @return login result
*/ */
public abstract UserProfileProvider login(LoginInfo info); public abstract UserProfileProvider login(LoginInfo info);

View File

@@ -39,10 +39,10 @@ public final class SkinmeAuthenticator extends IAuthenticator {
public String getCharacter(String user, String hash, String $char) throws Exception { public String getCharacter(String user, String hash, String $char) throws Exception {
if ($char == null) if ($char == null)
return NetUtils.doGet( return NetUtils.doGet(
"http://www.skinme.cc/api/login.php?user=" + user + "&hash=" + hash); "http://www.skinme.cc/api/login.php?user=" + user + "&hash=" + hash);
else else
return NetUtils.doGet( return NetUtils.doGet(
"http://www.skinme.cc/api/login.php?user=" + user + "&hash=" + hash + "&char=" + $char); "http://www.skinme.cc/api/login.php?user=" + user + "&hash=" + hash + "&char=" + $char);
} }
@Override @Override
@@ -61,53 +61,53 @@ public final class SkinmeAuthenticator extends IAuthenticator {
String hashCode = DigestUtils.sha1Hex(DigestUtils.md5Hex(DigestUtils.sha1Hex(pwd) + pwd) + str); String hashCode = DigestUtils.sha1Hex(DigestUtils.md5Hex(DigestUtils.sha1Hex(pwd) + pwd) + str);
String data = getCharacter(usr, hashCode, null); String data = getCharacter(usr, hashCode, null);
String[] sl = data.split(":"); String[] sl = data.split(":");
if (null != sl[0]) switch (sl[0]) { if (null != sl[0])
case "0": switch (sl[0]) {
req.setSuccess(false); case "0":
if(sl[1].contains("No Valid Character")) {
sl[1] = C.i18n("login.no_valid_character");
}
req.setErrorReason(sl[1]);
break;
case "1": {
req.setSuccess(true);
String[] s = parseType1(sl[1]);
req.setUserName(s[0]);
req.setSession(s[1]);
req.setUserId(s[1]);
req.setAccessToken(s[1]);
break;
}
case "2": {
req.setSuccess(true);
String[] charators = sl[1].split(";");
int len = charators.length;
String[] $char = new String[len];
String[] user = new String[len];
System.out.println(sl[1]);
for (int i = 0; i < len; i++) {
String[] charator = charators[i].split(",");
$char[i] = charator[0];
user[i] = charator[1];
}
Selector s = new Selector(null, user, C.i18n("login.choose_charactor"));
s.setVisible(true);
if (s.sel == Selector.failedToSel) {
req.setSuccess(false); req.setSuccess(false);
req.setErrorReason(C.i18n("message.cancelled")); if (sl[1].contains("No Valid Character"))
} else { sl[1] = C.i18n("login.no_valid_character");
int index = s.sel; req.setErrorReason(sl[1]);
String character = $char[index]; break;
sl = getCharacter(usr, hashCode, character).split(":"); case "1": {
String[] s2 = parseType1(sl[1]); req.setSuccess(true);
req.setUserName(s2[0]); String[] s = parseType1(sl[1]);
req.setSession(s2[1]); req.setUserName(s[0]);
req.setUserId(s2[1]); req.setSession(s[1]);
req.setAccessToken(s2[1]); req.setUserId(s[1]);
req.setAccessToken(s[1]);
break;
}
case "2": {
req.setSuccess(true);
String[] charators = sl[1].split(";");
int len = charators.length;
String[] $char = new String[len];
String[] user = new String[len];
System.out.println(sl[1]);
for (int i = 0; i < len; i++) {
String[] charator = charators[i].split(",");
$char[i] = charator[0];
user[i] = charator[1];
}
Selector s = new Selector(null, user, C.i18n("login.choose_charactor"));
s.setVisible(true);
if (s.sel == Selector.failedToSel) {
req.setSuccess(false);
req.setErrorReason(C.i18n("message.cancelled"));
} else {
int index = s.sel;
String character = $char[index];
sl = getCharacter(usr, hashCode, character).split(":");
String[] s2 = parseType1(sl[1]);
req.setUserName(s2[0]);
req.setSession(s2[1]);
req.setUserId(s2[1]);
req.setAccessToken(s2[1]);
}
break;
} }
break;
} }
}
req.setUserType("Legacy"); req.setUserType("Legacy");
return req; return req;

View File

@@ -70,7 +70,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
ua.setUsername(usr); ua.setUsername(usr);
try { try {
ua.logIn(); ua.logIn();
if (!ua.isLoggedIn()) throw new Exception(C.i18n("login.wrong_password")); if (!ua.isLoggedIn())
throw new Exception(C.i18n("login.wrong_password"));
GameProfile selectedProfile = ua.getSelectedProfile(); GameProfile selectedProfile = ua.getSelectedProfile();
GameProfile[] profiles = ua.getAvailableProfiles(); GameProfile[] profiles = ua.getAvailableProfiles();
String[] names; String[] names;
@@ -94,7 +95,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.LegacySerializer()).create().toJson(ua.getUserProperties())); result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.LegacySerializer()).create().toJson(ua.getUserProperties()));
result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties())); result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()));
String authToken = ua.getAuthenticatedToken(); String authToken = ua.getAuthenticatedToken();
if (authToken == null) authToken = "0"; if (authToken == null)
authToken = "0";
result.setAccessToken(authToken); result.setAccessToken(authToken);
result.setSession(authToken); result.setSession(authToken);
} catch (Exception ex) { } catch (Exception ex) {
@@ -123,7 +125,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
} }
public void onLoadSettings(Map settings) { public void onLoadSettings(Map settings) {
if (settings == null) return; if (settings == null)
return;
ua.loadFromStorage(settings); ua.loadFromStorage(settings);
} }
@@ -132,7 +135,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
UserProfileProvider info = new UserProfileProvider(); UserProfileProvider info = new UserProfileProvider();
try { try {
ua.logIn(); ua.logIn();
if (!ua.isLoggedIn()) throw new Exception(C.i18n("login.wrong_password")); if (!ua.isLoggedIn())
throw new Exception(C.i18n("login.wrong_password"));
GameProfile profile = ua.getSelectedProfile(); GameProfile profile = ua.getSelectedProfile();
info.setUserName(profile.name); info.setUserName(profile.name);
info.setSuccess(true); info.setSuccess(true);

View File

@@ -5,7 +5,7 @@ public class Property {
public final String name, value; public final String name, value;
public Property(String name, String value) { public Property(String name, String value) {
this.name = name; this.name = name;
this.value = value; this.value = value;
} }
} }

View File

@@ -52,7 +52,7 @@ public class PropertyMap extends HashMap<String, Property> {
if (entry.getValue() instanceof JsonArray) if (entry.getValue() instanceof JsonArray)
for (JsonElement element : (JsonArray) entry.getValue()) for (JsonElement element : (JsonArray) entry.getValue())
result.put(entry.getKey(), result.put(entry.getKey(),
new Property((String) entry.getKey(), element.getAsString())); new Property((String) entry.getKey(), element.getAsString()));
} else if ((json instanceof JsonArray)) } else if ((json instanceof JsonArray))
for (JsonElement element : (JsonArray) json) for (JsonElement element : (JsonArray) json)
if ((element instanceof JsonObject)) { if ((element instanceof JsonObject)) {

View File

@@ -17,9 +17,9 @@ import org.jackhuang.hellominecraft.utils.StrUtils;
public class YggdrasilAuthentication { public class YggdrasilAuthentication {
public static final Gson GSON = new GsonBuilder() public static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(GameProfile.class, new GameProfile.GameProfileSerializer()) .registerTypeAdapter(GameProfile.class, new GameProfile.GameProfileSerializer())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()) .registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); .registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
protected static final String BASE_URL = "https://authserver.mojang.com/"; protected static final String BASE_URL = "https://authserver.mojang.com/";
protected static final URL ROUTE_AUTHENTICATE = NetUtils.constantURL(BASE_URL + "authenticate"); protected static final URL ROUTE_AUTHENTICATE = NetUtils.constantURL(BASE_URL + "authenticate");
@@ -48,7 +48,6 @@ public class YggdrasilAuthentication {
} }
// <editor-fold defaultstate="collapsed" desc="Get/Set"> // <editor-fold defaultstate="collapsed" desc="Get/Set">
public void setUsername(String username) { public void setUsername(String username) {
if ((isLoggedIn()) && (canPlayOnline())) if ((isLoggedIn()) && (canPlayOnline()))
throw new IllegalStateException("Cannot change username while logged in & online"); throw new IllegalStateException("Cannot change username while logged in & online");
@@ -120,7 +119,7 @@ public class YggdrasilAuthentication {
@Deprecated @Deprecated
public String getSessionToken() { public String getSessionToken() {
if (isLoggedIn() && getSelectedProfile() != null && canPlayOnline()) if (isLoggedIn() && getSelectedProfile() != null && canPlayOnline())
return String.format("token:%s:%s", new Object[]{getAuthenticatedToken(), getSelectedProfile().id}); return String.format("token:%s:%s", new Object[] {getAuthenticatedToken(), getSelectedProfile().id});
return null; return null;
} }
@@ -129,9 +128,7 @@ public class YggdrasilAuthentication {
} }
// </editor-fold> // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Log In/Out"> // <editor-fold defaultstate="collapsed" desc="Log In/Out">
public boolean canPlayOnline() { public boolean canPlayOnline() {
return isLoggedIn() && getSelectedProfile() != null && this.isOnline; return isLoggedIn() && getSelectedProfile() != null && this.isOnline;
} }
@@ -209,7 +206,6 @@ public class YggdrasilAuthentication {
// </editor-fold> // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Settings Storage"> // <editor-fold defaultstate="collapsed" desc="Settings Storage">
public void loadFromStorage(Map<String, Object> credentials) { public void loadFromStorage(Map<String, Object> credentials) {
logOut(); logOut();
@@ -259,7 +255,6 @@ public class YggdrasilAuthentication {
} }
// </editor-fold> // </editor-fold>
protected Response request(URL url, Object input) throws AuthenticationException { protected Response request(URL url, Object input) throws AuthenticationException {
try { try {
String jsonResult = input == null ? NetUtils.doGet(url) : NetUtils.post(url, GSON.toJson(input), "application/json", proxy); String jsonResult = input == null ? NetUtils.doGet(url) : NetUtils.post(url, GSON.toJson(input), "application/json", proxy);

View File

@@ -42,9 +42,12 @@ public class BMCLAPIDownloadProvider implements IDownloadProvider {
@Override @Override
public InstallerVersionList getInstallerByType(String type) { public InstallerVersionList getInstallerByType(String type) {
if (type.equalsIgnoreCase("forge")) return getForgeInstaller(); if (type.equalsIgnoreCase("forge"))
if (type.equalsIgnoreCase("liteloader")) return getLiteLoaderInstaller(); return getForgeInstaller();
if (type.equalsIgnoreCase("optifine")) return getOptiFineInstaller(); if (type.equalsIgnoreCase("liteloader"))
return getLiteLoaderInstaller();
if (type.equalsIgnoreCase("optifine"))
return getOptiFineInstaller();
return null; return null;
} }

View File

@@ -41,9 +41,12 @@ public class MojangDownloadProvider implements IDownloadProvider {
@Override @Override
public InstallerVersionList getInstallerByType(String type) { public InstallerVersionList getInstallerByType(String type) {
if (type.equalsIgnoreCase("forge")) return getForgeInstaller(); if (type.equalsIgnoreCase("forge"))
if (type.equalsIgnoreCase("liteloader")) return getLiteLoaderInstaller(); return getForgeInstaller();
if (type.equalsIgnoreCase("optifine")) return getOptiFineInstaller(); if (type.equalsIgnoreCase("liteloader"))
return getLiteLoaderInstaller();
if (type.equalsIgnoreCase("optifine"))
return getOptiFineInstaller();
return null; return null;
} }

View File

@@ -52,5 +52,4 @@ public class RapidDataDownloadProvider extends MojangDownloadProvider {
return str == null ? null : str.replace("http://files.minecraftforge.net/maven", "http://mirrors.rapiddata.org/forge/maven"); return str == null ? null : str.replace("http://files.minecraftforge.net/maven", "http://mirrors.rapiddata.org/forge/maven");
} }
} }

View File

@@ -30,6 +30,7 @@ public abstract class InstallerVersionList implements Consumer<String[]> {
* Refresh installer versions list from the downloaded content. * Refresh installer versions list from the downloaded content.
* *
* @param versions Minecraft versions you need to refresh * @param versions Minecraft versions you need to refresh
*
* @throws java.lang.Exception * @throws java.lang.Exception
*/ */
public abstract void refreshList(String[] versions) throws Exception; public abstract void refreshList(String[] versions) throws Exception;

View File

@@ -40,7 +40,8 @@ public class PackMinecraftInstaller {
public void install() throws IOException { public void install() throws IOException {
File file = new File(IOUtils.currentDir(), "HMCL-MERGE-TEMP"); File file = new File(IOUtils.currentDir(), "HMCL-MERGE-TEMP");
file.mkdirs(); file.mkdirs();
for (String src1 : src) Compressor.unzip(new File(src1), file); for (String src1 : src)
Compressor.unzip(new File(src1), file);
Compressor.zip(file, dest); Compressor.zip(file, dest);
FileUtils.deleteDirectory(file); FileUtils.deleteDirectory(file);
} }

View File

@@ -79,7 +79,7 @@ public class ForgeInstaller extends Task {
HMCLog.log("Copying jar..." + profile.install.minecraft + ".jar to " + profile.install.target + ".jar"); HMCLog.log("Copying jar..." + profile.install.minecraft + ".jar to " + profile.install.target + ".jar");
FileUtils.copyFile(new File(from, profile.install.minecraft + ".jar"), FileUtils.copyFile(new File(from, profile.install.minecraft + ".jar"),
new File(to, profile.install.target + ".jar")); new File(to, profile.install.target + ".jar"));
HMCLog.log("Creating new version profile..." + profile.install.target + ".json"); HMCLog.log("Creating new version profile..." + profile.install.target + ".json");
/*for (MinecraftLibrary library : profile.versionInfo.libraries) /*for (MinecraftLibrary library : profile.versionInfo.libraries)
if (library.name.startsWith("net.minecraftforge:forge:")) if (library.name.startsWith("net.minecraftforge:forge:"))
@@ -98,7 +98,8 @@ public class ForgeInstaller extends Task {
try (FileOutputStream fos = new FileOutputStream(file)) { try (FileOutputStream fos = new FileOutputStream(file)) {
BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedOutputStream bos = new BufferedOutputStream(fos);
int c; int c;
while ((c = is.read()) != -1) bos.write((byte) c); while ((c = is.read()) != -1)
bos.write((byte) c);
bos.close(); bos.close();
} }
return true; return true;

View File

@@ -39,7 +39,8 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
private static ForgeBMCLVersionList instance; private static ForgeBMCLVersionList instance;
public static ForgeBMCLVersionList getInstance() { public static ForgeBMCLVersionList getInstance() {
if (instance == null) instance = new ForgeBMCLVersionList(); if (instance == null)
instance = new ForgeBMCLVersionList();
return instance; return instance;
} }
@@ -55,7 +56,8 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
} }
for (String x : neededVersions) { for (String x : neededVersions) {
if (versionMap.containsKey(x)) continue; if (versionMap.containsKey(x))
continue;
String s = NetUtils.doGet("http://bmclapi2.bangbang93.com/forge/minecraft/" + x); String s = NetUtils.doGet("http://bmclapi2.bangbang93.com/forge/minecraft/" + x);
if (s == null) if (s == null)
@@ -63,7 +65,7 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
try { try {
root = C.gson.fromJson(s, new TypeToken<ArrayList<ForgeVersion>>() { root = C.gson.fromJson(s, new TypeToken<ArrayList<ForgeVersion>>() {
}.getType()); }.getType());
for (ForgeVersion v : root) { for (ForgeVersion v : root) {
InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.minecraft)); InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.minecraft));
@@ -83,10 +85,13 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
@Override @Override
public List<InstallerVersion> getVersions(String mcVersion) { public List<InstallerVersion> getVersions(String mcVersion) {
if (versions == null || versionMap == null) return null; if (versions == null || versionMap == null)
if (StrUtils.isBlank(mcVersion)) return versions; return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion); List c = versionMap.get(mcVersion);
if (c == null) return versions; if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE); Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c; return c;
} }

View File

@@ -49,7 +49,8 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] needed) throws Exception { public void refreshList(String[] needed) throws Exception {
String s = NetUtils.doGet(Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(C.URL_FORGE_LIST)); String s = NetUtils.doGet(Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(C.URL_FORGE_LIST));
if (root != null) return; if (root != null)
return;
root = C.gson.fromJson(s, MinecraftForgeVersionRoot.class); root = C.gson.fromJson(s, MinecraftForgeVersionRoot.class);
@@ -96,10 +97,13 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
@Override @Override
public List<InstallerVersion> getVersions(String mcVersion) { public List<InstallerVersion> getVersions(String mcVersion) {
if (versions == null || versionMap == null) return null; if (versions == null || versionMap == null)
if (StrUtils.isBlank(mcVersion)) return versions; return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion); List c = versionMap.get(mcVersion);
if (c == null) return versions; if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE); Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c; return c;
} }

View File

@@ -55,7 +55,8 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrar
setFailReason(new RuntimeException(C.i18n("install.no_version"))); setFailReason(new RuntimeException(C.i18n("install.no_version")));
return false; return false;
} }
if (pre.size() != 1 && installer == null) throw new IllegalStateException("No registered previous task."); if (pre.size() != 1 && installer == null)
throw new IllegalStateException("No registered previous task.");
if (installer == null) if (installer == null)
installer = pre.get(pre.size() - 1).getResult(); installer = pre.get(pre.size() - 1).getResult();
try { try {

View File

@@ -51,7 +51,8 @@ public class LiteLoaderVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] needed) throws Exception { public void refreshList(String[] needed) throws Exception {
String s = NetUtils.doGet(C.URL_LITELOADER_LIST); String s = NetUtils.doGet(C.URL_LITELOADER_LIST);
if (root != null) return; if (root != null)
return;
root = C.gson.fromJson(s, LiteLoaderVersionsRoot.class); root = C.gson.fromJson(s, LiteLoaderVersionsRoot.class);
@@ -62,7 +63,8 @@ public class LiteLoaderVersionList extends InstallerVersionList {
ArrayList<InstallerVersion> al = new ArrayList<>(); ArrayList<InstallerVersion> al = new ArrayList<>();
LiteLoaderMCVersions mcv = arr.getValue(); LiteLoaderMCVersions mcv = arr.getValue();
for (Map.Entry<String, LiteLoaderVersion> entry : mcv.artefacts.get("com.mumfrey:liteloader").entrySet()) { for (Map.Entry<String, LiteLoaderVersion> entry : mcv.artefacts.get("com.mumfrey:liteloader").entrySet()) {
if ("latest".equals(entry.getKey())) continue; if ("latest".equals(entry.getKey()))
continue;
LiteLoaderVersion v = entry.getValue(); LiteLoaderVersion v = entry.getValue();
LiteLoaderInstallerVersion iv = new LiteLoaderInstallerVersion(v.version, StrUtils.formatVersion(arr.getKey())); LiteLoaderInstallerVersion iv = new LiteLoaderInstallerVersion(v.version, StrUtils.formatVersion(arr.getKey()));
iv.universal = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + arr.getKey() + "/" + v.file; iv.universal = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + arr.getKey() + "/" + v.file;
@@ -81,10 +83,13 @@ public class LiteLoaderVersionList extends InstallerVersionList {
@Override @Override
public List<InstallerVersion> getVersions(String mcVersion) { public List<InstallerVersion> getVersions(String mcVersion) {
if (versions == null || versionMap == null) return null; if (versions == null || versionMap == null)
if (StrUtils.isBlank(mcVersion)) return versions; return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion); List c = versionMap.get(mcVersion);
if (c == null) return versions; if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE); Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c; return c;
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.optifine;
* @author huangyuhui * @author huangyuhui
*/ */
public class OptiFineVersion { public class OptiFineVersion {
public String dl, ver, date, mirror, mcver; public String dl, ver, date, mirror, mcver;
} }

View File

@@ -56,16 +56,18 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
versionMap = new HashMap<>(); versionMap = new HashMap<>();
versions = new ArrayList<>(); versions = new ArrayList<>();
if (s == null) return; if (s == null)
return;
root = C.gson.fromJson(s, new TypeToken<ArrayList<OptiFineVersion>>() { root = C.gson.fromJson(s, new TypeToken<ArrayList<OptiFineVersion>>() {
}.getType()); }.getType());
for (OptiFineVersion v : root) { for (OptiFineVersion v : root) {
v.mirror = v.mirror.replace("http://optifine.net/http://optifine.net/", "http://optifine.net/"); v.mirror = v.mirror.replace("http://optifine.net/http://optifine.net/", "http://optifine.net/");
if (StrUtils.isBlank(v.mcver)) { if (StrUtils.isBlank(v.mcver)) {
Pattern p = Pattern.compile("OptiFine (.*) HD"); Pattern p = Pattern.compile("OptiFine (.*) HD");
Matcher m = p.matcher(v.ver); Matcher m = p.matcher(v.ver);
while (m.find()) v.mcver = m.group(1); while (m.find())
v.mcver = m.group(1);
} }
InstallerVersion iv = new InstallerVersion(v.ver, StrUtils.formatVersion(v.mcver)); InstallerVersion iv = new InstallerVersion(v.ver, StrUtils.formatVersion(v.mcver));
@@ -81,10 +83,13 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
@Override @Override
public List<InstallerVersion> getVersions(String mcVersion) { public List<InstallerVersion> getVersions(String mcVersion) {
if (versions == null || versionMap == null) return null; if (versions == null || versionMap == null)
if (StrUtils.isBlank(mcVersion)) return versions; return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion); List c = versionMap.get(mcVersion);
if (c == null) return versions; if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE); Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c; return c;
} }

View File

@@ -41,7 +41,8 @@ public class OptiFineDownloadFormatter extends Task implements PreviousResult<St
String content = NetUtils.doGet(url); String content = NetUtils.doGet(url);
Pattern p = Pattern.compile("\"downloadx\\?f=OptiFine(.*)\""); Pattern p = Pattern.compile("\"downloadx\\?f=OptiFine(.*)\"");
Matcher m = p.matcher(content); Matcher m = p.matcher(content);
while (m.find()) result = m.group(1); while (m.find())
result = m.group(1);
result = "http://optifine.net/downloadx?f=OptiFine" + result; result = "http://optifine.net/downloadx?f=OptiFine" + result;
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {

View File

@@ -60,7 +60,8 @@ public class OptiFineVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] sss) throws Exception { public void refreshList(String[] sss) throws Exception {
String content = NetUtils.doGet("http://optifine.net/downloads"); String content = NetUtils.doGet("http://optifine.net/downloads");
if (versions != null) return; if (versions != null)
return;
versionMap = new HashMap<>(); versionMap = new HashMap<>();
versions = new ArrayList<>(); versions = new ArrayList<>();
@@ -93,7 +94,8 @@ public class OptiFineVersionList extends InstallerVersionList {
if (StrUtils.isBlank(v.mcver)) { if (StrUtils.isBlank(v.mcver)) {
Pattern p = Pattern.compile("OptiFine (.*?) "); Pattern p = Pattern.compile("OptiFine (.*?) ");
Matcher m = p.matcher(v.ver); Matcher m = p.matcher(v.ver);
while (m.find()) v.mcver = StrUtils.formatVersion(m.group(1)); while (m.find())
v.mcver = StrUtils.formatVersion(m.group(1));
} }
InstallerVersion iv = new InstallerVersion(v.ver, StrUtils.formatVersion(v.mcver)); InstallerVersion iv = new InstallerVersion(v.ver, StrUtils.formatVersion(v.mcver));
iv.installer = iv.universal = v.mirror; iv.installer = iv.universal = v.mirror;
@@ -119,10 +121,13 @@ public class OptiFineVersionList extends InstallerVersionList {
@Override @Override
public List<InstallerVersion> getVersions(String mcVersion) { public List<InstallerVersion> getVersions(String mcVersion) {
if (versions == null || versionMap == null) return null; if (versions == null || versionMap == null)
if (StrUtils.isBlank(mcVersion)) return versions; return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion); List c = versionMap.get(mcVersion);
if (c == null) return versions; if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE); Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c; return c;
} }

View File

@@ -64,9 +64,11 @@ public class Upgrader extends Task {
HashMap<String, String> json = new HashMap<>(); HashMap<String, String> json = new HashMap<>();
File f = getSelf(newestVersion); File f = getSelf(newestVersion);
try { try {
if (!f.getParentFile().exists()) f.getParentFile().mkdirs(); if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
for (int i = 0; f.exists(); i++) f = new File(BASE_FOLDER, "HMCL-" + newestVersion + (i > 0 ? "-" + i : "") + ".jar"); for (int i = 0; f.exists(); i++)
f = new File(BASE_FOLDER, "HMCL-" + newestVersion + (i > 0 ? "-" + i : "") + ".jar");
f.createNewFile(); f.createNewFile();
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(f))) { try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(f))) {

View File

@@ -104,10 +104,10 @@ public class MinecraftLibrary extends IMinecraftLibrary {
str = str.replace('.', File.separatorChar); str = str.replace('.', File.separatorChar);
if (natives == null) if (natives == null)
str += File.separator + s[1] + File.separator + s[2] str += File.separator + s[1] + File.separator + s[2]
+ File.separator + s[1] + '-' + s[2] + ".jar"; + File.separator + s[1] + '-' + s[2] + ".jar";
else { else {
str += File.separator + s[1] + File.separator + s[2] str += File.separator + s[1] + File.separator + s[2]
+ File.separator + s[1] + '-' + s[2] + '-'; + File.separator + s[1] + '-' + s[2] + '-';
str += getNative(); str += getNative();
str += ".jar"; str += ".jar";
} }
@@ -121,8 +121,10 @@ public class MinecraftLibrary extends IMinecraftLibrary {
@Override @Override
public String getDownloadURL(String urlBase, DownloadType downloadType) { public String getDownloadURL(String urlBase, DownloadType downloadType) {
if (StrUtils.isNotBlank(url) && downloadType.getProvider().isAllowedToUseSelfURL()) urlBase = this.url; if (StrUtils.isNotBlank(url) && downloadType.getProvider().isAllowedToUseSelfURL())
if (urlBase.endsWith(".jar")) return urlBase; urlBase = this.url;
if (urlBase.endsWith(".jar"))
return urlBase;
return urlBase + formatted.replace('\\', '/'); return urlBase + formatted.replace('\\', '/');
} }

View File

@@ -33,7 +33,7 @@ import org.jackhuang.hellominecraft.utils.ArrayUtils;
public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion> { public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion> {
public String minecraftArguments, mainClass, time, id, type, processArguments, public String minecraftArguments, mainClass, time, id, type, processArguments,
releaseTime, assets, jar, inheritsFrom; releaseTime, assets, jar, inheritsFrom;
public int minimumLauncherVersion; public int minimumLauncherVersion;
public boolean hidden; public boolean hidden;
@@ -56,7 +56,8 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
this.inheritsFrom = inheritsFrom; this.inheritsFrom = inheritsFrom;
this.minimumLauncherVersion = minimumLauncherVersion; this.minimumLauncherVersion = minimumLauncherVersion;
this.hidden = hidden; this.hidden = hidden;
if (libraries == null) this.libraries = new ArrayList<>(); if (libraries == null)
this.libraries = new ArrayList<>();
else { else {
this.libraries = new ArrayList<>(libraries.size()); this.libraries = new ArrayList<>(libraries.size());
for (IMinecraftLibrary library : libraries) for (IMinecraftLibrary library : libraries)
@@ -81,18 +82,19 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
MinecraftVersion parent = manager.getVersionById(inheritsFrom); MinecraftVersion parent = manager.getVersionById(inheritsFrom);
if (parent == null) { if (parent == null) {
if (!manager.install(inheritsFrom, sourceType)) return this; if (!manager.install(inheritsFrom, sourceType))
return this;
parent = manager.getVersionById(inheritsFrom); parent = manager.getVersionById(inheritsFrom);
} }
parent = parent.resolve(manager, resolvedSoFar, sourceType); parent = parent.resolve(manager, resolvedSoFar, sourceType);
MinecraftVersion result = new MinecraftVersion( MinecraftVersion result = new MinecraftVersion(
this.minecraftArguments != null ? this.minecraftArguments : parent.minecraftArguments, this.minecraftArguments != null ? this.minecraftArguments : parent.minecraftArguments,
this.mainClass != null ? this.mainClass : parent.mainClass, this.mainClass != null ? this.mainClass : parent.mainClass,
this.time, this.id, this.type, parent.processArguments, this.releaseTime, this.time, this.id, this.type, parent.processArguments, this.releaseTime,
this.assets != null ? this.assets : parent.assets, this.assets != null ? this.assets : parent.assets,
this.jar != null ? this.jar : parent.jar, this.jar != null ? this.jar : parent.jar,
null, parent.minimumLauncherVersion, null, parent.minimumLauncherVersion,
this.libraries != null ? ArrayUtils.merge(this.libraries, parent.libraries) : parent.libraries, this.hidden); this.libraries != null ? ArrayUtils.merge(this.libraries, parent.libraries) : parent.libraries, this.hidden);
return result; return result;
} }
@@ -109,7 +111,7 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
public File getNatives(File gameDir) { public File getNatives(File gameDir) {
return new File(gameDir, "versions/" + id + "/" + id return new File(gameDir, "versions/" + id + "/" + id
+ "-natives"); + "-natives");
} }
public boolean isAllowedToUnpackNatives() { public boolean isAllowedToUnpackNatives() {

View File

@@ -95,18 +95,21 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
File version = new File(baseFolder, "versions"); File version = new File(baseFolder, "versions");
File[] files = version.listFiles(); File[] files = version.listFiles();
if (files == null || files.length == 0) return; if (files == null || files.length == 0)
return;
for (File dir : files) { for (File dir : files) {
String id = dir.getName(); String id = dir.getName();
File jsonFile = new File(dir, id + ".json"); File jsonFile = new File(dir, id + ".json");
if (!dir.isDirectory()) continue; if (!dir.isDirectory())
continue;
boolean ask = false; boolean ask = false;
File[] jsons = null; File[] jsons = null;
if (!jsonFile.exists()) { if (!jsonFile.exists()) {
jsons = FileUtils.searchSuffix(dir, "json"); jsons = FileUtils.searchSuffix(dir, "json");
if (jsons.length == 1) ask = true; if (jsons.length == 1)
ask = true;
} }
if (ask) { if (ask) {
HMCLog.warn("Found not matched filenames version: " + id + ", json: " + jsons[0].getName()); HMCLog.warn("Found not matched filenames version: " + id + ", json: " + jsons[0].getName());
@@ -121,20 +124,23 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
MinecraftVersion mcVersion; MinecraftVersion mcVersion;
try { try {
mcVersion = C.gson.fromJson(FileUtils.readFileToString(jsonFile), MinecraftVersion.class); mcVersion = C.gson.fromJson(FileUtils.readFileToString(jsonFile), MinecraftVersion.class);
if (mcVersion == null) throw new RuntimeException("Wrong json format, got null."); if (mcVersion == null)
throw new RuntimeException("Wrong json format, got null.");
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
HMCLog.warn("Found wrong format json, try to fix it.", e); HMCLog.warn("Found wrong format json, try to fix it.", e);
if (MessageBox.Show(C.i18n("launcher.versions_json_not_formatted", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) { if (MessageBox.Show(C.i18n("launcher.versions_json_not_formatted", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
refreshJson(id); refreshJson(id);
try { try {
mcVersion = C.gson.fromJson(FileUtils.readFileToString(jsonFile), MinecraftVersion.class); mcVersion = C.gson.fromJson(FileUtils.readFileToString(jsonFile), MinecraftVersion.class);
if (mcVersion == null) throw new RuntimeException("Wrong json format, got null."); if (mcVersion == null)
throw new RuntimeException("Wrong json format, got null.");
} catch (IOException | RuntimeException ex) { } catch (IOException | RuntimeException ex) {
HMCLog.err("Retried but still failed."); HMCLog.err("Retried but still failed.");
HMCLog.warn("Ignoring: " + dir + ", the json of this Minecraft is malformed.", ex); HMCLog.warn("Ignoring: " + dir + ", the json of this Minecraft is malformed.", ex);
continue; continue;
} }
} else continue; } else
continue;
} }
try { try {
if (!id.equals(mcVersion.id)) { if (!id.equals(mcVersion.id)) {
@@ -156,7 +162,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public boolean removeVersionFromDisk(String name) { public boolean removeVersionFromDisk(String name) {
File version = new File(baseFolder, "versions/" + name); File version = new File(baseFolder, "versions/" + name);
if (!version.exists()) return true; if (!version.exists())
return true;
versions.remove(name); versions.remove(name);
return FileUtils.deleteDirectoryQuietly(version); return FileUtils.deleteDirectoryQuietly(version);
@@ -192,7 +199,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public boolean refreshAssetsIndex(String id) { public boolean refreshAssetsIndex(String id) {
MinecraftVersion mv = getVersionById(id); MinecraftVersion mv = getVersionById(id);
if (mv == null) return false; if (mv == null)
return false;
return MCUtils.downloadMinecraftAssetsIndex(new File(baseFolder, "assets"), mv.assets, Settings.getInstance().getDownloadSource()); return MCUtils.downloadMinecraftAssetsIndex(new File(baseFolder, "assets"), mv.assets, Settings.getInstance().getDownloadSource());
} }
@@ -218,7 +226,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public List<ModInfo> listMods() { public List<ModInfo> listMods() {
if (profile.getSelectedMinecraftVersion() == null) return new ArrayList<>(); if (profile.getSelectedMinecraftVersion() == null)
return new ArrayList<>();
File modsFolder = new File(getRunDirectory(profile.getSelectedMinecraftVersion().id), "mods"); File modsFolder = new File(getRunDirectory(profile.getSelectedMinecraftVersion().id), "mods");
ArrayList<ModInfo> mods = new ArrayList<>(); ArrayList<ModInfo> mods = new ArrayList<>();
File[] fs = modsFolder.listFiles(); File[] fs = modsFolder.listFiles();
@@ -245,7 +254,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) { public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) {
ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>(); ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>();
if(profile.getSelectedMinecraftVersion() == null) return downloadLibraries; if (profile.getSelectedMinecraftVersion() == null)
return downloadLibraries;
MinecraftVersion v = profile.getSelectedMinecraftVersion().resolve(this, Settings.getInstance().getDownloadSource()); MinecraftVersion v = profile.getSelectedMinecraftVersion().resolve(this, Settings.getInstance().getDownloadSource());
if (v.libraries != null) if (v.libraries != null)
for (IMinecraftLibrary l : v.libraries) { for (IMinecraftLibrary l : v.libraries) {
@@ -281,7 +291,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public GameLauncher.DecompressLibraryJob getDecompressLibraries() { public GameLauncher.DecompressLibraryJob getDecompressLibraries() {
MinecraftVersion v = profile.getSelectedMinecraftVersion().resolve(this, Settings.getInstance().getDownloadSource()); MinecraftVersion v = profile.getSelectedMinecraftVersion().resolve(this, Settings.getInstance().getDownloadSource());
if (v.libraries == null) return null; if (v.libraries == null)
return null;
ArrayList<File> unzippings = new ArrayList<>(); ArrayList<File> unzippings = new ArrayList<>();
ArrayList<String[]> extractRules = new ArrayList<>(); ArrayList<String[]> extractRules = new ArrayList<>();
for (IMinecraftLibrary l : v.libraries) { for (IMinecraftLibrary l : v.libraries) {
@@ -307,7 +318,7 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public IMinecraftLoader provideMinecraftLoader(UserProfileProvider p, DownloadType type) public IMinecraftLoader provideMinecraftLoader(UserProfileProvider p, DownloadType type)
throws IllegalStateException { throws IllegalStateException {
return new MinecraftLoader(profile, this, p, type); return new MinecraftLoader(profile, this, p, type);
} }
@@ -334,6 +345,7 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public void onLaunch() { public void onLaunch() {
File resourcePacks = getResourcePacks(); File resourcePacks = getResourcePacks();
if (!resourcePacks.exists()) resourcePacks.mkdirs(); if (!resourcePacks.exists())
resourcePacks.mkdirs();
} }
} }

View File

@@ -26,11 +26,12 @@ import javax.swing.JFrame;
* @author huangyuhui * @author huangyuhui
*/ */
public class DraggableFrame extends JFrame public class DraggableFrame extends JFrame
implements MouseListener, MouseMotionListener { implements MouseListener, MouseMotionListener {
private int dragGripX; private int dragGripX;
private int dragGripY; private int dragGripY;
@SuppressWarnings("LeakingThisInConstructor")
public DraggableFrame() { public DraggableFrame() {
setUndecorated(true); setUndecorated(true);
addMouseListener(this); addMouseListener(this);

View File

@@ -119,7 +119,8 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
itm = new JMenuItem(C.i18n("folder.game")); itm = new JMenuItem(C.i18n("folder.game"));
itm.addActionListener((e) -> { itm.addActionListener((e) -> {
Profile v = getProfile(); Profile v = getProfile();
if (v != null) v.getMinecraftProvider().openSelf(mcVersion); if (v != null)
v.getMinecraftProvider().openSelf(mcVersion);
}); });
ppmExplore.add(itm); ppmExplore.add(itm);
itm = new JMenuItem(C.i18n("folder.mod")); itm = new JMenuItem(C.i18n("folder.mod"));
@@ -227,13 +228,19 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
@Override @Override
public void stateChanged(ChangeEvent e) { public void stateChanged(ChangeEvent e) {
switch (tabInstallers.getSelectedIndex()) { switch (tabInstallers.getSelectedIndex()) {
case 0: if (!a) forge.refreshVersions(); case 0:
if (!a)
forge.refreshVersions();
a = true; a = true;
break; break;
case 1: if (!b) optifine.refreshVersions(); case 1:
if (!b)
optifine.refreshVersions();
b = true; b = true;
break; break;
case 2: if (!c) liteloader.refreshVersions(); case 2:
if (!c)
liteloader.refreshVersions();
c = true; c = true;
break; break;
} }
@@ -242,8 +249,10 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
for (Java j : Settings.JAVA) { for (Java j : Settings.JAVA) {
String name = j.getName(); String name = j.getName();
if (name.equals("Default")) name = C.i18n("settings.default"); if (name.equals("Default"))
if (name.equals("Custom")) name = C.i18n("settings.custom"); name = C.i18n("settings.default");
if (name.equals("Custom"))
name = C.i18n("settings.custom");
cboJava.addItem(name); cboJava.addItem(name);
} }
@@ -1122,7 +1131,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}// </editor-fold>//GEN-END:initComponents }// </editor-fold>//GEN-END:initComponents
// <editor-fold defaultstate="collapsed" desc="UI Events"> // <editor-fold defaultstate="collapsed" desc="UI Events">
private void cboProfilesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboProfilesItemStateChanged private void cboProfilesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboProfilesItemStateChanged
if (isLoading) return; if (isLoading)
return;
profile = getProfile(); profile = getProfile();
if (profile.getMinecraftProvider().getVersionCount() <= 0) if (profile.getMinecraftProvider().getVersionCount() <= 0)
versionChanged(profile, null); versionChanged(profile, null);
@@ -1136,8 +1146,10 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_btnNewProfileActionPerformed }//GEN-LAST:event_btnNewProfileActionPerformed
private void btnRemoveProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveProfileActionPerformed private void btnRemoveProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveProfileActionPerformed
if (profile == null) return; if (profile == null)
if (MessageBox.Show(C.i18n("ui.message.sure_remove", profile.getName()), MessageBox.YES_NO_OPTION) == MessageBox.NO_OPTION) return; return;
if (MessageBox.Show(C.i18n("ui.message.sure_remove", profile.getName()), MessageBox.YES_NO_OPTION) == MessageBox.NO_OPTION)
return;
if (Settings.delProfile(profile)) { if (Settings.delProfile(profile)) {
cboProfiles.removeItem(profile.getName()); cboProfiles.removeItem(profile.getName());
profile = Settings.getOneProfile(); profile = Settings.getOneProfile();
@@ -1180,9 +1192,9 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
if (v.installer != null) { if (v.installer != null) {
url = Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(v.installer); url = Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(v.installer);
TaskWindow.getInstance() TaskWindow.getInstance()
.addTask(new FileDownloadTask(url, filepath).setTag("forge")) .addTask(new FileDownloadTask(url, filepath).setTag("forge"))
.addTask(new ForgeInstaller(profile.getMinecraftProvider(), filepath, v)) .addTask(new ForgeInstaller(profile.getMinecraftProvider(), filepath, v))
.start(); .start();
refreshVersions(); refreshVersions();
} }
}//GEN-LAST:event_btnDownloadForgeActionPerformed }//GEN-LAST:event_btnDownloadForgeActionPerformed
@@ -1203,9 +1215,9 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
OptiFineDownloadFormatter task = new OptiFineDownloadFormatter(v.installer); OptiFineDownloadFormatter task = new OptiFineDownloadFormatter(v.installer);
TaskWindow.getInstance().addTask(task) TaskWindow.getInstance().addTask(task)
.addTask(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine")) .addTask(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.addTask(new OptiFineInstaller(profile, v.selfVersion, filepath)) .addTask(new OptiFineInstaller(profile, v.selfVersion, filepath))
.start(); .start();
refreshVersions(); refreshVersions();
}); });
}//GEN-LAST:event_btnDownloadOptifineActionPerformed }//GEN-LAST:event_btnDownloadOptifineActionPerformed
@@ -1222,8 +1234,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
url = v.universal; url = v.universal;
FileDownloadTask task = (FileDownloadTask) new FileDownloadTask(url, filepath).setTag("LiteLoader"); FileDownloadTask task = (FileDownloadTask) new FileDownloadTask(url, filepath).setTag("LiteLoader");
TaskWindow.getInstance() TaskWindow.getInstance()
.addTask(task).addTask(new LiteLoaderInstaller(profile, (LiteLoaderInstallerVersion) v).registerPreviousResult(task)) .addTask(task).addTask(new LiteLoaderInstaller(profile, (LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.start(); .start();
refreshVersions(); refreshVersions();
}//GEN-LAST:event_btnInstallLiteLoaderActionPerformed }//GEN-LAST:event_btnInstallLiteLoaderActionPerformed
@@ -1332,13 +1344,15 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_txtWidthFocusLost }//GEN-LAST:event_txtWidthFocusLost
private void txtGameDirFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtGameDirFocusLost private void txtGameDirFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtGameDirFocusLost
if (profile == null) return; if (profile == null)
return;
profile.setGameDir(txtGameDir.getText()); profile.setGameDir(txtGameDir.getText());
loadVersions(); loadVersions();
}//GEN-LAST:event_txtGameDirFocusLost }//GEN-LAST:event_txtGameDirFocusLost
private void btnChoosingJavaDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChoosingJavaDirActionPerformed private void btnChoosingJavaDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChoosingJavaDirActionPerformed
if (cboJava.getSelectedIndex() != 1) return; if (cboJava.getSelectedIndex() != 1)
return;
JFileChooser fc = new JFileChooser(); JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setDialogTitle(C.i18n("settings.choose_javapath")); fc.setDialogTitle(C.i18n("settings.choose_javapath"));
@@ -1376,25 +1390,29 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setDialogTitle(C.I18N.getString("mods.choose_mod")); fc.setDialogTitle(C.I18N.getString("mods.choose_mod"));
fc.setMultiSelectionEnabled(true); fc.setMultiSelectionEnabled(true);
if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
return;
boolean flag = false; boolean flag = false;
for (File f : fc.getSelectedFiles()) for (File f : fc.getSelectedFiles())
if (!addMod(f)) flag |= true; if (!addMod(f))
flag |= true;
if (flag) if (flag)
MessageBox.Show(C.I18N.getString("mods.failed")); MessageBox.Show(C.I18N.getString("mods.failed"));
}//GEN-LAST:event_btnAddModActionPerformed }//GEN-LAST:event_btnAddModActionPerformed
boolean addMod(File f) { boolean addMod(File f) {
try { try {
if (!ModInfo.isFileMod(f) || mods == null) return false; if (!ModInfo.isFileMod(f) || mods == null)
return false;
File newf = profile.getFolder("mods"); File newf = profile.getFolder("mods");
if (newf == null) return false; if (newf == null)
return false;
newf.mkdirs(); newf.mkdirs();
newf = new File(newf, f.getName()); newf = new File(newf, f.getName());
FileUtils.copyFile(f, newf); FileUtils.copyFile(f, newf);
ModInfo i = ModInfo.readModInfo(f); ModInfo i = ModInfo.readModInfo(f);
mods.add(i); mods.add(i);
((DefaultTableModel) lstExternalMods.getModel()).addRow(new Object[]{i.isActive(), i.location.getName(), i.version}); ((DefaultTableModel) lstExternalMods.getModel()).addRow(new Object[] {i.isActive(), i.location.getName(), i.version});
return true; return true;
} catch (IOException ex) { } catch (IOException ex) {
HMCLog.warn("Failed to copy mod", ex); HMCLog.warn("Failed to copy mod", ex);
@@ -1460,9 +1478,11 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
private void btnCleanGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCleanGameActionPerformed private void btnCleanGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCleanGameActionPerformed
File f = getProfile().getMinecraftProvider().getRunDirectory(mcVersion); File f = getProfile().getMinecraftProvider().getRunDirectory(mcVersion);
String[] dir = {"logs", "asm", "NVIDIA", "crash-reports", "server-resource-packs", "natives", "native"}; String[] dir = {"logs", "asm", "NVIDIA", "crash-reports", "server-resource-packs", "natives", "native"};
for (String s : dir) FileUtils.deleteDirectoryQuietly(new File(f, s)); for (String s : dir)
FileUtils.deleteDirectoryQuietly(new File(f, s));
String[] files = {"output-client.log", "usercache.json", "usernamecache.json", "hmclmc.log"}; String[] files = {"output-client.log", "usercache.json", "usernamecache.json", "hmclmc.log"};
for (String s : files) new File(f, s).delete(); for (String s : files)
new File(f, s).delete();
for (MinecraftVersion s : getProfile().getMinecraftProvider().getVersions()) for (MinecraftVersion s : getProfile().getMinecraftProvider().getVersions())
FileUtils.deleteDirectoryQuietly(new File(getProfile().getGameDirFile(), "versions" + File.separator + s.id + File.separator + s.id + "-natives")); FileUtils.deleteDirectoryQuietly(new File(getProfile().getGameDirFile(), "versions" + File.separator + s.id + File.separator + s.id + "-natives"));
}//GEN-LAST:event_btnCleanGameActionPerformed }//GEN-LAST:event_btnCleanGameActionPerformed
@@ -1475,7 +1495,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
Profile firstProfile = null, selectedProfile = null; Profile firstProfile = null, selectedProfile = null;
int index = 0, i = 0; int index = 0, i = 0;
for (Profile s : Settings.getProfilesFiltered()) { for (Profile s : Settings.getProfilesFiltered()) {
if (firstProfile == null) firstProfile = s; if (firstProfile == null)
firstProfile = s;
cboProfiles.addItem(s.getName()); cboProfiles.addItem(s.getName());
if (Settings.getInstance().getLast() != null && Settings.getInstance().getLast().equals(s.getName())) { if (Settings.getInstance().getLast() != null && Settings.getInstance().getLast().equals(s.getName())) {
index = i; index = i;
@@ -1483,13 +1504,15 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
} }
i++; i++;
} }
if (selectedProfile == null) selectedProfile = Settings.getOneProfile(); if (selectedProfile == null)
selectedProfile = Settings.getOneProfile();
isLoading = false; isLoading = false;
if (index < cboProfiles.getItemCount()) { if (index < cboProfiles.getItemCount()) {
cboProfiles.setSelectedIndex(index); cboProfiles.setSelectedIndex(index);
profile = selectedProfile; profile = selectedProfile;
if (profile == null) profile = firstProfile; if (profile == null)
profile = firstProfile;
prepare(profile); prepare(profile);
loadVersions(); loadVersions();
} }
@@ -1498,11 +1521,13 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
final Profile getProfile() { final Profile getProfile() {
if (cboProfiles.getSelectedIndex() >= 0) if (cboProfiles.getSelectedIndex() >= 0)
return Settings.getProfile(cboProfiles.getSelectedItem().toString()); return Settings.getProfile(cboProfiles.getSelectedItem().toString());
else return null; else
return null;
} }
void prepare(Profile profile) { void prepare(Profile profile) {
if (profile == null) return; if (profile == null)
return;
txtWidth.setText(profile.getWidth()); txtWidth.setText(profile.getWidth());
txtHeight.setText(profile.getHeight()); txtHeight.setText(profile.getHeight());
txtMaxMemory.setText(profile.getMaxMemory()); txtMaxMemory.setText(profile.getMaxMemory());
@@ -1530,7 +1555,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
} }
void loadVersions() { void loadVersions() {
if (profile == null) return; if (profile == null)
return;
isLoading = true; isLoading = true;
cboVersions.removeAllItems(); cboVersions.removeAllItems();
int index = 0, i = 0; int index = 0, i = 0;
@@ -1538,11 +1564,13 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
String selectedMC = selVersion == null ? null : selVersion.id; String selectedMC = selVersion == null ? null : selVersion.id;
for (MinecraftVersion each : profile.getMinecraftProvider().getVersions()) { for (MinecraftVersion each : profile.getMinecraftProvider().getVersions()) {
cboVersions.addItem(each.id); cboVersions.addItem(each.id);
if (each.id.equals(selectedMC)) index = i; if (each.id.equals(selectedMC))
index = i;
i++; i++;
} }
isLoading = false; isLoading = false;
if (index < cboVersions.getItemCount()) cboVersions.setSelectedIndex(index); if (index < cboVersions.getItemCount())
cboVersions.setSelectedIndex(index);
reloadMods(); reloadMods();
} }
@@ -1563,7 +1591,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
*/ */
void loadMinecraftVersion(MinecraftVersion v) { void loadMinecraftVersion(MinecraftVersion v) {
txtMinecraftVersion.setText(""); txtMinecraftVersion.setText("");
if (v == null) return; if (v == null)
return;
File minecraftJar = v.getJar(profile.getGameDirFile()); File minecraftJar = v.getJar(profile.getGameDirFile());
minecraftVersion = MCUtils.minecraftVersion(minecraftJar); minecraftVersion = MCUtils.minecraftVersion(minecraftJar);
txtMinecraftVersion.setText(MinecraftVersionRequest.getResponse(minecraftVersion)); txtMinecraftVersion.setText(MinecraftVersionRequest.getResponse(minecraftVersion));
@@ -1573,11 +1602,12 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
public int assetsType; public int assetsType;
private void downloadAssets(final IAssetsHandler type) { private void downloadAssets(final IAssetsHandler type) {
if (mcVersion == null || profile == null) return; if (mcVersion == null || profile == null)
return;
type.getList(profile.getMinecraftProvider().getVersionById(mcVersion), profile.getMinecraftProvider(), (value) -> { type.getList(profile.getMinecraftProvider().getVersionById(mcVersion), profile.getMinecraftProvider(), (value) -> {
if (value != null) if (value != null)
SwingUtilities.invokeLater(() -> TaskWindow.getInstance().addTask(type.getDownloadTask(Settings.getInstance().getDownloadSource().getProvider())).start()); SwingUtilities.invokeLater(() -> TaskWindow.getInstance().addTask(type.getDownloadTask(Settings.getInstance().getDownloadSource().getProvider())).start());
}); });
} }
// </editor-fold> // </editor-fold>
@@ -1593,14 +1623,16 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
return true; return true;
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
DefaultTableModel model = (DefaultTableModel) lstDownloads.getModel(); DefaultTableModel model = (DefaultTableModel) lstDownloads.getModel();
while (model.getRowCount() > 0) model.removeRow(0); while (model.getRowCount() > 0)
model.removeRow(0);
for (MinecraftRemoteVersion ver : v.versions) { for (MinecraftRemoteVersion ver : v.versions) {
Object[] line = new Object[3]; Object[] line = new Object[3];
line[0] = ver.id; line[0] = ver.id;
line[1] = ver.time; line[1] = ver.time;
if (StrUtils.equalsOne(ver.type, "old_beta", "old_alpha", "release", "snapshot")) if (StrUtils.equalsOne(ver.type, "old_beta", "old_alpha", "release", "snapshot"))
line[2] = C.i18n("versions." + ver.type); line[2] = C.i18n("versions." + ver.type);
else line[2] = ver.type; else
line[2] = ver.type;
model.addRow(line); model.addRow(line);
} }
lstDownloads.updateUI(); lstDownloads.updateUI();
@@ -1621,7 +1653,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
} }
void downloadMinecraft(DownloadType index) { void downloadMinecraft(DownloadType index) {
if (profile == null) return; if (profile == null)
return;
if (lstDownloads.getSelectedRow() < 0) if (lstDownloads.getSelectedRow() < 0)
refreshDownloads(Settings.getInstance().getDownloadSource()); refreshDownloads(Settings.getInstance().getDownloadSource());
if (lstDownloads.getSelectedRow() < 0) { if (lstDownloads.getSelectedRow() < 0) {
@@ -1687,8 +1720,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
void refreshVersions() { void refreshVersions() {
list = Settings.getInstance().getDownloadSource().getProvider().getInstallerByType(id); list = Settings.getInstance().getDownloadSource().getProvider().getInstallerByType(id);
if (TaskWindow.getInstance().addTask(new TaskRunnableArg1<>(C.i18n("install." + id + ".get_list"), list) if (TaskWindow.getInstance().addTask(new TaskRunnableArg1<>(C.i18n("install." + id + ".get_list"), list)
.registerPreviousResult(new DefaultPreviousResult<>(new String[]{getMinecraftVersionFormatted()}))) .registerPreviousResult(new DefaultPreviousResult<>(new String[] {getMinecraftVersionFormatted()})))
.start()) .start())
loadVersions(); loadVersions();
} }
@@ -1708,7 +1741,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
for (InstallerVersionList.InstallerVersion v : ver) { for (InstallerVersionList.InstallerVersion v : ver) {
Object a = v.selfVersion == null ? "null" : v.selfVersion; Object a = v.selfVersion == null ? "null" : v.selfVersion;
Object b = v.mcVersion == null ? "null" : v.mcVersion; Object b = v.mcVersion == null ? "null" : v.mcVersion;
Object[] row = new Object[]{a, b}; Object[] row = new Object[] {a, b};
model.addRow(row); model.addRow(row);
} }
table.updateUI(); table.updateUI();
@@ -1744,7 +1777,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
SwingUtils.clearDefaultTable(lstExternalMods); SwingUtils.clearDefaultTable(lstExternalMods);
DefaultTableModel model = (DefaultTableModel) lstExternalMods.getModel(); DefaultTableModel model = (DefaultTableModel) lstExternalMods.getModel();
for (ModInfo info : mods) for (ModInfo info : mods)
model.addRow(new Object[]{info.isActive(), info.getFileName(), info.version}); model.addRow(new Object[] {info.isActive(), info.getFileName(), info.version});
} }
}); });
} }
@@ -1763,10 +1796,12 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
public void onSelected() { public void onSelected() {
loadProfiles(); loadProfiles();
if (profile == null) return; if (profile == null)
return;
if (profile.getMinecraftProvider().getVersionCount() <= 0) if (profile.getMinecraftProvider().getVersionCount() <= 0)
versionChanged(profile, null); versionChanged(profile, null);
else versionChanged(getProfile(), (String) cboVersions.getSelectedItem()); else
versionChanged(getProfile(), (String) cboVersions.getSelectedItem());
} }
public void showGameDownloads() { public void showGameDownloads() {

View File

@@ -29,7 +29,7 @@ import javax.swing.JLabel;
* @author huangyuhui * @author huangyuhui
*/ */
public class HeaderTab extends JLabel public class HeaderTab extends JLabel
implements MouseListener { implements MouseListener {
private boolean isActive; private boolean isActive;
private final DefaultButtonModel model; private final DefaultButtonModel model;

View File

@@ -186,7 +186,8 @@ public final class MainFrame extends DraggableFrame {
@Override @Override
public void mouseClicked(MouseEvent e) { public void mouseClicked(MouseEvent e) {
if (UpdateChecker.OUT_DATED) Main.update(); if (UpdateChecker.OUT_DATED)
Main.update();
} }
@Override @Override
@@ -361,7 +362,7 @@ public final class MainFrame extends DraggableFrame {
int contentWidth = width - off - off; int contentWidth = width - off - off;
int contentHeight = height - off - off; int contentHeight = height - off - off;
BufferedImage contentImage = new BufferedImage(contentWidth, BufferedImage contentImage = new BufferedImage(contentWidth,
contentHeight, Transparency.OPAQUE); contentHeight, Transparency.OPAQUE);
Graphics2D contentG2d = contentImage.createGraphics(); Graphics2D contentG2d = contentImage.createGraphics();
contentG2d.translate(-off, -off); contentG2d.translate(-off, -off);
paintImpl(g); paintImpl(g);

View File

@@ -275,9 +275,11 @@ public class MainPagePanel extends javax.swing.JPanel {
}//GEN-LAST:event_txtPlayerNameFocusLost }//GEN-LAST:event_txtPlayerNameFocusLost
private void cboLoginModeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboLoginModeItemStateChanged private void cboLoginModeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboLoginModeItemStateChanged
if (preaparingAuth) return; if (preaparingAuth)
return;
int index = cboLoginMode.getSelectedIndex(); int index = cboLoginMode.getSelectedIndex();
if (index < 0) return; if (index < 0)
return;
IAuthenticator l = IAuthenticator.LOGINS.get(index); IAuthenticator l = IAuthenticator.LOGINS.get(index);
if (l.isHidePasswordBox()) { if (l.isHidePasswordBox()) {
@@ -289,10 +291,13 @@ public class MainPagePanel extends javax.swing.JPanel {
} }
CardLayout cl = (CardLayout) pnlPassword.getLayout(); CardLayout cl = (CardLayout) pnlPassword.getLayout();
if (l.isLoggedIn()) cl.last(pnlPassword); if (l.isLoggedIn())
else cl.first(pnlPassword); cl.last(pnlPassword);
else
cl.first(pnlPassword);
String username = Settings.getInstance().getUsername(); String username = Settings.getInstance().getUsername();
if (StrUtils.isNotBlank(username)) txtPlayerName.setText(username); if (StrUtils.isNotBlank(username))
txtPlayerName.setText(username);
Settings.getInstance().setLoginType(index); Settings.getInstance().setLoginType(index);
}//GEN-LAST:event_cboLoginModeItemStateChanged }//GEN-LAST:event_cboLoginModeItemStateChanged
@@ -321,12 +326,14 @@ public class MainPagePanel extends javax.swing.JPanel {
}//GEN-LAST:event_txtPasswordActionPerformed }//GEN-LAST:event_txtPasswordActionPerformed
private void btnLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogoutActionPerformed private void btnLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogoutActionPerformed
if (preaparingAuth) return; if (preaparingAuth)
return;
int index = cboLoginMode.getSelectedIndex(); int index = cboLoginMode.getSelectedIndex();
IAuthenticator l = IAuthenticator.LOGINS.get(index); IAuthenticator l = IAuthenticator.LOGINS.get(index);
CardLayout cl = (CardLayout) pnlPassword.getLayout(); CardLayout cl = (CardLayout) pnlPassword.getLayout();
if (l.isLoggedIn()) l.logout(); if (l.isLoggedIn())
l.logout();
cl.first(pnlPassword); cl.first(pnlPassword);
}//GEN-LAST:event_btnLogoutActionPerformed }//GEN-LAST:event_btnLogoutActionPerformed
@@ -334,22 +341,27 @@ public class MainPagePanel extends javax.swing.JPanel {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) { if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
Settings.getInstance().setUsername(txtPlayerName.getText()); Settings.getInstance().setUsername(txtPlayerName.getText());
int index = cboLoginMode.getSelectedIndex(); int index = cboLoginMode.getSelectedIndex();
if (index < 0) return; if (index < 0)
return;
IAuthenticator l = IAuthenticator.LOGINS.get(index); IAuthenticator l = IAuthenticator.LOGINS.get(index);
if (l.isHidePasswordBox()) btnRunActionPerformed(); if (l.isHidePasswordBox())
else if (!l.isLoggedIn()) txtPassword.requestFocus(); btnRunActionPerformed();
else if (!l.isLoggedIn())
txtPassword.requestFocus();
} }
}//GEN-LAST:event_txtPlayerNameKeyPressed }//GEN-LAST:event_txtPlayerNameKeyPressed
private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) btnRunActionPerformed(); if (evt.getKeyCode() == KeyEvent.VK_ENTER)
btnRunActionPerformed();
}//GEN-LAST:event_txtPasswordKeyPressed }//GEN-LAST:event_txtPasswordKeyPressed
boolean isLaunching = false; boolean isLaunching = false;
// <editor-fold defaultstate="collapsed" desc="Game Launch"> // <editor-fold defaultstate="collapsed" desc="Game Launch">
void genLaunchCode(final Consumer<GameLauncher> listener) { void genLaunchCode(final Consumer<GameLauncher> listener) {
if (isLaunching || getCurrentProfile() == null) return; if (isLaunching || getCurrentProfile() == null)
return;
isLaunching = true; isLaunching = true;
HMCLog.log("Start generating launching command..."); HMCLog.log("Start generating launching command...");
File file = getCurrentProfile().getCanonicalGameDirFile(); File file = getCurrentProfile().getCanonicalGameDirFile();
@@ -379,7 +391,8 @@ public class MainPagePanel extends javax.swing.JPanel {
Thread.currentThread().setName("Game Launcher"); Thread.currentThread().setName("Game Launcher");
DefaultGameLauncher gl = new DefaultGameLauncher(getCurrentProfile(), li, l, Settings.getInstance().getDownloadSource()); DefaultGameLauncher gl = new DefaultGameLauncher(getCurrentProfile(), li, l, Settings.getInstance().getDownloadSource());
gl.failEvent.register((sender, s) -> { gl.failEvent.register((sender, s) -> {
if (s != null) MessageBox.Show(s); if (s != null)
MessageBox.Show(s);
MainFrame.instance.closeMessage(); MainFrame.instance.closeMessage();
isLaunching = false; isLaunching = false;
return true; return true;
@@ -417,7 +430,8 @@ public class MainPagePanel extends javax.swing.JPanel {
} }
void loadFromSettings() { void loadFromSettings() {
for (Profile s : Settings.getProfilesFiltered()) cboProfiles.addItem(s.getName()); for (Profile s : Settings.getProfilesFiltered())
cboProfiles.addItem(s.getName());
} }
boolean showedNoVersion = false; boolean showedNoVersion = false;
@@ -433,7 +447,7 @@ public class MainPagePanel extends javax.swing.JPanel {
if (getCurrentProfile().getMinecraftProvider().getVersions().isEmpty()) { if (getCurrentProfile().getMinecraftProvider().getVersions().isEmpty()) {
if (!showedNoVersion) if (!showedNoVersion)
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
if(MessageBox.Show(C.i18n("mainwindow.no_version"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) { if (MessageBox.Show(C.i18n("mainwindow.no_version"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
MainFrame.instance.selectTab("game"); MainFrame.instance.selectTab("game");
MainFrame.instance.gamePanel.showGameDownloads(); MainFrame.instance.gamePanel.showGameDownloads();
} }
@@ -441,12 +455,15 @@ public class MainPagePanel extends javax.swing.JPanel {
}); });
} else { } else {
for (MinecraftVersion mcVersion : getCurrentProfile().getMinecraftProvider().getVersions()) { for (MinecraftVersion mcVersion : getCurrentProfile().getMinecraftProvider().getVersions()) {
if (mcVersion.hidden) continue; if (mcVersion.hidden)
continue;
cboVersions.addItem(mcVersion.id); cboVersions.addItem(mcVersion.id);
if (mcVersion.id.equals(selectedMC)) index = i; if (mcVersion.id.equals(selectedMC))
index = i;
i++; i++;
} }
if (index < cboVersions.getItemCount()) cboVersions.setSelectedIndex(index); if (index < cboVersions.getItemCount())
cboVersions.setSelectedIndex(index);
} }
} }
isLoading = false; isLoading = false;

View File

@@ -147,7 +147,6 @@ public final class NewProfileWindow extends javax.swing.JDialog {
this.dispose(); this.dispose();
}//GEN-LAST:event_btnCancelActionPerformed }//GEN-LAST:event_btnCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables // Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel; private javax.swing.JButton btnCancel;
private javax.swing.JButton btnOK; private javax.swing.JButton btnOK;

View File

@@ -21,7 +21,7 @@ if (!hasProperty('mainClass')) {
} }
if (System.getenv("BUILD_NUMBER") != null) if (System.getenv("BUILD_NUMBER") != null)
version = System.getenv("BUILD_NUMBER") version = System.getenv("BUILD_NUMBER")
buildscript { buildscript {
repositories { repositories {

View File

@@ -35,7 +35,7 @@ public final class C {
ResourceBundle rb = null; ResourceBundle rb = null;
try { try {
rb = ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N"); rb = ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N");
} catch(Throwable t) { } catch (Throwable t) {
rb = null; rb = null;
System.out.println("Did you delete I18N.properties?"); System.out.println("Did you delete I18N.properties?");
t.printStackTrace(); t.printStackTrace();

View File

@@ -26,45 +26,42 @@ public class AppenderControl {
private final int intLevel; private final int intLevel;
public AppenderControl(IAppender appender, Level level) { public AppenderControl(IAppender appender, Level level) {
this.appender = appender; this.appender = appender;
this.level = level; this.level = level;
this.intLevel = (level == null ? Level.ALL.level : level.level); this.intLevel = (level == null ? Level.ALL.level : level.level);
} }
public IAppender getAppender() { public IAppender getAppender() {
return this.appender; return this.appender;
} }
public void callAppender(LogEvent event) { public void callAppender(LogEvent event) {
if ((this.level != null) if ((this.level != null)
&& (this.intLevel < event.level.level)) { && (this.intLevel < event.level.level))
return; return;
}
if (this.recursive.get() != null) { if (this.recursive.get() != null) {
System.err.println("Recursive call to appender " + this.appender.getName()); System.err.println("Recursive call to appender " + this.appender.getName());
return; return;
} }
try { try {
this.recursive.set(this); this.recursive.set(this);
try { try {
this.appender.append(event); this.appender.append(event);
} catch (RuntimeException ex) { } catch (RuntimeException ex) {
System.err.println("An exception occurred processing Appender " + this.appender.getName()); System.err.println("An exception occurred processing Appender " + this.appender.getName());
ex.printStackTrace(); ex.printStackTrace();
if (!this.appender.ignoreExceptions()) { if (!this.appender.ignoreExceptions())
throw ex; throw ex;
} } catch (Exception ex) {
} catch (Exception ex) { System.err.println("An exception occurred processing Appender " + this.appender.getName());
System.err.println("An exception occurred processing Appender " + this.appender.getName()); ex.printStackTrace();
ex.printStackTrace(); if (!this.appender.ignoreExceptions())
if (!this.appender.ignoreExceptions()) { throw new LoggingException(ex);
throw new LoggingException(ex); }
} } finally {
} this.recursive.set(null);
} finally { }
this.recursive.set(null);
}
} }
} }

View File

@@ -25,7 +25,6 @@ import org.jackhuang.hellominecraft.logging.layout.DefaultLayout;
* *
* @author huangyuhui * @author huangyuhui
*/ */
public class Configuration { public class Configuration {
public ArrayList<IAppender> appenders = new ArrayList<IAppender>(); public ArrayList<IAppender> appenders = new ArrayList<IAppender>();
@@ -33,8 +32,8 @@ public class Configuration {
public static Configuration DEFAULT; public static Configuration DEFAULT;
static { static {
DEFAULT = new Configuration(); DEFAULT = new Configuration();
DEFAULT.appenders.add(new ConsoleAppender("Console", new DefaultLayout(), true, new ConsoleAppender.SystemOutStream(), true)); DEFAULT.appenders.add(new ConsoleAppender("Console", new DefaultLayout(), true, new ConsoleAppender.SystemOutStream(), true));
} }
} }

View File

@@ -73,7 +73,7 @@ public enum Level {
level = DEBUG; level = DEBUG;
} else { } else {
if (line.contains("[INFO]") || line.contains("[CONFIG]") || line.contains("[FINE]") if (line.contains("[INFO]") || line.contains("[CONFIG]") || line.contains("[FINE]")
|| line.contains("[FINER]") || line.contains("[FINEST]")) || line.contains("[FINER]") || line.contains("[FINEST]"))
level = INFO; level = INFO;
if (line.contains("[SEVERE]") || line.contains("[STDERR]")) if (line.contains("[SEVERE]") || line.contains("[STDERR]"))
level = ERROR; level = ERROR;
@@ -86,10 +86,10 @@ public enum Level {
return FATAL; return FATAL;
if (line.contains("Exception in thread") if (line.contains("Exception in thread")
|| line.matches("\\s+at " + JAVA_SYMBOL) || line.matches("\\s+at " + JAVA_SYMBOL)
|| line.matches("Caused by: " + JAVA_SYMBOL) || line.matches("Caused by: " + JAVA_SYMBOL)
|| line.matches("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$]?[a-zA-Z\\d_$]*(Exception|Error|Throwable)") || line.matches("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$]?[a-zA-Z\\d_$]*(Exception|Error|Throwable)")
|| line.matches("... \\d+ more$")) || line.matches("... \\d+ more$"))
return ERROR; return ERROR;
return level; return level;
} }

View File

@@ -23,7 +23,7 @@ package org.jackhuang.hellominecraft.logging;
public class LoggingException extends RuntimeException { public class LoggingException extends RuntimeException {
public LoggingException(Exception e) { public LoggingException(Exception e) {
super(e); super(e);
} }
} }

View File

@@ -30,27 +30,27 @@ public abstract class AbstractAppender implements IAppender {
private final boolean ignoreExceptions; private final boolean ignoreExceptions;
public AbstractAppender(String name, ILayout<? extends Serializable> layout) { public AbstractAppender(String name, ILayout<? extends Serializable> layout) {
this(name, layout, true); this(name, layout, true);
} }
public AbstractAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions) { public AbstractAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions) {
this.name = name; this.name = name;
this.layout = layout; this.layout = layout;
this.ignoreExceptions = ignoreExceptions; this.ignoreExceptions = ignoreExceptions;
} }
@Override @Override
public String getName() { public String getName() {
return name; return name;
} }
@Override @Override
public boolean ignoreExceptions() { public boolean ignoreExceptions() {
return ignoreExceptions; return ignoreExceptions;
} }
@Override @Override
public ILayout<? extends Serializable> getLayout() { public ILayout<? extends Serializable> getLayout() {
return this.layout; return this.layout;
} }
} }

View File

@@ -28,62 +28,62 @@ import org.jackhuang.hellominecraft.logging.layout.ILayout;
public class ConsoleAppender extends OutputStreamAppender { public class ConsoleAppender extends OutputStreamAppender {
public ConsoleAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions, OutputStream stream, boolean immediateFlush) { public ConsoleAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions, OutputStream stream, boolean immediateFlush) {
super(name, layout, ignoreExceptions, stream, true); super(name, layout, ignoreExceptions, stream, true);
} }
public static class SystemOutStream extends OutputStream { public static class SystemOutStream extends OutputStream {
@Override @Override
public void close() { public void close() {
} }
@Override @Override
public void flush() { public void flush() {
System.out.flush(); System.out.flush();
} }
@Override @Override
public void write(byte[] b) throws IOException { public void write(byte[] b) throws IOException {
System.out.write(b); System.out.write(b);
} }
@Override @Override
public void write(byte[] b, int off, int len) public void write(byte[] b, int off, int len)
throws IOException { throws IOException {
System.out.write(b, off, len); System.out.write(b, off, len);
} }
@Override @Override
public void write(int b) throws IOException { public void write(int b) throws IOException {
System.out.write(b); System.out.write(b);
} }
} }
public static class SystemErrStream extends OutputStream { public static class SystemErrStream extends OutputStream {
@Override @Override
public void close() { public void close() {
} }
@Override @Override
public void flush() { public void flush() {
System.err.flush(); System.err.flush();
} }
@Override @Override
public void write(byte[] b) throws IOException { public void write(byte[] b) throws IOException {
System.err.write(b); System.err.write(b);
} }
@Override @Override
public void write(byte[] b, int off, int len) public void write(byte[] b, int off, int len)
throws IOException { throws IOException {
System.err.write(b, off, len); System.err.write(b, off, len);
} }
@Override @Override
public void write(int b) { public void write(int b) {
System.err.write(b); System.err.write(b);
} }
} }
} }

View File

@@ -27,8 +27,11 @@ import org.jackhuang.hellominecraft.logging.layout.ILayout;
public interface IAppender { public interface IAppender {
void append(LogEvent event); void append(LogEvent event);
String getName(); String getName();
boolean ignoreExceptions(); boolean ignoreExceptions();
ILayout<? extends Serializable> getLayout(); ILayout<? extends Serializable> getLayout();
} }

View File

@@ -37,27 +37,26 @@ public abstract class OutputStreamAppender extends AbstractAppender {
private final Lock readLock = new ReentrantReadWriteLock().readLock(); private final Lock readLock = new ReentrantReadWriteLock().readLock();
public OutputStreamAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions, OutputStream stream, boolean immediateFlush) { public OutputStreamAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions, OutputStream stream, boolean immediateFlush) {
super(name, layout, ignoreExceptions); super(name, layout, ignoreExceptions);
this.immediateFlush = immediateFlush; this.immediateFlush = immediateFlush;
this.stream = stream; this.stream = stream;
} }
@Override @Override
public void append(LogEvent event) { public void append(LogEvent event) {
this.readLock.lock(); this.readLock.lock();
try { try {
byte[] bytes = getLayout().toByteArray(event); byte[] bytes = getLayout().toByteArray(event);
if (bytes.length > 0) { if (bytes.length > 0)
stream.write(bytes); stream.write(bytes);
} if (event.thrown != null)
if(event.thrown != null) event.thrown.printStackTrace(new PrintStream(stream));
event.thrown.printStackTrace(new PrintStream(stream)); } catch (IOException ex) {
} catch (IOException ex) { System.err.println("Unable to write to stream for appender: " + getName());
System.err.println("Unable to write to stream for appender: " + getName()); throw new LoggingException(ex);
throw new LoggingException(ex); } finally {
} finally { this.readLock.unlock();
this.readLock.unlock(); }
}
} }
} }

View File

@@ -26,7 +26,7 @@ public abstract class AbstractStringLayout implements ILayout<String> {
@Override @Override
public byte[] toByteArray(LogEvent event) { public byte[] toByteArray(LogEvent event) {
return toSerializable(event).getBytes(); return toSerializable(event).getBytes();
} }
} }

View File

@@ -25,11 +25,12 @@ import org.jackhuang.hellominecraft.logging.LogEvent;
* @author huangyuhui * @author huangyuhui
*/ */
public class DefaultLayout extends AbstractStringLayout { public class DefaultLayout extends AbstractStringLayout {
private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
@Override @Override
public String toSerializable(LogEvent event) { public String toSerializable(LogEvent event) {
return "[" + sdf.format(new Date()) + "] [" + event.threadName + "/" + event.level.name() + "] " + event.message.getFormattedMessage() + "\n"; return "[" + sdf.format(new Date()) + "] [" + event.threadName + "/" + event.level.name() + "] " + event.message.getFormattedMessage() + "\n";
} }
} }

View File

@@ -27,6 +27,7 @@ import org.jackhuang.hellominecraft.logging.LogEvent;
public interface ILayout<T extends Serializable> { public interface ILayout<T extends Serializable> {
byte[] toByteArray(LogEvent event); byte[] toByteArray(LogEvent event);
T toSerializable(LogEvent event); T toSerializable(LogEvent event);
} }

View File

@@ -23,7 +23,7 @@ import org.jackhuang.hellominecraft.logging.message.ParameterizedMessageFactory;
import org.jackhuang.hellominecraft.logging.message.StringFormattedMessage; import org.jackhuang.hellominecraft.logging.message.StringFormattedMessage;
public abstract class AbstractLogger public abstract class AbstractLogger
implements ILogger { implements ILogger {
public static final Class<? extends IMessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS = ParameterizedMessageFactory.class; public static final Class<? extends IMessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS = ParameterizedMessageFactory.class;
@@ -34,278 +34,249 @@ public abstract class AbstractLogger
private final IMessageFactory messageFactory; private final IMessageFactory messageFactory;
public AbstractLogger() { public AbstractLogger() {
this.name = getClass().getName(); this.name = getClass().getName();
this.messageFactory = createDefaultMessageFactory(); this.messageFactory = createDefaultMessageFactory();
} }
public AbstractLogger(String name) { public AbstractLogger(String name) {
this.name = name; this.name = name;
this.messageFactory = createDefaultMessageFactory(); this.messageFactory = createDefaultMessageFactory();
} }
public AbstractLogger(String name, IMessageFactory messageFactory) { public AbstractLogger(String name, IMessageFactory messageFactory) {
this.name = name; this.name = name;
this.messageFactory = (messageFactory == null ? createDefaultMessageFactory() : messageFactory); this.messageFactory = (messageFactory == null ? createDefaultMessageFactory() : messageFactory);
} }
private IMessageFactory createDefaultMessageFactory() { private IMessageFactory createDefaultMessageFactory() {
try { try {
return (IMessageFactory) DEFAULT_MESSAGE_FACTORY_CLASS.newInstance(); return (IMessageFactory) DEFAULT_MESSAGE_FACTORY_CLASS.newInstance();
} catch (InstantiationException e) { } catch (InstantiationException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
} }
@Override @Override
public void catching(Level level, Throwable t) { public void catching(Level level, Throwable t) {
if (isEnabled(level, (Object) null, null)) { if (isEnabled(level, (Object) null, null))
log(level, this.messageFactory.newMessage(CATCHING), t); log(level, this.messageFactory.newMessage(CATCHING), t);
}
} }
@Override @Override
public void catching(Throwable t) { public void catching(Throwable t) {
catching(Level.ERROR, t); catching(Level.ERROR, t);
} }
@Override @Override
public void debug(IMessage msg) { public void debug(IMessage msg) {
if (isEnabled(Level.DEBUG, msg, null)) { if (isEnabled(Level.DEBUG, msg, null))
log(Level.DEBUG, msg, null); log(Level.DEBUG, msg, null);
}
} }
@Override @Override
public void debug(IMessage msg, Throwable t) { public void debug(IMessage msg, Throwable t) {
if (isEnabled(Level.DEBUG, msg, t)) { if (isEnabled(Level.DEBUG, msg, t))
log(Level.DEBUG, msg, t); log(Level.DEBUG, msg, t);
}
} }
@Override @Override
public void debug(Object message) { public void debug(Object message) {
if (isEnabled(Level.DEBUG, message, null)) { if (isEnabled(Level.DEBUG, message, null))
log(Level.DEBUG, this.messageFactory.newMessage(message), null); log(Level.DEBUG, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void debug(Object message, Throwable t) { public void debug(Object message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t)) { if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t); log(Level.DEBUG, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void debug(String message) { public void debug(String message) {
if (isEnabled(Level.DEBUG, message)) { if (isEnabled(Level.DEBUG, message))
log(Level.DEBUG, this.messageFactory.newMessage(message), null); log(Level.DEBUG, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void debug(String message, Object[] params) { public void debug(String message, Object[] params) {
if (isEnabled(Level.DEBUG, message, params)) { if (isEnabled(Level.DEBUG, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params); IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.DEBUG, msg, msg.getThrowable()); log(Level.DEBUG, msg, msg.getThrowable());
} }
} }
@Override @Override
public void debug(String message, Throwable t) { public void debug(String message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t)) { if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t); log(Level.DEBUG, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void entry() { public void entry() {
entry(new Object[0]); entry(new Object[0]);
} }
@Override @Override
public void entry(Object[] params) { public void entry(Object[] params) {
if (isEnabled(Level.TRACE, (Object) null, null)) { if (isEnabled(Level.TRACE, (Object) null, null))
log(Level.TRACE, entryMsg(params.length, params), null); log(Level.TRACE, entryMsg(params.length, params), null);
}
} }
private IMessage entryMsg(int count, Object[] params) { private IMessage entryMsg(int count, Object[] params) {
if (count == 0) { if (count == 0)
return this.messageFactory.newMessage("entry"); return this.messageFactory.newMessage("entry");
} StringBuilder sb = new StringBuilder("entry params(");
StringBuilder sb = new StringBuilder("entry params("); int i = 0;
int i = 0; for (Object parm : params) {
for (Object parm : params) { if (parm != null)
if (parm != null) { sb.append(parm.toString());
sb.append(parm.toString()); else
} else { sb.append("null");
sb.append("null"); i++;
} if (i < params.length)
i++; sb.append(", ");
if (i < params.length) { }
sb.append(", "); sb.append(")");
} return this.messageFactory.newMessage(sb.toString());
}
sb.append(")");
return this.messageFactory.newMessage(sb.toString());
} }
@Override @Override
public void error(IMessage msg) { public void error(IMessage msg) {
if (isEnabled(Level.ERROR, msg, null)) { if (isEnabled(Level.ERROR, msg, null))
log(Level.ERROR, msg, null); log(Level.ERROR, msg, null);
}
} }
@Override @Override
public void error(IMessage msg, Throwable t) { public void error(IMessage msg, Throwable t) {
if (isEnabled(Level.ERROR, msg, t)) { if (isEnabled(Level.ERROR, msg, t))
log(Level.ERROR, msg, t); log(Level.ERROR, msg, t);
}
} }
@Override @Override
public void error(Object message) { public void error(Object message) {
if (isEnabled(Level.ERROR, message, null)) { if (isEnabled(Level.ERROR, message, null))
log(Level.ERROR, this.messageFactory.newMessage(message), null); log(Level.ERROR, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void error(Object message, Throwable t) { public void error(Object message, Throwable t) {
if (isEnabled(Level.ERROR, message, t)) { if (isEnabled(Level.ERROR, message, t))
log(Level.ERROR, this.messageFactory.newMessage(message), t); log(Level.ERROR, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void error(String message) { public void error(String message) {
if (isEnabled(Level.ERROR, message)) { if (isEnabled(Level.ERROR, message))
log(Level.ERROR, this.messageFactory.newMessage(message), null); log(Level.ERROR, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void error(String message, Object[] params) { public void error(String message, Object[] params) {
if (isEnabled(Level.ERROR, message, params)) { if (isEnabled(Level.ERROR, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params); IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.ERROR, msg, msg.getThrowable()); log(Level.ERROR, msg, msg.getThrowable());
} }
} }
@Override @Override
public void error(String message, Throwable t) { public void error(String message, Throwable t) {
if (isEnabled(Level.ERROR, message, t)) { if (isEnabled(Level.ERROR, message, t))
log(Level.ERROR, this.messageFactory.newMessage(message), t); log(Level.ERROR, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void fatal(IMessage msg) { public void fatal(IMessage msg) {
if (isEnabled(Level.FATAL, msg, null)) { if (isEnabled(Level.FATAL, msg, null))
log(Level.FATAL, msg, null); log(Level.FATAL, msg, null);
}
} }
@Override @Override
public void fatal(IMessage msg, Throwable t) { public void fatal(IMessage msg, Throwable t) {
if (isEnabled(Level.FATAL, msg, t)) { if (isEnabled(Level.FATAL, msg, t))
log(Level.FATAL, msg, t); log(Level.FATAL, msg, t);
}
} }
@Override @Override
public void fatal(Object message) { public void fatal(Object message) {
if (isEnabled(Level.FATAL, message, null)) { if (isEnabled(Level.FATAL, message, null))
log(Level.FATAL, this.messageFactory.newMessage(message), null); log(Level.FATAL, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void fatal(Object message, Throwable t) { public void fatal(Object message, Throwable t) {
if (isEnabled(Level.FATAL, message, t)) { if (isEnabled(Level.FATAL, message, t))
log(Level.FATAL, this.messageFactory.newMessage(message), t); log(Level.FATAL, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void fatal(String message) { public void fatal(String message) {
if (isEnabled(Level.FATAL, message)) { if (isEnabled(Level.FATAL, message))
log(Level.FATAL, this.messageFactory.newMessage(message), null); log(Level.FATAL, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void fatal(String message, Object[] params) { public void fatal(String message, Object[] params) {
if (isEnabled(Level.FATAL, message, params)) { if (isEnabled(Level.FATAL, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params); IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.FATAL, msg, msg.getThrowable()); log(Level.FATAL, msg, msg.getThrowable());
} }
} }
@Override @Override
public void fatal(String message, Throwable t) { public void fatal(String message, Throwable t) {
if (isEnabled(Level.FATAL, message, t)) { if (isEnabled(Level.FATAL, message, t))
log(Level.FATAL, this.messageFactory.newMessage(message), t); log(Level.FATAL, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public String getName() { public String getName() {
return this.name; return this.name;
} }
@Override @Override
public void info(IMessage msg) { public void info(IMessage msg) {
if (isEnabled(Level.INFO, msg, null)) { if (isEnabled(Level.INFO, msg, null))
log(Level.INFO, msg, null); log(Level.INFO, msg, null);
}
} }
@Override @Override
public void info(IMessage msg, Throwable t) { public void info(IMessage msg, Throwable t) {
if (isEnabled(Level.INFO, msg, t)) { if (isEnabled(Level.INFO, msg, t))
log(Level.INFO, msg, t); log(Level.INFO, msg, t);
}
} }
@Override @Override
public void info(Object message) { public void info(Object message) {
if (isEnabled(Level.INFO, message, null)) { if (isEnabled(Level.INFO, message, null))
log(Level.INFO, this.messageFactory.newMessage(message), null); log(Level.INFO, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void info(Object message, Throwable t) { public void info(Object message, Throwable t) {
if (isEnabled(Level.INFO, message, t)) { if (isEnabled(Level.INFO, message, t))
log(Level.INFO, this.messageFactory.newMessage(message), t); log(Level.INFO, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void info(String message) { public void info(String message) {
if (isEnabled(Level.INFO, message)) { if (isEnabled(Level.INFO, message))
log(Level.INFO, this.messageFactory.newMessage(message), null); log(Level.INFO, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void info(String message, Object[] params) { public void info(String message, Object[] params) {
if (isEnabled(Level.INFO, message, params)) { if (isEnabled(Level.INFO, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params); IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.INFO, msg, msg.getThrowable()); log(Level.INFO, msg, msg.getThrowable());
} }
} }
@Override @Override
public void info(String message, Throwable t) { public void info(String message, Throwable t) {
if (isEnabled(Level.INFO, message, t)) { if (isEnabled(Level.INFO, message, t))
log(Level.INFO, this.messageFactory.newMessage(message), t); log(Level.INFO, this.messageFactory.newMessage(message), t);
}
} }
protected abstract boolean isEnabled(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable); protected abstract boolean isEnabled(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable);
@@ -322,213 +293,194 @@ public abstract class AbstractLogger
@Override @Override
public boolean isErrorEnabled() { public boolean isErrorEnabled() {
return isEnabled(Level.ERROR); return isEnabled(Level.ERROR);
} }
@Override @Override
public boolean isFatalEnabled() { public boolean isFatalEnabled() {
return isEnabled(Level.FATAL); return isEnabled(Level.FATAL);
} }
@Override @Override
public boolean isInfoEnabled() { public boolean isInfoEnabled() {
return isEnabled(Level.INFO); return isEnabled(Level.INFO);
} }
@Override @Override
public boolean isTraceEnabled() { public boolean isTraceEnabled() {
return isEnabled(Level.TRACE); return isEnabled(Level.TRACE);
} }
@Override @Override
public boolean isWarnEnabled() { public boolean isWarnEnabled() {
return isEnabled(Level.WARN); return isEnabled(Level.WARN);
} }
@Override @Override
public boolean isDebugEnabled() { public boolean isDebugEnabled() {
return isEnabled(Level.DEBUG); return isEnabled(Level.DEBUG);
} }
@Override @Override
public boolean isEnabled(Level level) { public boolean isEnabled(Level level) {
return isEnabled(level, (Object) null, null); return isEnabled(level, (Object) null, null);
} }
@Override @Override
public void log(Level level, IMessage msg) { public void log(Level level, IMessage msg) {
if (isEnabled(level, msg, null)) { if (isEnabled(level, msg, null))
log(level, msg, null); log(level, msg, null);
}
} }
@Override @Override
public void log(Level level, IMessage msg, Throwable t) { public void log(Level level, IMessage msg, Throwable t) {
if (isEnabled(level, msg, t)) { if (isEnabled(level, msg, t))
abstractLog(level, msg, t); abstractLog(level, msg, t);
}
} }
@Override @Override
public void log(Level level, Object message) { public void log(Level level, Object message) {
if (isEnabled(level, message, null)) { if (isEnabled(level, message, null))
log(level, this.messageFactory.newMessage(message), null); log(level, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void log(Level level, Object message, Throwable t) { public void log(Level level, Object message, Throwable t) {
if (isEnabled(level, message, t)) { if (isEnabled(level, message, t))
log(level, this.messageFactory.newMessage(message), t); log(level, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void log(Level level, String message) { public void log(Level level, String message) {
if (isEnabled(level, message)) { if (isEnabled(level, message))
log(level, this.messageFactory.newMessage(message), null); log(level, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void log(Level level, String message, Object[] params) { public void log(Level level, String message, Object[] params) {
if (isEnabled(level, message, params)) { if (isEnabled(level, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params); IMessage msg = this.messageFactory.newMessage(message, params);
log(level, msg, msg.getThrowable()); log(level, msg, msg.getThrowable());
} }
} }
@Override @Override
public void log(Level level, String message, Throwable t) { public void log(Level level, String message, Throwable t) {
if (isEnabled(level, message, t)) { if (isEnabled(level, message, t))
log(level, this.messageFactory.newMessage(message), t); log(level, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void printf(Level level, String format, Object[] params) { public void printf(Level level, String format, Object[] params) {
if (isEnabled(level, format, params)) { if (isEnabled(level, format, params)) {
IMessage msg = new StringFormattedMessage(format, params); IMessage msg = new StringFormattedMessage(format, params);
log(level, msg, msg.getThrowable()); log(level, msg, msg.getThrowable());
} }
} }
@Override @Override
public <T extends Throwable> T throwing(T t) { public <T extends Throwable> T throwing(T t) {
return throwing(Level.ERROR, t); return throwing(Level.ERROR, t);
} }
@Override @Override
public <T extends Throwable> T throwing(Level level, T t) { public <T extends Throwable> T throwing(Level level, T t) {
if (isEnabled(level, (Object) null, null)) { if (isEnabled(level, (Object) null, null))
log(level, this.messageFactory.newMessage(THROWING), t); log(level, this.messageFactory.newMessage(THROWING), t);
} return t;
return t;
} }
@Override @Override
public String toString() { public String toString() {
return this.name; return this.name;
} }
@Override @Override
public void trace(IMessage msg) { public void trace(IMessage msg) {
if (isEnabled(Level.TRACE, msg, null)) { if (isEnabled(Level.TRACE, msg, null))
log(Level.TRACE, msg, null); log(Level.TRACE, msg, null);
}
} }
@Override @Override
public void trace(IMessage msg, Throwable t) { public void trace(IMessage msg, Throwable t) {
if (isEnabled(Level.TRACE, msg, t)) { if (isEnabled(Level.TRACE, msg, t))
log(Level.TRACE, msg, t); log(Level.TRACE, msg, t);
}
} }
@Override @Override
public void trace(Object message) { public void trace(Object message) {
if (isEnabled(Level.TRACE, message, null)) { if (isEnabled(Level.TRACE, message, null))
log(Level.TRACE, this.messageFactory.newMessage(message), null); log(Level.TRACE, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void trace(Object message, Throwable t) { public void trace(Object message, Throwable t) {
if (isEnabled(Level.TRACE, message, t)) { if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t); log(Level.TRACE, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void trace(String message) { public void trace(String message) {
if (isEnabled(Level.TRACE, message)) { if (isEnabled(Level.TRACE, message))
log(Level.TRACE, this.messageFactory.newMessage(message), null); log(Level.TRACE, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void trace(String message, Object[] params) { public void trace(String message, Object[] params) {
if (isEnabled(Level.TRACE, message, params)) { if (isEnabled(Level.TRACE, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params); IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.TRACE, msg, msg.getThrowable()); log(Level.TRACE, msg, msg.getThrowable());
} }
} }
@Override @Override
public void trace(String message, Throwable t) { public void trace(String message, Throwable t) {
if (isEnabled(Level.TRACE, message, t)) { if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t); log(Level.TRACE, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void warn(IMessage msg) { public void warn(IMessage msg) {
if (isEnabled(Level.WARN, msg, null)) { if (isEnabled(Level.WARN, msg, null))
log(Level.WARN, msg, null); log(Level.WARN, msg, null);
}
} }
@Override @Override
public void warn(IMessage msg, Throwable t) { public void warn(IMessage msg, Throwable t) {
if (isEnabled(Level.WARN, msg, t)) { if (isEnabled(Level.WARN, msg, t))
log(Level.WARN, msg, t); log(Level.WARN, msg, t);
}
} }
@Override @Override
public void warn(Object message) { public void warn(Object message) {
if (isEnabled(Level.WARN, message, null)) { if (isEnabled(Level.WARN, message, null))
log(Level.WARN, this.messageFactory.newMessage(message), null); log(Level.WARN, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void warn(Object message, Throwable t) { public void warn(Object message, Throwable t) {
if (isEnabled(Level.WARN, message, t)) { if (isEnabled(Level.WARN, message, t))
log(Level.WARN, this.messageFactory.newMessage(message), t); log(Level.WARN, this.messageFactory.newMessage(message), t);
}
} }
@Override @Override
public void warn(String message) { public void warn(String message) {
if (isEnabled(Level.WARN, message)) { if (isEnabled(Level.WARN, message))
log(Level.WARN, this.messageFactory.newMessage(message), null); log(Level.WARN, this.messageFactory.newMessage(message), null);
}
} }
@Override @Override
public void warn(String message, Object[] params) { public void warn(String message, Object[] params) {
if (isEnabled(Level.WARN, message, params)) { if (isEnabled(Level.WARN, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params); IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.WARN, msg, msg.getThrowable()); log(Level.WARN, msg, msg.getThrowable());
} }
} }
@Override @Override
public void warn(String message, Throwable t) { public void warn(String message, Throwable t) {
if (isEnabled(Level.WARN, message, t)) { if (isEnabled(Level.WARN, message, t))
log(Level.WARN, this.messageFactory.newMessage(message), t); log(Level.WARN, this.messageFactory.newMessage(message), t);
}
} }
} }

View File

@@ -25,132 +25,132 @@ import org.jackhuang.hellominecraft.logging.message.IMessage;
*/ */
public interface ILogger { public interface ILogger {
void catching(Level paramLevel, Throwable paramThrowable); void catching(Level paramLevel, Throwable paramThrowable);
void catching(Throwable paramThrowable); void catching(Throwable paramThrowable);
void debug(IMessage paramIMessage); void debug(IMessage paramIMessage);
void debug(IMessage paramIMessage, Throwable paramThrowable); void debug(IMessage paramIMessage, Throwable paramThrowable);
void debug(Object paramObject); void debug(Object paramObject);
void debug(Object paramObject, Throwable paramThrowable); void debug(Object paramObject, Throwable paramThrowable);
void debug(String paramString); void debug(String paramString);
void debug(String paramString, Object[] paramArrayOfObject); void debug(String paramString, Object[] paramArrayOfObject);
void debug(String paramString, Throwable paramThrowable); void debug(String paramString, Throwable paramThrowable);
void entry(); void entry();
void entry(Object[] paramArrayOfObject); void entry(Object[] paramArrayOfObject);
void error(IMessage paramIMessage); void error(IMessage paramIMessage);
void error(IMessage paramIMessage, Throwable paramThrowable); void error(IMessage paramIMessage, Throwable paramThrowable);
void error(Object paramObject); void error(Object paramObject);
void error(Object paramObject, Throwable paramThrowable); void error(Object paramObject, Throwable paramThrowable);
void error(String paramString); void error(String paramString);
void error(String paramString, Object[] paramArrayOfObject); void error(String paramString, Object[] paramArrayOfObject);
void error(String paramString, Throwable paramThrowable); void error(String paramString, Throwable paramThrowable);
void fatal(IMessage paramIMessage); void fatal(IMessage paramIMessage);
void fatal(IMessage paramIMessage, Throwable paramThrowable); void fatal(IMessage paramIMessage, Throwable paramThrowable);
void fatal(Object paramObject); void fatal(Object paramObject);
void fatal(Object paramObject, Throwable paramThrowable); void fatal(Object paramObject, Throwable paramThrowable);
void fatal(String paramString); void fatal(String paramString);
void fatal(String paramString, Object[] paramArrayOfObject); void fatal(String paramString, Object[] paramArrayOfObject);
void fatal(String paramString, Throwable paramThrowable); void fatal(String paramString, Throwable paramThrowable);
String getName(); String getName();
void info(IMessage paramIMessage); void info(IMessage paramIMessage);
void info(IMessage paramIMessage, Throwable paramThrowable); void info(IMessage paramIMessage, Throwable paramThrowable);
void info(Object paramObject); void info(Object paramObject);
void info(Object paramObject, Throwable paramThrowable); void info(Object paramObject, Throwable paramThrowable);
void info(String paramString); void info(String paramString);
void info(String paramString, Object[] paramArrayOfObject); void info(String paramString, Object[] paramArrayOfObject);
void info(String paramString, Throwable paramThrowable); void info(String paramString, Throwable paramThrowable);
boolean isDebugEnabled(); boolean isDebugEnabled();
boolean isEnabled(Level paramLevel); boolean isEnabled(Level paramLevel);
boolean isErrorEnabled(); boolean isErrorEnabled();
boolean isFatalEnabled(); boolean isFatalEnabled();
boolean isInfoEnabled(); boolean isInfoEnabled();
boolean isTraceEnabled(); boolean isTraceEnabled();
boolean isWarnEnabled(); boolean isWarnEnabled();
void log(Level paramLevel, IMessage paramIMessage); void log(Level paramLevel, IMessage paramIMessage);
void log(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable); void log(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable);
void log(Level paramLevel, Object paramObject); void log(Level paramLevel, Object paramObject);
void log(Level paramLevel, Object paramObject, Throwable paramThrowable); void log(Level paramLevel, Object paramObject, Throwable paramThrowable);
void log(Level paramLevel, String paramString); void log(Level paramLevel, String paramString);
void log(Level paramLevel, String paramString, Object[] paramArrayOfObject); void log(Level paramLevel, String paramString, Object[] paramArrayOfObject);
void log(Level paramLevel, String paramString, Throwable paramThrowable); void log(Level paramLevel, String paramString, Throwable paramThrowable);
void printf(Level paramLevel, String paramString, Object[] paramArrayOfObject); void printf(Level paramLevel, String paramString, Object[] paramArrayOfObject);
<T extends Throwable> T throwing(Level paramLevel, T paramT); <T extends Throwable> T throwing(Level paramLevel, T paramT);
<T extends Throwable> T throwing(T paramT); <T extends Throwable> T throwing(T paramT);
void trace(IMessage paramIMessage); void trace(IMessage paramIMessage);
void trace(IMessage paramIMessage, Throwable paramThrowable); void trace(IMessage paramIMessage, Throwable paramThrowable);
void trace(Object paramObject); void trace(Object paramObject);
void trace(Object paramObject, Throwable paramThrowable); void trace(Object paramObject, Throwable paramThrowable);
void trace(String paramString); void trace(String paramString);
void trace(String paramString, Object[] paramArrayOfObject); void trace(String paramString, Object[] paramArrayOfObject);
void trace(String paramString, Throwable paramThrowable); void trace(String paramString, Throwable paramThrowable);
void warn(IMessage paramIMessage); void warn(IMessage paramIMessage);
void warn(IMessage paramIMessage, Throwable paramThrowable); void warn(IMessage paramIMessage, Throwable paramThrowable);
void warn(Object paramObject); void warn(Object paramObject);
void warn(Object paramObject, Throwable paramThrowable); void warn(Object paramObject, Throwable paramThrowable);
void warn(String paramString); void warn(String paramString);
void warn(String paramString, Object[] paramArrayOfObject); void warn(String paramString, Object[] paramArrayOfObject);
void warn(String paramString, Throwable paramThrowable); void warn(String paramString, Throwable paramThrowable);
} }

View File

@@ -33,136 +33,133 @@ public class Logger extends AbstractLogger {
private final Map<String, AppenderControl> appenders = new ConcurrentHashMap(); private final Map<String, AppenderControl> appenders = new ConcurrentHashMap();
public Logger(String name) { public Logger(String name) {
this(name, null, Level.INFO); this(name, null, Level.INFO);
} }
public Logger(String name, IMessageFactory messageFactory, Level defaultLevel) { public Logger(String name, IMessageFactory messageFactory, Level defaultLevel) {
super(name, messageFactory); super(name, messageFactory);
this.config = new PrivateConfig(Configuration.DEFAULT, this, defaultLevel); this.config = new PrivateConfig(Configuration.DEFAULT, this, defaultLevel);
} }
public synchronized void setLevel(Level level) { public synchronized void setLevel(Level level) {
if (level != null) { if (level != null)
this.config = new PrivateConfig(this.config, level); this.config = new PrivateConfig(this.config, level);
}
} }
public Level getLevel() { public Level getLevel() {
return this.config.level; return this.config.level;
} }
@Override @Override
public void abstractLog(Level level, IMessage data, Throwable t) { public void abstractLog(Level level, IMessage data, Throwable t) {
LogEvent event = new LogEvent(); LogEvent event = new LogEvent();
event.level = level; event.level = level;
event.message = data; event.message = data;
event.thrown = t; event.thrown = t;
event.threadName = Thread.currentThread().getName(); event.threadName = Thread.currentThread().getName();
log(event); log(event);
} }
public void log(LogEvent event) { public void log(LogEvent event) {
callAppenders(event); callAppenders(event);
} }
protected void callAppenders(LogEvent event) { protected void callAppenders(LogEvent event) {
for (AppenderControl control : this.appenders.values()) { for (AppenderControl control : this.appenders.values())
control.callAppender(event); control.callAppender(event);
}
} }
@Override @Override
public boolean isEnabled(Level level, String msg) { public boolean isEnabled(Level level, String msg) {
return this.config.filter(level, msg); return this.config.filter(level, msg);
} }
@Override @Override
public boolean isEnabled(Level level, String msg, Throwable t) { public boolean isEnabled(Level level, String msg, Throwable t) {
return this.config.filter(level, msg, t); return this.config.filter(level, msg, t);
} }
@Override @Override
public boolean isEnabled(Level level, String msg, Object[] p1) { public boolean isEnabled(Level level, String msg, Object[] p1) {
return this.config.filter(level, msg, p1); return this.config.filter(level, msg, p1);
} }
@Override @Override
public boolean isEnabled(Level level, Object msg, Throwable t) { public boolean isEnabled(Level level, Object msg, Throwable t) {
return this.config.filter(level, msg, t); return this.config.filter(level, msg, t);
} }
@Override @Override
public boolean isEnabled(Level level, IMessage msg, Throwable t) { public boolean isEnabled(Level level, IMessage msg, Throwable t) {
return this.config.filter(level, msg, t); return this.config.filter(level, msg, t);
} }
public void addAppender(IAppender appender) { public void addAppender(IAppender appender) {
this.appenders.put(appender.getName(), new AppenderControl(appender, null)); this.appenders.put(appender.getName(), new AppenderControl(appender, null));
} }
public void removeAppender(IAppender appender) { public void removeAppender(IAppender appender) {
this.appenders.remove(appender.getName()); this.appenders.remove(appender.getName());
} }
public Map<String, IAppender> getAppenders() { public Map<String, IAppender> getAppenders() {
Map map = new HashMap(); Map map = new HashMap();
for (Map.Entry entry : this.appenders.entrySet()) { for (Map.Entry entry : this.appenders.entrySet())
map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender()); map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender());
} return map;
return map;
} }
@Override @Override
public String toString() { public String toString() {
String nameLevel = "" + getName() + ":" + getLevel(); String nameLevel = "" + getName() + ":" + getLevel();
return nameLevel; return nameLevel;
} }
protected class PrivateConfig { protected class PrivateConfig {
public final Configuration config; public final Configuration config;
private final Level level; private final Level level;
private final int intLevel; private final int intLevel;
private final Logger logger; private final Logger logger;
public PrivateConfig(Configuration c, Logger logger, Level level) { public PrivateConfig(Configuration c, Logger logger, Level level) {
this.level = level; this.level = level;
this.intLevel = this.level.level; this.intLevel = this.level.level;
this.logger = logger; this.logger = logger;
this.config = c; this.config = c;
for(IAppender appender : config.appenders) for (IAppender appender : config.appenders)
addAppender(appender); addAppender(appender);
} }
public PrivateConfig(PrivateConfig pc, Level level) { public PrivateConfig(PrivateConfig pc, Level level) {
this(pc.config, pc.logger, level); this(pc.config, pc.logger, level);
} }
boolean filter(Level level, String msg) { boolean filter(Level level, String msg) {
return this.intLevel >= level.level; return this.intLevel >= level.level;
} }
boolean filter(Level level, String msg, Throwable t) { boolean filter(Level level, String msg, Throwable t) {
return this.intLevel >= level.level; return this.intLevel >= level.level;
} }
boolean filter(Level level, String msg, Object[] p1) { boolean filter(Level level, String msg, Object[] p1) {
return this.intLevel >= level.level; return this.intLevel >= level.level;
} }
boolean filter(Level level, Object msg, Throwable t) { boolean filter(Level level, Object msg, Throwable t) {
return this.intLevel >= level.level; return this.intLevel >= level.level;
} }
boolean filter(Level level, IMessage msg, Throwable t) { boolean filter(Level level, IMessage msg, Throwable t) {
return this.intLevel >= level.level; return this.intLevel >= level.level;
} }
} }
} }

View File

@@ -36,106 +36,101 @@ public class SimpleLogger extends AbstractLogger {
private final String logName; private final String logName;
public SimpleLogger(String name, Level defaultLevel, boolean showLogName, boolean showShortLogName, boolean showDateTime, boolean showContextMap, String dateTimeFormat, IMessageFactory messageFactory, PrintStream stream) { public SimpleLogger(String name, Level defaultLevel, boolean showLogName, boolean showShortLogName, boolean showDateTime, boolean showContextMap, String dateTimeFormat, IMessageFactory messageFactory, PrintStream stream) {
super(name, messageFactory); super(name, messageFactory);
this.level = defaultLevel; this.level = defaultLevel;
if (showShortLogName) { if (showShortLogName) {
int index = name.lastIndexOf("."); int index = name.lastIndexOf(".");
if ((index > 0) && (index < name.length())) { if ((index > 0) && (index < name.length()))
this.logName = name.substring(index + 1); this.logName = name.substring(index + 1);
} else { else
this.logName = name; this.logName = name;
} } else if (showLogName)
} else if (showLogName) { this.logName = name;
this.logName = name; else
} else { this.logName = null;
this.logName = null; this.showDateTime = showDateTime;
} this.showContextMap = showContextMap;
this.showDateTime = showDateTime; this.stream = stream;
this.showContextMap = showContextMap;
this.stream = stream;
if (showDateTime) { if (showDateTime)
try { try {
this.dateFormatter = new SimpleDateFormat(dateTimeFormat); this.dateFormatter = new SimpleDateFormat(dateTimeFormat);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
this.dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS zzz"); this.dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS zzz");
} }
}
} }
public void setStream(PrintStream stream) { public void setStream(PrintStream stream) {
this.stream = stream; this.stream = stream;
} }
public Level getLevel() { public Level getLevel() {
return this.level; return this.level;
} }
public void setLevel(Level level) { public void setLevel(Level level) {
if (level != null) { if (level != null)
this.level = level; this.level = level;
}
} }
@Override @Override
public void abstractLog(Level level, IMessage msg, Throwable throwable) { public void abstractLog(Level level, IMessage msg, Throwable throwable) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (this.showDateTime) { if (this.showDateTime) {
Date now = new Date(); Date now = new Date();
String dateText; String dateText;
synchronized (this.dateFormatter) { synchronized (this.dateFormatter) {
dateText = this.dateFormatter.format(now); dateText = this.dateFormatter.format(now);
} }
sb.append(dateText); sb.append(dateText);
sb.append(' '); sb.append(' ');
} }
sb.append(level.toString()); sb.append(level.toString());
sb.append(' '); sb.append(' ');
if ((this.logName != null) && (this.logName.length() > 0)) { if ((this.logName != null) && (this.logName.length() > 0)) {
sb.append(this.logName); sb.append(this.logName);
sb.append(' '); sb.append(' ');
} }
sb.append(msg.getFormattedMessage()); sb.append(msg.getFormattedMessage());
Object[] params = msg.getParameters(); Object[] params = msg.getParameters();
Throwable t; Throwable t;
if ((throwable == null) && (params != null) && ((params[(params.length - 1)] instanceof Throwable))) { if ((throwable == null) && (params != null) && ((params[(params.length - 1)] instanceof Throwable)))
t = (Throwable) params[(params.length - 1)]; t = (Throwable) params[(params.length - 1)];
} else { else
t = throwable; t = throwable;
} if (t != null) {
if (t != null) { sb.append(' ');
sb.append(' '); ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(baos));
t.printStackTrace(new PrintStream(baos)); sb.append(baos.toString());
sb.append(baos.toString()); }
} this.stream.println(sb.toString());
this.stream.println(sb.toString());
} }
@Override @Override
protected boolean isEnabled(Level level, String msg) { protected boolean isEnabled(Level level, String msg) {
return this.level.level >= level.level; return this.level.level >= level.level;
} }
@Override @Override
protected boolean isEnabled(Level level, String msg, Throwable t) { protected boolean isEnabled(Level level, String msg, Throwable t) {
return this.level.level >= level.level; return this.level.level >= level.level;
} }
@Override @Override
protected boolean isEnabled(Level level, String msg, Object[] p1) { protected boolean isEnabled(Level level, String msg, Object[] p1) {
return this.level.level >= level.level; return this.level.level >= level.level;
} }
@Override @Override
protected boolean isEnabled(Level level, Object msg, Throwable t) { protected boolean isEnabled(Level level, Object msg, Throwable t) {
return this.level.level >= level.level; return this.level.level >= level.level;
} }
@Override @Override
protected boolean isEnabled(Level level, IMessage msg, Throwable t) { protected boolean isEnabled(Level level, IMessage msg, Throwable t) {
return this.level.level >= level.level; return this.level.level >= level.level;
} }
} }

View File

@@ -21,15 +21,15 @@ package org.jackhuang.hellominecraft.logging.message;
* @author huangyuhui * @author huangyuhui
*/ */
public abstract class AbstractMessageFactory public abstract class AbstractMessageFactory
implements IMessageFactory { implements IMessageFactory {
@Override @Override
public IMessage newMessage(Object message) { public IMessage newMessage(Object message) {
return new ObjectMessage(message); return new ObjectMessage(message);
} }
@Override @Override
public IMessage newMessage(String message) { public IMessage newMessage(String message) {
return new SimpleMessage(message); return new SimpleMessage(message);
} }
} }

View File

@@ -23,8 +23,12 @@ import java.io.Serializable;
* @author huangyuhui * @author huangyuhui
*/ */
public interface IMessage extends Serializable { public interface IMessage extends Serializable {
String getFormattedMessage(); String getFormattedMessage();
String getFormat(); String getFormat();
Object[] getParameters(); Object[] getParameters();
Throwable getThrowable(); Throwable getThrowable();
} }

View File

@@ -17,15 +17,14 @@
package org.jackhuang.hellominecraft.logging.message; package org.jackhuang.hellominecraft.logging.message;
public class ObjectMessage public class ObjectMessage
implements IMessage { implements IMessage {
private static final long serialVersionUID = -5903272448334166185L; private static final long serialVersionUID = -5903272448334166185L;
private final transient Object obj; private final transient Object obj;
public ObjectMessage(Object obj) { public ObjectMessage(Object obj) {
if (obj == null) { if (obj == null)
obj = "null"; obj = "null";
}
this.obj = obj; this.obj = obj;
} }
@@ -41,17 +40,15 @@ public class ObjectMessage
@Override @Override
public Object[] getParameters() { public Object[] getParameters() {
return new Object[]{this.obj}; return new Object[] {this.obj};
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o)
return true; return true;
} if ((o == null) || (getClass() != o.getClass()))
if ((o == null) || (getClass() != o.getClass())) {
return false; return false;
}
ObjectMessage that = (ObjectMessage) o; ObjectMessage that = (ObjectMessage) o;

View File

@@ -30,7 +30,7 @@ import java.util.Set;
* @author huangyuhui * @author huangyuhui
*/ */
public class ParameterizedMessage public class ParameterizedMessage
implements IMessage { implements IMessage {
public static final String RECURSION_PREFIX = "[..."; public static final String RECURSION_PREFIX = "[...";
public static final String RECURSION_SUFFIX = "...]"; public static final String RECURSION_SUFFIX = "...]";
@@ -67,21 +67,20 @@ public class ParameterizedMessage
} }
public ParameterizedMessage(String messagePattern, Object arg) { public ParameterizedMessage(String messagePattern, Object arg) {
this(messagePattern, new Object[]{arg}); this(messagePattern, new Object[] {arg});
} }
public ParameterizedMessage(String messagePattern, Object arg1, Object arg2) { public ParameterizedMessage(String messagePattern, Object arg1, Object arg2) {
this(messagePattern, new Object[]{arg1, arg2}); this(messagePattern, new Object[] {arg1, arg2});
} }
private String[] parseArguments(Object[] arguments) { private String[] parseArguments(Object[] arguments) {
if (arguments == null) { if (arguments == null)
return null; return null;
}
int argsCount = countArgumentPlaceholders(this.messagePattern); int argsCount = countArgumentPlaceholders(this.messagePattern);
int resultArgCount = arguments.length; int resultArgCount = arguments.length;
if ((argsCount < arguments.length) if ((argsCount < arguments.length)
&& (this.throwable == null) && ((arguments[(arguments.length - 1)] instanceof Throwable))) { && (this.throwable == null) && ((arguments[(arguments.length - 1)] instanceof Throwable))) {
this.throwable = ((Throwable) arguments[(arguments.length - 1)]); this.throwable = ((Throwable) arguments[(arguments.length - 1)]);
resultArgCount--; resultArgCount--;
} }
@@ -94,18 +93,16 @@ public class ParameterizedMessage
strArgs[0] = deepToString(arguments); strArgs[0] = deepToString(arguments);
} else { } else {
strArgs = new String[resultArgCount]; strArgs = new String[resultArgCount];
for (int i = 0; i < strArgs.length; i++) { for (int i = 0; i < strArgs.length; i++)
strArgs[i] = deepToString(arguments[i]); strArgs[i] = deepToString(arguments[i]);
}
} }
return strArgs; return strArgs;
} }
@Override @Override
public String getFormattedMessage() { public String getFormattedMessage() {
if (this.formattedMessage == null) { if (this.formattedMessage == null)
this.formattedMessage = formatMessage(this.messagePattern, this.stringArgs); this.formattedMessage = formatMessage(this.messagePattern, this.stringArgs);
}
return this.formattedMessage; return this.formattedMessage;
} }
@@ -116,9 +113,8 @@ public class ParameterizedMessage
@Override @Override
public Object[] getParameters() { public Object[] getParameters() {
if (this.argArray != null) { if (this.argArray != null)
return this.argArray; return this.argArray;
}
return this.stringArgs; return this.stringArgs;
} }
@@ -133,8 +129,10 @@ public class ParameterizedMessage
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
ParameterizedMessage that = (ParameterizedMessage) o; ParameterizedMessage that = (ParameterizedMessage) o;
if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null) if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null)
@@ -159,11 +157,11 @@ public class ParameterizedMessage
int currentArgument = 0; int currentArgument = 0;
for (int i = 0; i < messagePattern.length(); i++) { for (int i = 0; i < messagePattern.length(); i++) {
char curChar = messagePattern.charAt(i); char curChar = messagePattern.charAt(i);
if (curChar == ESCAPE_CHAR) { if (curChar == ESCAPE_CHAR)
escapeCounter++; escapeCounter++;
} else if ((curChar == DELIM_START) else if ((curChar == DELIM_START)
&& (i < messagePattern.length() - 1) && (i < messagePattern.length() - 1)
&& (messagePattern.charAt(i + 1) == DELIM_STOP)) { && (messagePattern.charAt(i + 1) == DELIM_STOP)) {
int escapedEscapes = escapeCounter / 2; int escapedEscapes = escapeCounter / 2;
for (int j = 0; j < escapedEscapes; j++) for (int j = 0; j < escapedEscapes; j++)
result.append(ESCAPE_CHAR); result.append(ESCAPE_CHAR);
@@ -193,36 +191,39 @@ public class ParameterizedMessage
} }
public static int countArgumentPlaceholders(String messagePattern) { public static int countArgumentPlaceholders(String messagePattern) {
if (messagePattern == null) return 0; if (messagePattern == null)
return 0;
int delim = messagePattern.indexOf(123); int delim = messagePattern.indexOf(123);
if (delim == -1) return 0; if (delim == -1)
return 0;
int result = 0; int result = 0;
boolean isEscaped = false; boolean isEscaped = false;
for (int i = 0; i < messagePattern.length(); i++) { for (int i = 0; i < messagePattern.length(); i++) {
char curChar = messagePattern.charAt(i); char curChar = messagePattern.charAt(i);
if (curChar == ESCAPE_CHAR) { if (curChar == ESCAPE_CHAR)
isEscaped = !isEscaped; isEscaped = !isEscaped;
} else if (curChar == DELIM_START) { else if (curChar == DELIM_START) {
if ((!isEscaped) if ((!isEscaped)
&& (i < messagePattern.length() - 1) && (i < messagePattern.length() - 1)
&& (messagePattern.charAt(i + 1) == DELIM_STOP)) { && (messagePattern.charAt(i + 1) == DELIM_STOP)) {
result++; result++;
i++; i++;
} }
isEscaped = false; isEscaped = false;
} else { } else
isEscaped = false; isEscaped = false;
}
} }
return result; return result;
} }
public static String deepToString(Object o) { public static String deepToString(Object o) {
if (o == null) return null; if (o == null)
if (o instanceof String) return (String) o; return null;
if (o instanceof String)
return (String) o;
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
Set dejaVu = new HashSet(); Set dejaVu = new HashSet();
recursiveDeepToString(o, str, dejaVu); recursiveDeepToString(o, str, dejaVu);
@@ -239,53 +240,57 @@ public class ParameterizedMessage
return; return;
} }
Class oClass = o.getClass(); Class oClass = o.getClass();
if (oClass.isArray()) { if (oClass.isArray())
if (oClass == byte[].class) { if (oClass == byte[].class)
str.append(Arrays.toString((byte[]) (byte[]) o)); str.append(Arrays.toString((byte[]) (byte[]) o));
} else if (oClass == short[].class) { else if (oClass == short[].class)
str.append(Arrays.toString((short[]) (short[]) o)); str.append(Arrays.toString((short[]) (short[]) o));
} else if (oClass == int[].class) { else if (oClass == int[].class)
str.append(Arrays.toString((int[]) (int[]) o)); str.append(Arrays.toString((int[]) (int[]) o));
} else if (oClass == long[].class) { else if (oClass == long[].class)
str.append(Arrays.toString((long[]) (long[]) o)); str.append(Arrays.toString((long[]) (long[]) o));
} else if (oClass == float[].class) { else if (oClass == float[].class)
str.append(Arrays.toString((float[]) (float[]) o)); str.append(Arrays.toString((float[]) (float[]) o));
} else if (oClass == double[].class) { else if (oClass == double[].class)
str.append(Arrays.toString((double[]) (double[]) o)); str.append(Arrays.toString((double[]) (double[]) o));
} else if (oClass == boolean[].class) { else if (oClass == boolean[].class)
str.append(Arrays.toString((boolean[]) (boolean[]) o)); str.append(Arrays.toString((boolean[]) (boolean[]) o));
} else if (oClass == char[].class) { else if (oClass == char[].class)
str.append(Arrays.toString((char[]) (char[]) o)); str.append(Arrays.toString((char[]) (char[]) o));
} else { else {
String id = identityToString(o); String id = identityToString(o);
if (dejaVu.contains(id)) { if (dejaVu.contains(id))
str.append("[...").append(id).append("...]"); str.append("[...").append(id).append("...]");
} else { else {
dejaVu.add(id); dejaVu.add(id);
Object[] oArray = (Object[]) (Object[]) o; Object[] oArray = (Object[]) (Object[]) o;
str.append("["); str.append("[");
boolean first = true; boolean first = true;
for (Object current : oArray) { for (Object current : oArray) {
if (first) first = false; if (first)
else str.append(", "); first = false;
else
str.append(", ");
recursiveDeepToString(current, str, new HashSet(dejaVu)); recursiveDeepToString(current, str, new HashSet(dejaVu));
} }
str.append("]"); str.append("]");
} }
} }
} else if ((o instanceof Map)) { else if ((o instanceof Map)) {
String id = identityToString(o); String id = identityToString(o);
if (dejaVu.contains(id)) { if (dejaVu.contains(id))
str.append("[...").append(id).append("...]"); str.append("[...").append(id).append("...]");
} else { else {
dejaVu.add(id); dejaVu.add(id);
Map oMap = (Map) o; Map oMap = (Map) o;
str.append("{"); str.append("{");
boolean isFirst = true; boolean isFirst = true;
for (Object o1 : oMap.entrySet()) { for (Object o1 : oMap.entrySet()) {
Map.Entry current = (Map.Entry) o1; Map.Entry current = (Map.Entry) o1;
if (isFirst) isFirst = false; if (isFirst)
else str.append(", "); isFirst = false;
else
str.append(", ");
Object key = current.getKey(); Object key = current.getKey();
Object value = current.getValue(); Object value = current.getValue();
recursiveDeepToString(key, str, new HashSet(dejaVu)); recursiveDeepToString(key, str, new HashSet(dejaVu));
@@ -296,17 +301,19 @@ public class ParameterizedMessage
} }
} else if ((o instanceof Collection)) { } else if ((o instanceof Collection)) {
String id = identityToString(o); String id = identityToString(o);
if (dejaVu.contains(id)) { if (dejaVu.contains(id))
str.append("[...").append(id).append("...]"); str.append("[...").append(id).append("...]");
} else { else {
dejaVu.add(id); dejaVu.add(id);
Collection oCol = (Collection) o; Collection oCol = (Collection) o;
str.append("["); str.append("[");
boolean isFirst = true; boolean isFirst = true;
for (Iterator i$ = oCol.iterator(); i$.hasNext();) { for (Iterator i$ = oCol.iterator(); i$.hasNext();) {
Object anOCol = i$.next(); Object anOCol = i$.next();
if (isFirst) isFirst = false; if (isFirst)
else str.append(", "); isFirst = false;
else
str.append(", ");
recursiveDeepToString(anOCol, str, new HashSet(dejaVu)); recursiveDeepToString(anOCol, str, new HashSet(dejaVu));
} }
str.append("]"); str.append("]");
@@ -316,7 +323,7 @@ public class ParameterizedMessage
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
str.append(format.format(date)); str.append(format.format(date));
} else { } else
try { try {
str.append(o.toString()); str.append(o.toString());
} catch (Throwable t) { } catch (Throwable t) {
@@ -332,16 +339,16 @@ public class ParameterizedMessage
} }
str.append("!!!]"); str.append("!!!]");
} }
}
} }
public static String identityToString(Object obj) { public static String identityToString(Object obj) {
if (obj == null) return null; if (obj == null)
return obj.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(obj)); return null;
return obj.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(obj));
} }
@Override @Override
public String toString() { public String toString() {
return "ParameterizedMessage[messagePattern="+this.messagePattern+", stringArgs="+Arrays.toString(this.stringArgs)+", throwable="+this.throwable+"]"; return "ParameterizedMessage[messagePattern=" + this.messagePattern + ", stringArgs=" + Arrays.toString(this.stringArgs) + ", throwable=" + this.throwable + "]";
} }
} }

View File

@@ -26,6 +26,6 @@ public final class ParameterizedMessageFactory extends AbstractMessageFactory {
@Override @Override
public IMessage newMessage(String message, Object[] params) { public IMessage newMessage(String message, Object[] params) {
return new ParameterizedMessage(message, params); return new ParameterizedMessage(message, params);
} }
} }

View File

@@ -21,60 +21,58 @@ package org.jackhuang.hellominecraft.logging.message;
* @author huangyuhui * @author huangyuhui
*/ */
public class SimpleMessage public class SimpleMessage
implements IMessage { implements IMessage {
private static final long serialVersionUID = -8398002534962715992L; private static final long serialVersionUID = -8398002534962715992L;
private final String message; private final String message;
public SimpleMessage() { public SimpleMessage() {
this(null); this(null);
} }
public SimpleMessage(String message) { public SimpleMessage(String message) {
this.message = message; this.message = message;
} }
@Override @Override
public String getFormattedMessage() { public String getFormattedMessage() {
return this.message; return this.message;
} }
@Override @Override
public String getFormat() { public String getFormat() {
return this.message; return this.message;
} }
@Override @Override
public Object[] getParameters() { public Object[] getParameters() {
return null; return null;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o)
return true; return true;
} if ((o == null) || (getClass() != o.getClass()))
if ((o == null) || (getClass() != o.getClass())) { return false;
return false;
}
SimpleMessage that = (SimpleMessage) o; SimpleMessage that = (SimpleMessage) o;
return this.message != null ? this.message.equals(that.message) : that.message == null; return this.message != null ? this.message.equals(that.message) : that.message == null;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return this.message != null ? this.message.hashCode() : 0; return this.message != null ? this.message.hashCode() : 0;
} }
@Override @Override
public String toString() { public String toString() {
return "SimpleMessage[message=" + this.message + "]"; return "SimpleMessage[message=" + this.message + "]";
} }
@Override @Override
public Throwable getThrowable() { public Throwable getThrowable() {
return null; return null;
} }
} }

View File

@@ -20,7 +20,7 @@ import java.util.Arrays;
import java.util.IllegalFormatException; import java.util.IllegalFormatException;
public class StringFormattedMessage public class StringFormattedMessage
implements IMessage { implements IMessage {
private static final long serialVersionUID = -665975803997290697L; private static final long serialVersionUID = -665975803997290697L;
private final String messagePattern; private final String messagePattern;
@@ -30,76 +30,70 @@ public class StringFormattedMessage
private transient Throwable throwable; private transient Throwable throwable;
public StringFormattedMessage(String messagePattern, Object[] arguments) { public StringFormattedMessage(String messagePattern, Object[] arguments) {
this.messagePattern = messagePattern; this.messagePattern = messagePattern;
this.argArray = arguments; this.argArray = arguments;
if ((arguments != null) && (arguments.length > 0) && ((arguments[(arguments.length - 1)] instanceof Throwable))) { if ((arguments != null) && (arguments.length > 0) && ((arguments[(arguments.length - 1)] instanceof Throwable)))
this.throwable = ((Throwable) arguments[(arguments.length - 1)]); this.throwable = ((Throwable) arguments[(arguments.length - 1)]);
}
} }
@Override @Override
public String getFormattedMessage() { public String getFormattedMessage() {
if (this.formattedMessage == null) { if (this.formattedMessage == null)
this.formattedMessage = formatMessage(this.messagePattern, this.argArray); this.formattedMessage = formatMessage(this.messagePattern, this.argArray);
} return this.formattedMessage;
return this.formattedMessage;
} }
@Override @Override
public String getFormat() { public String getFormat() {
return this.messagePattern; return this.messagePattern;
} }
@Override @Override
public Object[] getParameters() { public Object[] getParameters() {
if (this.argArray != null) { if (this.argArray != null)
return this.argArray; return this.argArray;
} return this.stringArgs;
return this.stringArgs;
} }
protected String formatMessage(String msgPattern, Object[] args) { protected String formatMessage(String msgPattern, Object[] args) {
try { try {
return String.format(msgPattern, args); return String.format(msgPattern, args);
} catch (IllegalFormatException ife) { } catch (IllegalFormatException ife) {
System.err.println("Unable to format msg: " + msgPattern); System.err.println("Unable to format msg: " + msgPattern);
ife.printStackTrace(); ife.printStackTrace();
} }
return msgPattern; return msgPattern;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o)
return true; return true;
} if ((o == null) || (getClass() != o.getClass()))
if ((o == null) || (getClass() != o.getClass())) { return false;
return false;
}
StringFormattedMessage that = (StringFormattedMessage) o; StringFormattedMessage that = (StringFormattedMessage) o;
if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null) { if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null)
return false; return false;
}
return Arrays.equals(this.stringArgs, that.stringArgs); return Arrays.equals(this.stringArgs, that.stringArgs);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = this.messagePattern != null ? this.messagePattern.hashCode() : 0; int result = this.messagePattern != null ? this.messagePattern.hashCode() : 0;
result = 31 * result + (this.stringArgs != null ? Arrays.hashCode(this.stringArgs) : 0); result = 31 * result + (this.stringArgs != null ? Arrays.hashCode(this.stringArgs) : 0);
return result; return result;
} }
@Override @Override
public String toString() { public String toString() {
return "StringFormatMessage[messagePattern=" + this.messagePattern + ", args=" + Arrays.toString(this.argArray) + "]"; return "StringFormatMessage[messagePattern=" + this.messagePattern + ", args=" + Arrays.toString(this.argArray) + "]";
} }
@Override @Override
public Throwable getThrowable() { public Throwable getThrowable() {
return this.throwable; return this.throwable;
} }
} }

View File

@@ -98,7 +98,8 @@ public class TaskList extends Thread {
} }
while (!runningThread.isEmpty()) while (!runningThread.isEmpty())
try { try {
if (this.isInterrupted()) return; if (this.isInterrupted())
return;
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException ignore) { } catch (InterruptedException ignore) {
} }
@@ -119,7 +120,7 @@ public class TaskList extends Thread {
boolean returns = false; boolean returns = false;
try { try {
returns = t.executeTask(); returns = t.executeTask();
} catch(Throwable e) { } catch (Throwable e) {
t.setFailReason(e); t.setFailReason(e);
} }
if (returns) { if (returns) {
@@ -144,7 +145,7 @@ public class TaskList extends Thread {
threadPool.clear(); threadPool.clear();
totTask = taskQueue.size(); totTask = taskQueue.size();
while(!taskQueue.isEmpty()) while (!taskQueue.isEmpty())
executeTask(taskQueue.remove(0)); executeTask(taskQueue.remove(0));
if (shouldContinue) if (shouldContinue)
for (Runnable d : allDone) for (Runnable d : allDone)
@@ -160,7 +161,8 @@ public class TaskList extends Thread {
while (!threadPool.isEmpty()) while (!threadPool.isEmpty())
synchronized (threadPool) { synchronized (threadPool) {
InvokeThread it = threadPool.iterator().next(); InvokeThread it = threadPool.iterator().next();
if (!it.task.abort()) it.interrupt(); if (!it.task.abort())
it.interrupt();
threadPool.remove(it); threadPool.remove(it);
} }
this.interrupt(); this.interrupt();

View File

@@ -27,7 +27,9 @@ import org.jackhuang.hellominecraft.utils.functions.Consumer;
* @param <T> Runnable&lt;T&gt; * @param <T> Runnable&lt;T&gt;
*/ */
public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegistrar<T> { public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegistrar<T> {
private final Consumer<T> r; private final Consumer<T> r;
public TaskRunnableArg1(String info, Consumer<T> r) { public TaskRunnableArg1(String info, Consumer<T> r) {
super(info); super(info);
this.r = r; this.r = r;
@@ -35,11 +37,12 @@ public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegis
@Override @Override
public boolean executeTask() { public boolean executeTask() {
if(al.size() != 1) throw new IllegalStateException("the count of args is not one."); if (al.size() != 1)
throw new IllegalStateException("the count of args is not one.");
try { try {
r.accept(al.get(0).getResult()); r.accept(al.get(0).getResult());
return true; return true;
} catch(Throwable t) { } catch (Throwable t) {
setFailReason(t); setFailReason(t);
return false; return false;
} }
@@ -53,6 +56,4 @@ public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegis
return this; return this;
} }
} }

View File

@@ -30,7 +30,7 @@ import org.jackhuang.hellominecraft.utils.SwingUtils;
* @author huangyuhui * @author huangyuhui
*/ */
public class TaskWindow extends javax.swing.JDialog public class TaskWindow extends javax.swing.JDialog
implements ProgressProviderListener, Runnable, DoingDoneListener<Task> { implements ProgressProviderListener, Runnable, DoingDoneListener<Task> {
private static final TaskWindow instance = new TaskWindow(); private static final TaskWindow instance = new TaskWindow();
@@ -72,14 +72,16 @@ public class TaskWindow extends javax.swing.JDialog
} }
public synchronized void clean() { public synchronized void clean() {
if (isVisible()) return; if (isVisible())
return;
taskList = new TaskList(); taskList = new TaskList();
taskList.addTaskListener(this); taskList.addTaskListener(this);
taskList.addAllDoneListener(this); taskList.addAllDoneListener(this);
} }
public boolean start() { public boolean start() {
if (isVisible() || taskList == null || taskList.isAlive()) return false; if (isVisible() || taskList == null || taskList.isAlive())
return false;
pgsTotal.setValue(0); pgsTotal.setValue(0);
suc = false; suc = false;
SwingUtils.clearDefaultTable(lstDownload); SwingUtils.clearDefaultTable(lstDownload);
@@ -169,7 +171,8 @@ public class TaskWindow extends javax.swing.JDialog
}//GEN-LAST:event_btnCancelActionPerformed }//GEN-LAST:event_btnCancelActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
if(taskList == null) return; if (taskList == null)
return;
tasks.clear(); tasks.clear();
if (!this.failReasons.isEmpty()) { if (!this.failReasons.isEmpty()) {
@@ -203,7 +206,8 @@ public class TaskWindow extends javax.swing.JDialog
public void setProgress(Task task, int progress, int max) { public void setProgress(Task task, int progress, int max) {
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
int idx = tasks.indexOf(task); int idx = tasks.indexOf(task);
if (idx == -1) return; if (idx == -1)
return;
int pgs = progress * 100 / max; int pgs = progress * 100 / max;
if (progresses.contains(idx) && progresses.get(idx) != pgs && lstDownload.getRowCount() > idx) { if (progresses.contains(idx) && progresses.get(idx) != pgs && lstDownload.getRowCount() > idx) {
SwingUtils.setValueAt(lstDownload, pgs + "%", idx, 1); SwingUtils.setValueAt(lstDownload, pgs + "%", idx, 1);
@@ -224,7 +228,8 @@ public class TaskWindow extends javax.swing.JDialog
task.setProgressProviderListener(this); task.setProgressProviderListener(this);
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
if(taskList == null) return; if (taskList == null)
return;
tasks.add(task); tasks.add(task);
progresses.add(0); progresses.add(0);
SwingUtils.appendLast(lstDownload, task.getInfo(), "0%"); SwingUtils.appendLast(lstDownload, task.getInfo(), "0%");
@@ -239,11 +244,13 @@ public class TaskWindow extends javax.swing.JDialog
@Override @Override
public void onDone(Task task) { public void onDone(Task task) {
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
if(taskList == null) return; if (taskList == null)
return;
pgsTotal.setMaximum(taskList.taskCount()); pgsTotal.setMaximum(taskList.taskCount());
pgsTotal.setValue(pgsTotal.getValue() + 1); pgsTotal.setValue(pgsTotal.getValue() + 1);
int idx = tasks.indexOf(task); int idx = tasks.indexOf(task);
if (idx == -1) return; if (idx == -1)
return;
tasks.remove(idx); tasks.remove(idx);
progresses.remove(idx); progresses.remove(idx);
SwingUtils.removeRow(lstDownload, idx); SwingUtils.removeRow(lstDownload, idx);
@@ -253,12 +260,14 @@ public class TaskWindow extends javax.swing.JDialog
@Override @Override
public void onFailed(Task task) { public void onFailed(Task task) {
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
if(taskList == null) return; if (taskList == null)
return;
failReasons.add(task.getInfo() + ": " + (null == task.getFailReason() ? "No exception" : (StrUtils.isBlank(task.getFailReason().getLocalizedMessage()) ? task.getFailReason().getClass().getSimpleName() : task.getFailReason().getLocalizedMessage()))); failReasons.add(task.getInfo() + ": " + (null == task.getFailReason() ? "No exception" : (StrUtils.isBlank(task.getFailReason().getLocalizedMessage()) ? task.getFailReason().getClass().getSimpleName() : task.getFailReason().getLocalizedMessage())));
pgsTotal.setMaximum(taskList.taskCount()); pgsTotal.setMaximum(taskList.taskCount());
pgsTotal.setValue(pgsTotal.getValue() + 1); pgsTotal.setValue(pgsTotal.getValue() + 1);
int idx = tasks.indexOf(task); int idx = tasks.indexOf(task);
if (idx == -1) return; if (idx == -1)
return;
SwingUtils.setValueAt(lstDownload, task.getFailReason(), idx, 0); SwingUtils.setValueAt(lstDownload, task.getFailReason(), idx, 0);
SwingUtils.setValueAt(lstDownload, "0%", idx, 1); SwingUtils.setValueAt(lstDownload, "0%", idx, 1);
SwingUtils.moveEnd(srlDownload); SwingUtils.moveEnd(srlDownload);
@@ -273,14 +282,17 @@ public class TaskWindow extends javax.swing.JDialog
@Override @Override
public void setStatus(Task task, String sta) { public void setStatus(Task task, String sta) {
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
if(taskList == null) return; if (taskList == null)
return;
int idx = tasks.indexOf(task); int idx = tasks.indexOf(task);
if (idx == -1) return; if (idx == -1)
return;
SwingUtils.setValueAt(lstDownload, task.getInfo() + ": " + sta, idx, 0); SwingUtils.setValueAt(lstDownload, task.getInfo() + ": " + sta, idx, 0);
}); });
} }
public static class TaskWindowFactory { public static class TaskWindowFactory {
LinkedList<Task> ll = new LinkedList<>(); LinkedList<Task> ll = new LinkedList<>();
public TaskWindowFactory addTask(Task t) { public TaskWindowFactory addTask(Task t) {
@@ -289,10 +301,12 @@ public class TaskWindow extends javax.swing.JDialog
} }
public boolean start() { public boolean start() {
synchronized(instance) { synchronized (instance) {
if (instance.isVisible()) return false; if (instance.isVisible())
return false;
TaskWindow tw = inst(); TaskWindow tw = inst();
for(Task t : ll) tw.addTask(t); for (Task t : ll)
tw.addTask(t);
return tw.start(); return tw.start();
} }
} }

View File

@@ -28,6 +28,7 @@ public interface PreviousResultRegistrar<T> {
/** /**
* *
* @param pr previous task handler * @param pr previous task handler
*
* @return task self instance * @return task self instance
*/ */
Task registerPreviousResult(PreviousResult<T> pr); Task registerPreviousResult(PreviousResult<T> pr);

View File

@@ -25,5 +25,6 @@ import org.jackhuang.hellominecraft.tasks.ProgressProviderListener;
public interface DownloadListener extends ProgressProviderListener { public interface DownloadListener extends ProgressProviderListener {
boolean OnFailed(); boolean OnFailed();
void OnFailedMoreThan5Times(String url); void OnFailedMoreThan5Times(String url);
} }

View File

@@ -103,7 +103,7 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
// Open connection to URL. // Open connection to URL.
HttpURLConnection connection HttpURLConnection connection
= (HttpURLConnection) url.openConnection(); = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000); connection.setConnectTimeout(5000);
connection.setRequestProperty("User-Agent", "Hello Minecraft! Launcher"); connection.setRequestProperty("User-Agent", "Hello Minecraft! Launcher");
@@ -167,7 +167,8 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
if (aborted) if (aborted)
tempFile.delete(); tempFile.delete();
else { else {
if (filePath.exists()) filePath.delete(); if (filePath.exists())
filePath.delete();
tempFile.renameTo(filePath); tempFile.renameTo(filePath);
} }
if (ppl != null) if (ppl != null)

View File

@@ -52,7 +52,8 @@ public class HTTPGetTask extends TaskInfo implements PreviousResult<String> {
@Override @Override
public boolean executeTask() { public boolean executeTask() {
for (int repeat = 0; repeat < 6; repeat++) { for (int repeat = 0; repeat < 6; repeat++) {
if (repeat > 0) HMCLog.warn("Failed to download, repeat: " + repeat); if (repeat > 0)
HMCLog.warn("Failed to download, repeat: " + repeat);
try { try {
URLConnection conn = new URL(url).openConnection(); URLConnection conn = new URL(url).openConnection();
InputStream is = conn.getInputStream(); InputStream is = conn.getInputStream();
@@ -61,12 +62,10 @@ public class HTTPGetTask extends TaskInfo implements PreviousResult<String> {
int size = conn.getContentLength(), read = 0; int size = conn.getContentLength(), read = 0;
while ((i = is.read()) != -1) { while ((i = is.read()) != -1) {
baos.write(i); baos.write(i);
if (ppl != null) { if (ppl != null)
ppl.setProgress(this, ++read, size); ppl.setProgress(this, ++read, size);
} if (!shouldContinue)
if (!shouldContinue) {
return true; return true;
}
} }
result = baos.toString(); result = baos.toString();
tdtsl.execute(result); tdtsl.execute(result);

View File

@@ -78,8 +78,10 @@ public class ArrayUtils {
} }
public static <K> K getEnd(K[] k) { public static <K> K getEnd(K[] k) {
if (k == null) return null; if (k == null)
else return k[k.length - 1]; return null;
else
return k[k.length - 1];
} }
public static List tryGetMapWithList(Map map, String key) { public static List tryGetMapWithList(Map map, String key) {

View File

@@ -29,14 +29,16 @@ import java.util.Iterator;
public final class CollectionUtils { public final class CollectionUtils {
public static <T> void forEach(Collection<T> coll, Consumer<T> p) { public static <T> void forEach(Collection<T> coll, Consumer<T> p) {
for (T t : coll) p.accept(t); for (T t : coll)
p.accept(t);
} }
public static <T> Collection<T> sortOut(Collection<T> coll, Predicate<T> p) { public static <T> Collection<T> sortOut(Collection<T> coll, Predicate<T> p) {
ArrayList<T> newColl = new ArrayList<>(); ArrayList<T> newColl = new ArrayList<>();
forEach(coll, t -> { forEach(coll, t -> {
if (p.apply(t)) newColl.add(t); if (p.apply(t))
}); newColl.add(t);
});
return newColl; return newColl;
} }

View File

@@ -44,7 +44,8 @@ public class EventHandler<T> {
public boolean execute(T x) { public boolean execute(T x) {
boolean flag = true; boolean flag = true;
for (Event<T> t : handlers) for (Event<T> t : handlers)
if (!t.call(sender, x)) flag = false; if (!t.call(sender, x))
flag = false;
return flag; return flag;
} }

View File

@@ -84,7 +84,7 @@ public class LogWindowOutputStream extends OutputStream {
@Override @Override
public final void write(int paramInt) { public final void write(int paramInt) {
append(new String(new byte[]{(byte) paramInt})); append(new String(new byte[] {(byte) paramInt}));
} }
public static void dispose() { public static void dispose() {

View File

@@ -44,9 +44,12 @@ public class MathUtils {
return Integer.parseInt(s); return Integer.parseInt(s);
} catch (Exception e) { } catch (Exception e) {
int a = parseInt(s.substring(0, s.length() - 1), def); int a = parseInt(s.substring(0, s.length() - 1), def);
if (s.endsWith("g")) return a * 1024; if (s.endsWith("g"))
else if (s.endsWith("k")) return a / 1024; return a * 1024;
else return a; else if (s.endsWith("k"))
return a / 1024;
else
return a;
} }
} }

View File

@@ -52,7 +52,7 @@ public final class NetUtils {
} }
public static String getStreamContent(InputStream is, String encoding) public static String getStreamContent(InputStream is, String encoding)
throws IOException { throws IOException {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
try (InputStreamReader br = new InputStreamReader(is, encoding)) { try (InputStreamReader br = new InputStreamReader(is, encoding)) {
int len; int len;
@@ -82,15 +82,16 @@ public final class NetUtils {
/** /**
* Sends an HTTP GET request to a url * Sends an HTTP GET request to a url
* *
* @param endpoint - The URL of the server. (Example: " * @param endpoint - The URL of the server. (Example: "
* http://www.yahoo.com/search") * http://www.yahoo.com/search")
* @param requestParameters - all the request parameters (Example: * @param requestParameters - all the request parameters (Example:
* "param1=val1&param2=val2"). Note: This method will add the question mark * "param1=val1&param2=val2"). Note: This method will add the question mark
* (?) to the request - DO NOT add it yourself * (?) to the request - DO NOT add it yourself
*
* @return - The response from the end point * @return - The response from the end point
*/ */
public static String sendGetRequest(String endpoint, public static String sendGetRequest(String endpoint,
String requestParameters) { String requestParameters) {
String result = null; String result = null;
if (endpoint.startsWith("http://")) if (endpoint.startsWith("http://"))
// Send a GET request to the servlet // Send a GET request to the servlet
@@ -157,7 +158,8 @@ public final class NetUtils {
os = con.getOutputStream(); os = con.getOutputStream();
IOUtils.write(post, os, DEFAULT_CHARSET); IOUtils.write(post, os, DEFAULT_CHARSET);
} finally { } finally {
if (os != null) IOUtils.closeQuietly(os); if (os != null)
IOUtils.closeQuietly(os);
} }
String result = null; String result = null;
@@ -165,8 +167,9 @@ public final class NetUtils {
try { try {
is = con.getInputStream(); is = con.getInputStream();
result = getStreamContent(is); result = getStreamContent(is);
} catch(IOException ex) { } catch (IOException ex) {
if (is != null) IOUtils.closeQuietly(is); if (is != null)
IOUtils.closeQuietly(is);
is = con.getErrorStream(); is = con.getErrorStream();
result = getStreamContent(is); result = getStreamContent(is);
} }

View File

@@ -34,37 +34,32 @@ public final class StrUtils {
public static String substring(String src, int start_idx, int end_idx) { public static String substring(String src, int start_idx, int end_idx) {
byte[] b = src.getBytes(); byte[] b = src.getBytes();
String tgt = ""; String tgt = "";
for (int i = start_idx; i <= end_idx; i++) { for (int i = start_idx; i <= end_idx; i++)
tgt += (char) b[i]; tgt += (char) b[i];
}
return tgt; return tgt;
} }
public static String makeCommand(List<String> cmd) { public static String makeCommand(List<String> cmd) {
StringBuilder cmdbuf = new StringBuilder(120); StringBuilder cmdbuf = new StringBuilder(120);
for (int i = 0; i < cmd.size(); i++) { for (int i = 0; i < cmd.size(); i++) {
if (i > 0) { if (i > 0)
cmdbuf.append(' '); cmdbuf.append(' ');
}
String s = cmd.get(i); String s = cmd.get(i);
if (s.indexOf(' ') >= 0 || s.indexOf('\t') >= 0) { if (s.indexOf(' ') >= 0 || s.indexOf('\t') >= 0)
if (s.charAt(0) != '"') { if (s.charAt(0) != '"') {
cmdbuf.append('"'); cmdbuf.append('"');
cmdbuf.append(s); cmdbuf.append(s);
if (s.endsWith("\\")) { if (s.endsWith("\\"))
cmdbuf.append("\\"); cmdbuf.append("\\");
}
cmdbuf.append('"'); cmdbuf.append('"');
} else if (s.endsWith("\"")) { } else if (s.endsWith("\""))
/* The argument has already been quoted. */ /* The argument has already been quoted. */
cmdbuf.append(s); cmdbuf.append(s);
} else { else
/* Unmatched quote for the argument. */ /* Unmatched quote for the argument. */
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} else
} else {
cmdbuf.append(s); cmdbuf.append(s);
}
} }
String str = cmdbuf.toString(); String str = cmdbuf.toString();
@@ -76,61 +71,49 @@ public final class StrUtils {
} }
public static boolean startsWithOne(String[] a, String match) { public static boolean startsWithOne(String[] a, String match) {
if (a == null) { if (a == null)
return false; return false;
} for (String b : a)
for (String b : a) { if (startsWith(match, b))
if (startsWith(match, b)) {
return true; return true;
}
}
return false; return false;
} }
public static boolean equalsOne(String base, String... a) { public static boolean equalsOne(String base, String... a) {
for (String s : a) { for (String s : a)
if (base.equals(s)) { if (base.equals(s))
return true; return true;
}
}
return false; return false;
} }
public static boolean containsOne(List<String> base, List<String> match) { public static boolean containsOne(List<String> base, List<String> match) {
for (String a : base) { for (String a : base)
for (String b : match) { for (String b : match)
if (a.toLowerCase().contains(b.toLowerCase())) { if (a.toLowerCase().contains(b.toLowerCase()))
return true; return true;
}
}
}
return false; return false;
} }
public static int getCharShowTime(String s, char c) { public static int getCharShowTime(String s, char c) {
int res = 0; int res = 0;
for (int i = 0; i < s.length(); i++) { for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == c) { if (s.charAt(i) == c)
res++; res++;
}
}
return res; return res;
} }
public static String formatVersion(String ver) { public static String formatVersion(String ver) {
if (isBlank(ver)) { if (isBlank(ver))
return null; return null;
} else { else
for(char ch : ver.toCharArray()) { for (char ch : ver.toCharArray())
if((ch < '0' || ch > '9') && ch != '.') return null; if ((ch < '0' || ch > '9') && ch != '.')
} return null;
}
int i = getCharShowTime(ver, '.'); int i = getCharShowTime(ver, '.');
if (i == 1) { if (i == 1)
return ver + ".0"; return ver + ".0";
} else { else
return ver; return ver;
}
} }
public static String parseParams(String addBefore, Collection paramArrayOfObject, String paramString) { public static String parseParams(String addBefore, Collection paramArrayOfObject, String paramString) {
@@ -138,57 +121,49 @@ public final class StrUtils {
} }
public static String parseParams(String addBefore, Object[] paramArrayOfObject, String paramString) { public static String parseParams(String addBefore, Object[] paramArrayOfObject, String paramString) {
if (paramArrayOfObject == null) { if (paramArrayOfObject == null)
return ""; return "";
}
StringBuilder localStringBuffer = new StringBuilder(); StringBuilder localStringBuffer = new StringBuilder();
for (int i = 0; i < paramArrayOfObject.length; i++) { for (int i = 0; i < paramArrayOfObject.length; i++) {
Object localObject = paramArrayOfObject[i]; Object localObject = paramArrayOfObject[i];
if (i > 0) { if (i > 0)
localStringBuffer.append(addBefore).append(paramString); localStringBuffer.append(addBefore).append(paramString);
} if (localObject == null)
if (localObject == null) {
localStringBuffer.append("null"); localStringBuffer.append("null");
} else if (localObject.getClass().isArray()) { else if (localObject.getClass().isArray()) {
localStringBuffer.append("["); localStringBuffer.append("[");
if ((localObject instanceof Object[])) { if ((localObject instanceof Object[])) {
Object[] arrayOfObject = (Object[]) localObject; Object[] arrayOfObject = (Object[]) localObject;
localStringBuffer.append(parseParams(addBefore, arrayOfObject, paramString)); localStringBuffer.append(parseParams(addBefore, arrayOfObject, paramString));
} else { } else
for (int j = 0; j < Array.getLength(localObject); j++) { for (int j = 0; j < Array.getLength(localObject); j++) {
if (j > 0) { if (j > 0)
localStringBuffer.append(paramString); localStringBuffer.append(paramString);
}
localStringBuffer.append(addBefore).append(Array.get(localObject, j)); localStringBuffer.append(addBefore).append(Array.get(localObject, j));
} }
}
localStringBuffer.append("]"); localStringBuffer.append("]");
} else { } else
localStringBuffer.append(addBefore).append(paramArrayOfObject[i]); localStringBuffer.append(addBefore).append(paramArrayOfObject[i]);
}
} }
return localStringBuffer.toString(); return localStringBuffer.toString();
} }
public static boolean isEquals(String base, String to) { public static boolean isEquals(String base, String to) {
if (base == null) { if (base == null)
return (to == null); return (to == null);
} else { else
return base.equals(to); return base.equals(to);
}
} }
public static Dimension parseDimension(String str) { public static Dimension parseDimension(String str) {
String[] tokenized = tokenize(str, "x,"); String[] tokenized = tokenize(str, "x,");
if (tokenized.length != 2) { if (tokenized.length != 2)
return null; return null;
}
int i = MathUtils.parseInt(tokenized[0], -1); int i = MathUtils.parseInt(tokenized[0], -1);
int j = MathUtils.parseInt(tokenized[1], -1); int j = MathUtils.parseInt(tokenized[1], -1);
if ((i < 0) || (j < 0)) { if ((i < 0) || (j < 0))
return null; return null;
}
return new Dimension(i, j); return new Dimension(i, j);
} }
@@ -210,9 +185,8 @@ public final class StrUtils {
public static String trimExtension(String filename) { public static String trimExtension(String filename) {
if ((filename != null) && (filename.length() > 0)) { if ((filename != null) && (filename.length() > 0)) {
int i = filename.lastIndexOf('.'); int i = filename.lastIndexOf('.');
if ((i > -1) && (i < (filename.length()))) { if ((i > -1) && (i < (filename.length())))
return filename.substring(0, i); return filename.substring(0, i);
}
} }
return filename; return filename;
} }

View File

@@ -38,28 +38,29 @@ public class SwingUtils {
* Make DefaultTableModel by overriding getColumnClass and isCellEditable of * Make DefaultTableModel by overriding getColumnClass and isCellEditable of
* DefaultTableModel. * DefaultTableModel.
* *
* @param titleA The title of each column. * @param titleA The title of each column.
* @param typesA The type of each column value. * @param typesA The type of each column value.
* @param canEditA Is column editable? * @param canEditA Is column editable?
*
* @return * @return
*/ */
public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) { public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) {
return new javax.swing.table.DefaultTableModel( return new javax.swing.table.DefaultTableModel(
new Object[][]{}, new Object[][] {},
titleA) { titleA) {
Class[] types = typesA; Class[] types = typesA;
boolean[] canEdit = canEditA; boolean[] canEdit = canEditA;
@Override @Override
public Class getColumnClass(int columnIndex) { public Class getColumnClass(int columnIndex) {
return types[columnIndex]; return types[columnIndex];
} }
@Override @Override
public boolean isCellEditable(int rowIndex, int columnIndex) { public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex]; return canEdit[columnIndex];
} }
}; };
} }
/** /**
@@ -99,6 +100,7 @@ public class SwingUtils {
* Get the DefaultListModel from JList. * Get the DefaultListModel from JList.
* *
* @param list * @param list
*
* @return Forcely Type casted to DefaultListModel * @return Forcely Type casted to DefaultListModel
*/ */
public static DefaultListModel getDefaultListModel(JList list) { public static DefaultListModel getDefaultListModel(JList list) {
@@ -108,7 +110,7 @@ public class SwingUtils {
/** /**
* Append new element to JList * Append new element to JList
* *
* @param list the JList * @param list the JList
* @param element the Element * @param element the Element
*/ */
public static void appendLast(JList list, Object element) { public static void appendLast(JList list, Object element) {
@@ -152,12 +154,14 @@ public class SwingUtils {
} }
public static String getParsedJPanelText(JLabel jLabel1, String longString) { public static String getParsedJPanelText(JLabel jLabel1, String longString) {
if (StrUtils.isBlank(longString)) return longString; if (StrUtils.isBlank(longString))
return longString;
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
char[] chars = longString.toCharArray(); char[] chars = longString.toCharArray();
FontMetrics fontMetrics = jLabel1.getFontMetrics(jLabel1.getFont()); FontMetrics fontMetrics = jLabel1.getFontMetrics(jLabel1.getFont());
for (int beginIndex = 0, limit = 1;; limit++) { for (int beginIndex = 0, limit = 1;; limit++) {
if (beginIndex + limit >= chars.length) break; if (beginIndex + limit >= chars.length)
break;
if (fontMetrics.charsWidth(chars, beginIndex, limit) < jLabel1.getWidth()) { if (fontMetrics.charsWidth(chars, beginIndex, limit) < jLabel1.getWidth()) {
if (beginIndex + limit < chars.length) if (beginIndex + limit < chars.length)
continue; continue;

View File

@@ -60,7 +60,9 @@ public final class Utils {
Field field = ClassLoader.class.getDeclaredField("usr_paths"); Field field = ClassLoader.class.getDeclaredField("usr_paths");
field.setAccessible(true); field.setAccessible(true);
String[] paths = (String[]) field.get(null); String[] paths = (String[]) field.get(null);
for (String path : paths) if (s.equals(path)) return; for (String path : paths)
if (s.equals(path))
return;
String[] tmp = new String[paths.length + 1]; String[] tmp = new String[paths.length + 1];
System.arraycopy(paths, 0, tmp, 0, paths.length); System.arraycopy(paths, 0, tmp, 0, paths.length);
tmp[paths.length] = s; tmp[paths.length] = s;
@@ -166,6 +168,7 @@ public final class Utils {
/** /**
* In order to fight against the permission manager by Minecraft Forge. * In order to fight against the permission manager by Minecraft Forge.
*
* @param status exit code * @param status exit code
*/ */
public static void shutdownForcely(int status) { public static void shutdownForcely(int status) {
@@ -181,6 +184,7 @@ public final class Utils {
} }
public static void requireNonNull(Object o) { public static void requireNonNull(Object o) {
if (o == null) throw new NullPointerException("Oh dear, there is a problem..."); if (o == null)
throw new NullPointerException("Oh dear, there is a problem...");
} }
} }

View File

@@ -68,9 +68,12 @@ public final class VersionNumber implements Comparable<VersionNumber> {
@Override @Override
public int compareTo(VersionNumber o) { public int compareTo(VersionNumber o) {
if (isOlder(this, o)) return -1; if (isOlder(this, o))
else if (isOlder(o, this)) return 1; return -1;
else return 0; else if (isOlder(o, this))
return 1;
else
return 0;
} }
} }

View File

@@ -25,87 +25,80 @@ import java.io.UnsupportedEncodingException;
public class Base64 { public class Base64 {
public static char[] encode(byte[] data) { public static char[] encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4]; char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false; boolean quad = false;
boolean trip = false; boolean trip = false;
int val = (0xFF & (int) data[i]); int val = (0xFF & (int) data[i]);
val <<= 8; val <<= 8;
if ((i + 1) < data.length) { if ((i + 1) < data.length) {
val |= (0xFF & (int) data[i + 1]); val |= (0xFF & (int) data[i + 1]);
trip = true; trip = true;
} }
val <<= 8; val <<= 8;
if ((i + 2) < data.length) { if ((i + 2) < data.length) {
val |= (0xFF & (int) data[i + 2]); val |= (0xFF & (int) data[i + 2]);
quad = true; quad = true;
} }
out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
val >>= 6; val >>= 6;
out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
val >>= 6; val >>= 6;
out[index + 1] = alphabet[val & 0x3F]; out[index + 1] = alphabet[val & 0x3F];
val >>= 6; val >>= 6;
out[index + 0] = alphabet[val & 0x3F]; out[index + 0] = alphabet[val & 0x3F];
} }
return out; return out;
} }
public static char[] encode(String s, String charset) throws UnsupportedEncodingException { public static char[] encode(String s, String charset) throws UnsupportedEncodingException {
return encode(s.getBytes(charset)); return encode(s.getBytes(charset));
} }
public static char[] encode(String s) { public static char[] encode(String s) {
return encode(s.getBytes()); return encode(s.getBytes());
} }
public static byte[] decode(char[] data) { public static byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3; int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 && data[data.length - 1] == '=') { if (data.length > 0 && data[data.length - 1] == '=')
--len; --len;
} if (data.length > 1 && data[data.length - 2] == '=')
if (data.length > 1 && data[data.length - 2] == '=') { --len;
--len; byte[] out = new byte[len];
} int shift = 0;
byte[] out = new byte[len]; int accum = 0;
int shift = 0; int index = 0;
int accum = 0; for (int ix = 0; ix < data.length; ix++) {
int index = 0; int value = codes[data[ix] & 0xFF];
for (int ix = 0; ix < data.length; ix++) { if (value >= 0) {
int value = codes[data[ix] & 0xFF]; accum <<= 6;
if (value >= 0) { shift += 6;
accum <<= 6; accum |= value;
shift += 6; if (shift >= 8) {
accum |= value; shift -= 8;
if (shift >= 8) { out[index++] = (byte) ((accum >> shift) & 0xff);
shift -= 8; }
out[index++] = (byte) ((accum >> shift) & 0xff); }
} }
} if (index != out.length)
} throw new Error("miscalculated data length!");
if (index != out.length) { return out;
throw new Error("miscalculated data length!");
}
return out;
} }
private static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" private static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray(); .toCharArray();
private static final byte[] codes = new byte[256]; private static final byte[] codes = new byte[256];
static { static {
for (int i = 0; i < 256; i++) { for (int i = 0; i < 256; i++)
codes[i] = -1; codes[i] = -1;
} for (int i = 'A'; i <= 'Z'; i++)
for (int i = 'A'; i <= 'Z'; i++) { codes[i] = (byte) (i - 'A');
codes[i] = (byte) (i - 'A'); for (int i = 'a'; i <= 'z'; i++)
} codes[i] = (byte) (26 + i - 'a');
for (int i = 'a'; i <= 'z'; i++) { for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (26 + i - 'a'); codes[i] = (byte) (52 + i - '0');
} codes['+'] = 62;
for (int i = '0'; i <= '9'; i++) { codes['/'] = 63;
codes[i] = (byte) (52 + i - '0');
}
codes['+'] = 62;
codes['/'] = 63;
} }
} }

View File

@@ -33,10 +33,10 @@ public class Charsets {
public static final Charset UTF_8 = Charset.forName("UTF-8"); public static final Charset UTF_8 = Charset.forName("UTF-8");
public static Charset toCharset(Charset charset) { public static Charset toCharset(Charset charset) {
return charset == null ? Charset.defaultCharset() : charset; return charset == null ? Charset.defaultCharset() : charset;
} }
public static Charset toCharset(String charset) { public static Charset toCharset(String charset) {
return charset == null ? Charset.defaultCharset() : Charset.forName(charset); return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
} }
} }

View File

@@ -30,255 +30,255 @@ public class DigestUtils {
private static final int STREAM_BUFFER_LENGTH = 1024; private static final int STREAM_BUFFER_LENGTH = 1024;
private static byte[] digest(MessageDigest digest, InputStream data) private static byte[] digest(MessageDigest digest, InputStream data)
throws IOException { throws IOException {
return updateDigest(digest, data).digest(); return updateDigest(digest, data).digest();
} }
public static MessageDigest getDigest(String algorithm) { public static MessageDigest getDigest(String algorithm) {
try { try {
return MessageDigest.getInstance(algorithm); return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e); throw new IllegalArgumentException(e);
} }
} }
public static MessageDigest getMd2Digest() { public static MessageDigest getMd2Digest() {
return getDigest("MD2"); return getDigest("MD2");
} }
public static MessageDigest getMd5Digest() { public static MessageDigest getMd5Digest() {
return getDigest("MD5"); return getDigest("MD5");
} }
public static MessageDigest getSha1Digest() { public static MessageDigest getSha1Digest() {
return getDigest("SHA-1"); return getDigest("SHA-1");
} }
public static MessageDigest getSha256Digest() { public static MessageDigest getSha256Digest() {
return getDigest("SHA-256"); return getDigest("SHA-256");
} }
public static MessageDigest getSha384Digest() { public static MessageDigest getSha384Digest() {
return getDigest("SHA-384"); return getDigest("SHA-384");
} }
public static MessageDigest getSha512Digest() { public static MessageDigest getSha512Digest() {
return getDigest("SHA-512"); return getDigest("SHA-512");
} }
@Deprecated @Deprecated
public static MessageDigest getShaDigest() { public static MessageDigest getShaDigest() {
return getSha1Digest(); return getSha1Digest();
} }
public static byte[] md2(byte[] data) { public static byte[] md2(byte[] data) {
return getMd2Digest().digest(data); return getMd2Digest().digest(data);
} }
public static byte[] md2(InputStream data) public static byte[] md2(InputStream data)
throws IOException { throws IOException {
return digest(getMd2Digest(), data); return digest(getMd2Digest(), data);
} }
public static byte[] md2(String data) { public static byte[] md2(String data) {
return md2(data.getBytes(Charsets.UTF_8)); return md2(data.getBytes(Charsets.UTF_8));
} }
public static String md2Hex(byte[] data) { public static String md2Hex(byte[] data) {
return Hex.encodeHexString(md2(data)); return Hex.encodeHexString(md2(data));
} }
public static String md2Hex(InputStream data) public static String md2Hex(InputStream data)
throws IOException { throws IOException {
return Hex.encodeHexString(md2(data)); return Hex.encodeHexString(md2(data));
} }
public static String md2Hex(String data) { public static String md2Hex(String data) {
return Hex.encodeHexString(md2(data)); return Hex.encodeHexString(md2(data));
} }
public static byte[] md5(byte[] data) { public static byte[] md5(byte[] data) {
return getMd5Digest().digest(data); return getMd5Digest().digest(data);
} }
public static byte[] md5(InputStream data) public static byte[] md5(InputStream data)
throws IOException { throws IOException {
return digest(getMd5Digest(), data); return digest(getMd5Digest(), data);
} }
public static byte[] md5(String data) { public static byte[] md5(String data) {
return md5(data.getBytes(Charsets.UTF_8)); return md5(data.getBytes(Charsets.UTF_8));
} }
public static String md5Hex(byte[] data) { public static String md5Hex(byte[] data) {
return Hex.encodeHexString(md5(data)); return Hex.encodeHexString(md5(data));
} }
public static String md5Hex(InputStream data) public static String md5Hex(InputStream data)
throws IOException { throws IOException {
return Hex.encodeHexString(md5(data)); return Hex.encodeHexString(md5(data));
} }
public static String md5Hex(String data) { public static String md5Hex(String data) {
return Hex.encodeHexString(md5(data)); return Hex.encodeHexString(md5(data));
} }
@Deprecated @Deprecated
public static byte[] sha(byte[] data) { public static byte[] sha(byte[] data) {
return sha1(data); return sha1(data);
} }
@Deprecated @Deprecated
public static byte[] sha(InputStream data) public static byte[] sha(InputStream data)
throws IOException { throws IOException {
return sha1(data); return sha1(data);
} }
@Deprecated @Deprecated
public static byte[] sha(String data) { public static byte[] sha(String data) {
return sha1(data); return sha1(data);
} }
public static byte[] sha1(byte[] data) { public static byte[] sha1(byte[] data) {
return getSha1Digest().digest(data); return getSha1Digest().digest(data);
} }
public static byte[] sha1(InputStream data) public static byte[] sha1(InputStream data)
throws IOException { throws IOException {
return digest(getSha1Digest(), data); return digest(getSha1Digest(), data);
} }
public static byte[] sha1(String data) { public static byte[] sha1(String data) {
return sha1(data.getBytes(Charsets.UTF_8)); return sha1(data.getBytes(Charsets.UTF_8));
} }
public static String sha1Hex(byte[] data) { public static String sha1Hex(byte[] data) {
return Hex.encodeHexString(sha1(data)); return Hex.encodeHexString(sha1(data));
} }
public static String sha1Hex(InputStream data) public static String sha1Hex(InputStream data)
throws IOException { throws IOException {
return Hex.encodeHexString(sha1(data)); return Hex.encodeHexString(sha1(data));
} }
public static String sha1Hex(String data) { public static String sha1Hex(String data) {
return Hex.encodeHexString(sha1(data)); return Hex.encodeHexString(sha1(data));
} }
public static byte[] sha256(byte[] data) { public static byte[] sha256(byte[] data) {
return getSha256Digest().digest(data); return getSha256Digest().digest(data);
} }
public static byte[] sha256(InputStream data) public static byte[] sha256(InputStream data)
throws IOException { throws IOException {
return digest(getSha256Digest(), data); return digest(getSha256Digest(), data);
} }
public static byte[] sha256(String data) { public static byte[] sha256(String data) {
return sha256(data.getBytes(Charsets.UTF_8)); return sha256(data.getBytes(Charsets.UTF_8));
} }
public static String sha256Hex(byte[] data) { public static String sha256Hex(byte[] data) {
return Hex.encodeHexString(sha256(data)); return Hex.encodeHexString(sha256(data));
} }
public static String sha256Hex(InputStream data) public static String sha256Hex(InputStream data)
throws IOException { throws IOException {
return Hex.encodeHexString(sha256(data)); return Hex.encodeHexString(sha256(data));
} }
public static String sha256Hex(String data) { public static String sha256Hex(String data) {
return Hex.encodeHexString(sha256(data)); return Hex.encodeHexString(sha256(data));
} }
public static byte[] sha384(byte[] data) { public static byte[] sha384(byte[] data) {
return getSha384Digest().digest(data); return getSha384Digest().digest(data);
} }
public static byte[] sha384(InputStream data) public static byte[] sha384(InputStream data)
throws IOException { throws IOException {
return digest(getSha384Digest(), data); return digest(getSha384Digest(), data);
} }
public static byte[] sha384(String data) { public static byte[] sha384(String data) {
return sha384(data.getBytes(Charsets.UTF_8)); return sha384(data.getBytes(Charsets.UTF_8));
} }
public static String sha384Hex(byte[] data) { public static String sha384Hex(byte[] data) {
return Hex.encodeHexString(sha384(data)); return Hex.encodeHexString(sha384(data));
} }
public static String sha384Hex(InputStream data) public static String sha384Hex(InputStream data)
throws IOException { throws IOException {
return Hex.encodeHexString(sha384(data)); return Hex.encodeHexString(sha384(data));
} }
public static String sha384Hex(String data) { public static String sha384Hex(String data) {
return Hex.encodeHexString(sha384(data)); return Hex.encodeHexString(sha384(data));
} }
public static byte[] sha512(byte[] data) { public static byte[] sha512(byte[] data) {
return getSha512Digest().digest(data); return getSha512Digest().digest(data);
} }
public static byte[] sha512(InputStream data) public static byte[] sha512(InputStream data)
throws IOException { throws IOException {
return digest(getSha512Digest(), data); return digest(getSha512Digest(), data);
} }
public static byte[] sha512(String data) { public static byte[] sha512(String data) {
return sha512(data.getBytes(Charsets.UTF_8)); return sha512(data.getBytes(Charsets.UTF_8));
} }
public static String sha512Hex(byte[] data) { public static String sha512Hex(byte[] data) {
return Hex.encodeHexString(sha512(data)); return Hex.encodeHexString(sha512(data));
} }
public static String sha512Hex(InputStream data) public static String sha512Hex(InputStream data)
throws IOException { throws IOException {
return Hex.encodeHexString(sha512(data)); return Hex.encodeHexString(sha512(data));
} }
public static String sha512Hex(String data) { public static String sha512Hex(String data) {
return Hex.encodeHexString(sha512(data)); return Hex.encodeHexString(sha512(data));
} }
@Deprecated @Deprecated
public static String shaHex(byte[] data) { public static String shaHex(byte[] data) {
return sha1Hex(data); return sha1Hex(data);
} }
@Deprecated @Deprecated
public static String shaHex(InputStream data) public static String shaHex(InputStream data)
throws IOException { throws IOException {
return sha1Hex(data); return sha1Hex(data);
} }
@Deprecated @Deprecated
public static String shaHex(String data) { public static String shaHex(String data) {
return sha1Hex(data); return sha1Hex(data);
} }
public static MessageDigest updateDigest(MessageDigest messageDigest, byte[] valueToDigest) { public static MessageDigest updateDigest(MessageDigest messageDigest, byte[] valueToDigest) {
messageDigest.update(valueToDigest); messageDigest.update(valueToDigest);
return messageDigest; return messageDigest;
} }
public static MessageDigest updateDigest(MessageDigest digest, InputStream data) public static MessageDigest updateDigest(MessageDigest digest, InputStream data)
throws IOException { throws IOException {
byte[] buffer = new byte[STREAM_BUFFER_LENGTH]; byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH); int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
while (read > -1) { while (read > -1) {
digest.update(buffer, 0, read); digest.update(buffer, 0, read);
read = data.read(buffer, 0, STREAM_BUFFER_LENGTH); read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
} }
return digest; return digest;
} }
public static MessageDigest updateDigest(MessageDigest messageDigest, String valueToDigest) { public static MessageDigest updateDigest(MessageDigest messageDigest, String valueToDigest) {
messageDigest.update(valueToDigest.getBytes(Charsets.UTF_8)); messageDigest.update(valueToDigest.getBytes(Charsets.UTF_8));
return messageDigest; return messageDigest;
} }
} }

View File

@@ -28,108 +28,106 @@ public class Hex {
private final Charset charset; private final Charset charset;
public static byte[] decodeHex(char[] data) throws Exception { public static byte[] decodeHex(char[] data) throws Exception {
int len = data.length; int len = data.length;
if ((len & 0x1) != 0) { if ((len & 0x1) != 0)
throw new Exception("Odd number of characters."); throw new Exception("Odd number of characters.");
}
byte[] out = new byte[len >> 1]; byte[] out = new byte[len >> 1];
int i = 0; int i = 0;
for (int j = 0; j < len; i++) { for (int j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4; int f = toDigit(data[j], j) << 4;
j++; j++;
f |= toDigit(data[j], j); f |= toDigit(data[j], j);
j++; j++;
out[i] = (byte) (f & 0xFF); out[i] = (byte) (f & 0xFF);
} }
return out; return out;
} }
public static char[] encodeHex(byte[] data) { public static char[] encodeHex(byte[] data) {
return encodeHex(data, true); return encodeHex(data, true);
} }
public static char[] encodeHex(byte[] data, boolean toLowerCase) { public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
} }
protected static char[] encodeHex(byte[] data, char[] toDigits) { protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length; int l = data.length;
char[] out = new char[l << 1]; char[] out = new char[l << 1];
int i = 0; int i = 0;
for (int j = 0; i < l; i++) { for (int j = 0; i < l; i++) {
out[(j++)] = toDigits[((0xF0 & data[i]) >>> 4)]; out[(j++)] = toDigits[((0xF0 & data[i]) >>> 4)];
out[(j++)] = toDigits[(0xF & data[i])]; out[(j++)] = toDigits[(0xF & data[i])];
} }
return out; return out;
} }
public static String encodeHexString(byte[] data) { public static String encodeHexString(byte[] data) {
return new String(encodeHex(data)); return new String(encodeHex(data));
} }
protected static int toDigit(char ch, int index) throws Exception { protected static int toDigit(char ch, int index) throws Exception {
int digit = Character.digit(ch, 16); int digit = Character.digit(ch, 16);
if (digit == -1) { if (digit == -1)
throw new Exception("Illegal hexadecimal character " + ch + " at index " + index); throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
} return digit;
return digit;
} }
public Hex() { public Hex() {
this.charset = DEFAULT_CHARSET; this.charset = DEFAULT_CHARSET;
} }
public Hex(Charset charset) { public Hex(Charset charset) {
this.charset = charset; this.charset = charset;
} }
public Hex(String charsetName) { public Hex(String charsetName) {
this(Charset.forName(charsetName)); this(Charset.forName(charsetName));
} }
public byte[] decode(byte[] array) throws Exception { public byte[] decode(byte[] array) throws Exception {
return decodeHex(new String(array, getCharset()).toCharArray()); return decodeHex(new String(array, getCharset()).toCharArray());
} }
public Object decode(Object object) throws Exception { public Object decode(Object object) throws Exception {
try { try {
char[] charArray = (object instanceof String) ? ((String) object).toCharArray() : (char[]) (char[]) object; char[] charArray = (object instanceof String) ? ((String) object).toCharArray() : (char[]) (char[]) object;
return decodeHex(charArray); return decodeHex(charArray);
} catch (ClassCastException e) { } catch (ClassCastException e) {
throw new Exception(e.getMessage(), e); throw new Exception(e.getMessage(), e);
} }
} }
public byte[] encode(byte[] array) { public byte[] encode(byte[] array) {
return encodeHexString(array).getBytes(getCharset()); return encodeHexString(array).getBytes(getCharset());
} }
public Object encode(Object object) public Object encode(Object object)
throws Exception { throws Exception {
try { try {
byte[] byteArray = (object instanceof String) ? ((String) object).getBytes(getCharset()) : (byte[]) (byte[]) object; byte[] byteArray = (object instanceof String) ? ((String) object).getBytes(getCharset()) : (byte[]) (byte[]) object;
return encodeHex(byteArray); return encodeHex(byteArray);
} catch (ClassCastException e) { } catch (ClassCastException e) {
throw new Exception(e.getMessage(), e); throw new Exception(e.getMessage(), e);
} }
} }
public Charset getCharset() { public Charset getCharset() {
return this.charset; return this.charset;
} }
public String getCharsetName() { public String getCharsetName() {
return this.charset.name(); return this.charset.name();
} }
@Override @Override
public String toString() { public String toString() {
return super.toString() + "[charsetName=" + this.charset + "]"; return super.toString() + "[charsetName=" + this.charset + "]";
} }
} }

View File

@@ -24,7 +24,8 @@ public class TrueFunction implements NonFunction<Boolean> {
public static final TrueFunction instance = new TrueFunction(); public static final TrueFunction instance = new TrueFunction();
private TrueFunction(){} private TrueFunction() {
}
@Override @Override
public Boolean apply() { public Boolean apply() {

View File

@@ -43,7 +43,8 @@ public class Compressor {
* 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件 * 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件
* *
* @param sourceDir 源文件夹 * @param sourceDir 源文件夹
* @param zipFile 压缩生成的zip文件路径。 * @param zipFile 压缩生成的zip文件路径。
*
* @throws java.io.IOException 压缩失败或无法读取 * @throws java.io.IOException 压缩失败或无法读取
*/ */
public static void zip(File sourceDir, File zipFile) throws IOException { public static void zip(File sourceDir, File zipFile) throws IOException {
@@ -64,12 +65,12 @@ public class Compressor {
/** /**
* 将文件压缩成zip文件 * 将文件压缩成zip文件
* *
* @param source zip文件路径 * @param source zip文件路径
* @param basePath 待压缩文件根目录 * @param basePath 待压缩文件根目录
* @param zos zip文件的os * @param zos zip文件的os
*/ */
private static void zipFile(File source, String basePath, private static void zipFile(File source, String basePath,
ZipOutputStream zos) throws IOException { ZipOutputStream zos) throws IOException {
File[] files; File[] files;
if (source.isDirectory()) if (source.isDirectory())
files = source.listFiles(); files = source.listFiles();
@@ -83,7 +84,7 @@ public class Compressor {
for (File file : files) for (File file : files)
if (file.isDirectory()) { if (file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) pathName = file.getPath().substring(basePath.length() + 1)
+ "/"; + "/";
if (file.getName().toLowerCase().contains("meta-inf")) if (file.getName().toLowerCase().contains("meta-inf"))
continue; continue;
zos.putNextEntry(new ZipEntry(pathName)); zos.putNextEntry(new ZipEntry(pathName));
@@ -111,8 +112,9 @@ public class Compressor {
* 将文件压缩成zip文件 * 将文件压缩成zip文件
* *
* @param zipFileName zip文件路径 * @param zipFileName zip文件路径
* @param extPlace 待压缩文件根目录 * @param extPlace 待压缩文件根目录
* @param without 带前缀的不解压 * @param without 带前缀的不解压
*
* @throws java.io.IOException 解压失败或无法写入 * @throws java.io.IOException 解压失败或无法写入
*/ */
public static void unzip(File zipFileName, File extPlace, String[] without) throws IOException { public static void unzip(File zipFileName, File extPlace, String[] without) throws IOException {
@@ -125,7 +127,8 @@ public class Compressor {
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
ZipEntry zipEnt = (ZipEntry) e.nextElement(); ZipEntry zipEnt = (ZipEntry) e.nextElement();
gbkPath = zipEnt.getName(); gbkPath = zipEnt.getName();
if (StrUtils.startsWithOne(without, gbkPath)) continue; if (StrUtils.startsWithOne(without, gbkPath))
continue;
if (zipEnt.isDirectory()) { if (zipEnt.isDirectory()) {
strtemp = strPath + File.separator + gbkPath; strtemp = strPath + File.separator + gbkPath;
File dir = new File(strtemp); File dir = new File(strtemp);
@@ -160,7 +163,8 @@ public class Compressor {
* 将zip1合并到zip2里面即保留zip2 * 将zip1合并到zip2里面即保留zip2
* *
* @param destFile zip1 * @param destFile zip1
* @param srcFile zip2 * @param srcFile zip2
*
* @throws java.io.IOException 无法写入或读取 * @throws java.io.IOException 无法写入或读取
*/ */
public static void merge(File destFile, File srcFile) throws IOException { public static void merge(File destFile, File srcFile) throws IOException {

View File

@@ -36,7 +36,7 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
public class FileUtils { public class FileUtils {
public static void deleteDirectory(File directory) public static void deleteDirectory(File directory)
throws IOException { throws IOException {
if (!directory.exists()) if (!directory.exists())
return; return;
@@ -71,7 +71,7 @@ public class FileUtils {
} }
public static void cleanDirectory(File directory) public static void cleanDirectory(File directory)
throws IOException { throws IOException {
if (!directory.exists()) { if (!directory.exists()) {
//String message = directory + " does not exist"; //String message = directory + " does not exist";
//throw new IllegalArgumentException(message); //throw new IllegalArgumentException(message);
@@ -101,7 +101,7 @@ public class FileUtils {
} }
public static void forceDelete(File file) public static void forceDelete(File file)
throws IOException { throws IOException {
if (file.isDirectory()) if (file.isDirectory())
deleteDirectory(file); deleteDirectory(file);
else { else {
@@ -117,7 +117,7 @@ public class FileUtils {
} }
public static boolean isSymlink(File file) public static boolean isSymlink(File file)
throws IOException { throws IOException {
if (file == null) if (file == null)
throw new NullPointerException("File must not be null"); throw new NullPointerException("File must not be null");
if (File.separatorChar == '\\') if (File.separatorChar == '\\')
@@ -134,22 +134,22 @@ public class FileUtils {
} }
public static void copyDirectory(File srcDir, File destDir) public static void copyDirectory(File srcDir, File destDir)
throws IOException { throws IOException {
copyDirectory(srcDir, destDir, true); copyDirectory(srcDir, destDir, true);
} }
public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate)
throws IOException { throws IOException {
copyDirectory(srcDir, destDir, null, preserveFileDate); copyDirectory(srcDir, destDir, null, preserveFileDate);
} }
public static void copyDirectory(File srcDir, File destDir, FileFilter filter) public static void copyDirectory(File srcDir, File destDir, FileFilter filter)
throws IOException { throws IOException {
copyDirectory(srcDir, destDir, filter, true); copyDirectory(srcDir, destDir, filter, true);
} }
public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)
throws IOException { throws IOException {
if (srcDir == null) if (srcDir == null)
throw new NullPointerException("Source must not be null"); throw new NullPointerException("Source must not be null");
if (destDir == null) if (destDir == null)
@@ -176,7 +176,7 @@ public class FileUtils {
} }
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList) private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList)
throws IOException { throws IOException {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles == null) if (srcFiles == null)
throw new IOException("Failed to list contents of " + srcDir); throw new IOException("Failed to list contents of " + srcDir);
@@ -203,7 +203,7 @@ public class FileUtils {
} }
public static String readFileToString(File file) public static String readFileToString(File file)
throws IOException { throws IOException {
return NetUtils.getStreamContent(IOUtils.openInputStream(file)); return NetUtils.getStreamContent(IOUtils.openInputStream(file));
} }
@@ -217,7 +217,7 @@ public class FileUtils {
} }
public static String readFileToString(File file, String charset) public static String readFileToString(File file, String charset)
throws IOException { throws IOException {
return NetUtils.getStreamContent(IOUtils.openInputStream(file), charset); return NetUtils.getStreamContent(IOUtils.openInputStream(file), charset);
} }
@@ -238,12 +238,12 @@ public class FileUtils {
} }
public static void copyFile(File srcFile, File destFile) public static void copyFile(File srcFile, File destFile)
throws IOException { throws IOException {
copyFile(srcFile, destFile, true); copyFile(srcFile, destFile, true);
} }
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) public static void copyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException { throws IOException {
if (srcFile == null) if (srcFile == null)
throw new NullPointerException("Source must not be null"); throw new NullPointerException("Source must not be null");
if (destFile == null) if (destFile == null)
@@ -256,7 +256,7 @@ public class FileUtils {
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
File parentFile = destFile.getParentFile(); File parentFile = destFile.getParentFile();
if ((parentFile != null) if ((parentFile != null)
&& (!parentFile.mkdirs()) && (!parentFile.isDirectory())) && (!parentFile.mkdirs()) && (!parentFile.isDirectory()))
throw new IOException("Destination '" + parentFile + "' directory cannot be created"); throw new IOException("Destination '" + parentFile + "' directory cannot be created");
if ((destFile.exists()) && (!destFile.canWrite())) if ((destFile.exists()) && (!destFile.canWrite()))
@@ -265,7 +265,7 @@ public class FileUtils {
} }
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException { throws IOException {
if ((destFile.exists()) && (destFile.isDirectory())) if ((destFile.exists()) && (destFile.isDirectory()))
throw new IOException("Destination '" + destFile + "' exists but is a directory"); throw new IOException("Destination '" + destFile + "' exists but is a directory");
@@ -355,38 +355,38 @@ public class FileUtils {
} }
public static void write(File file, CharSequence data) public static void write(File file, CharSequence data)
throws IOException { throws IOException {
write(file, data, "UTF-8", false); write(file, data, "UTF-8", false);
} }
public static void write(File file, CharSequence data, boolean append) public static void write(File file, CharSequence data, boolean append)
throws IOException { throws IOException {
write(file, data, "UTF-8", append); write(file, data, "UTF-8", append);
} }
public static void write(File file, CharSequence data, String encoding) public static void write(File file, CharSequence data, String encoding)
throws IOException { throws IOException {
write(file, data, encoding, false); write(file, data, encoding, false);
} }
public static void write(File file, CharSequence data, String encoding, boolean append) public static void write(File file, CharSequence data, String encoding, boolean append)
throws IOException { throws IOException {
String str = data == null ? null : data.toString(); String str = data == null ? null : data.toString();
writeStringToFile(file, str, encoding, append); writeStringToFile(file, str, encoding, append);
} }
public static void writeStringToFile(File file, String data) public static void writeStringToFile(File file, String data)
throws IOException { throws IOException {
writeStringToFile(file, data, "UTF-8", false); writeStringToFile(file, data, "UTF-8", false);
} }
public static void writeStringToFile(File file, String data, String encoding) public static void writeStringToFile(File file, String data, String encoding)
throws IOException { throws IOException {
writeStringToFile(file, data, encoding, false); writeStringToFile(file, data, encoding, false);
} }
public static void writeStringToFile(File file, String data, String encoding, boolean append) public static void writeStringToFile(File file, String data, String encoding, boolean append)
throws IOException { throws IOException {
OutputStream out = null; OutputStream out = null;
try { try {
out = openOutputStream(file, append); out = openOutputStream(file, append);
@@ -398,7 +398,7 @@ public class FileUtils {
} }
public static FileInputStream openInputStream(File file) public static FileInputStream openInputStream(File file)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
@@ -410,12 +410,12 @@ public class FileUtils {
} }
public static FileOutputStream openOutputStream(File file) public static FileOutputStream openOutputStream(File file)
throws IOException { throws IOException {
return openOutputStream(file, false); return openOutputStream(file, false);
} }
public static FileOutputStream openOutputStream(File file, boolean append) public static FileOutputStream openOutputStream(File file, boolean append)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
@@ -424,7 +424,7 @@ public class FileUtils {
} else { } else {
File parent = file.getParentFile(); File parent = file.getParentFile();
if ((parent != null) if ((parent != null)
&& (!parent.mkdirs()) && (!parent.isDirectory())) && (!parent.mkdirs()) && (!parent.isDirectory()))
throw new IOException("Directory '" + parent + "' could not be created"); throw new IOException("Directory '" + parent + "' could not be created");
file.createNewFile(); file.createNewFile();
} }
@@ -435,9 +435,11 @@ public class FileUtils {
public static File[] searchSuffix(File dir, String suffix) { public static File[] searchSuffix(File dir, String suffix) {
ArrayList<File> al = new ArrayList(); ArrayList<File> al = new ArrayList();
File[] files = dir.listFiles(); File[] files = dir.listFiles();
if (files == null) return new File[0]; if (files == null)
return new File[0];
for (File f : files) for (File f : files)
if (f.getName().endsWith(suffix)) al.add(f); if (f.getName().endsWith(suffix))
al.add(f);
return al.toArray(new File[0]); return al.toArray(new File[0]);
} }
} }

View File

@@ -218,19 +218,19 @@ public class IOUtils {
} }
public static void write(byte[] data, OutputStream output) public static void write(byte[] data, OutputStream output)
throws IOException { throws IOException {
if (data != null) if (data != null)
output.write(data); output.write(data);
} }
public static void write(String data, OutputStream output, String encoding) public static void write(String data, OutputStream output, String encoding)
throws IOException { throws IOException {
if (data != null) if (data != null)
output.write(data.getBytes(encoding)); output.write(data.getBytes(encoding));
} }
public static FileInputStream openInputStream(File file) public static FileInputStream openInputStream(File file)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
@@ -284,9 +284,8 @@ public class IOUtils {
try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getInputStream()))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getInputStream()))) {
jp.getRawProcess().waitFor(); jp.getRawProcess().waitFor();
String line; String line;
while((line = br.readLine()) != null) { while ((line = br.readLine()) != null)
lines.add(line); lines.add(line);
}
} }
return lines; return lines;
} }
@@ -297,9 +296,8 @@ public class IOUtils {
try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getErrorStream()))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getErrorStream()))) {
jp.getRawProcess().waitFor(); jp.getRawProcess().waitFor();
String line; String line;
while((line = br.readLine()) != null) { while ((line = br.readLine()) != null)
lines.add(line); lines.add(line);
}
} }
return lines; return lines;
} }

View File

@@ -52,7 +52,8 @@ public class Java {
if (obj instanceof Java) { if (obj instanceof Java) {
Java j = (Java) obj; Java j = (Java) obj;
return (j.getName() == null && this.getName() == null) || ((Java) obj).getName().equals(this.getName()); return (j.getName() == null && this.getName() == null) || ((Java) obj).getName().equals(this.getName());
} else return false; } else
return false;
} }
@Override @Override
@@ -88,8 +89,10 @@ public class Java {
for (String java : javas) { for (String java : javas) {
int s = 0; int s = 0;
for (char c : java.toCharArray()) for (char c : java.toCharArray())
if (c == '.') s++; if (c == '.')
if (s <= 1) continue; s++;
if (s <= 1)
continue;
String javahome = queryRegValue(java, "JavaHome"); String javahome = queryRegValue(java, "JavaHome");
if (javahome != null) if (javahome != null)
ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\".length()), javahome)); ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\".length()), javahome));
@@ -98,8 +101,10 @@ public class Java {
for (String java : javas) { for (String java : javas) {
int s = 0; int s = 0;
for (char c : java.toCharArray()) for (char c : java.toCharArray())
if (c == '.') s++; if (c == '.')
if (s <= 1) continue; s++;
if (s <= 1)
continue;
String javahome = queryRegValue(java, "JavaHome"); String javahome = queryRegValue(java, "JavaHome");
if (javahome != null) if (javahome != null)
ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\".length()), javahome)); ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\".length()), javahome));
@@ -111,7 +116,7 @@ public class Java {
} }
private static List<String> queryRegSubFolders(String location) throws IOException, InterruptedException { private static List<String> queryRegSubFolders(String location) throws IOException, InterruptedException {
String[] cmd = new String[]{"cmd", "/c", "reg", "query", location}; String[] cmd = new String[] {"cmd", "/c", "reg", "query", location};
List<String> l = IOUtils.readProcessByInputStream(cmd); List<String> l = IOUtils.readProcessByInputStream(cmd);
List<String> ans = new ArrayList<>(); List<String> ans = new ArrayList<>();
for (String line : l) for (String line : l)
@@ -121,11 +126,12 @@ public class Java {
} }
private static String queryRegValue(String location, String name) throws IOException, InterruptedException { private static String queryRegValue(String location, String name) throws IOException, InterruptedException {
String[] cmd = new String[]{"cmd", "/c", "reg", "query", location, "/v", name}; String[] cmd = new String[] {"cmd", "/c", "reg", "query", location, "/v", name};
List<String> l = IOUtils.readProcessByInputStream(cmd); List<String> l = IOUtils.readProcessByInputStream(cmd);
boolean last = false; boolean last = false;
for (String s : l) { for (String s : l) {
if (s.trim().isEmpty()) continue; if (s.trim().isEmpty())
continue;
if (last == true && s.trim().startsWith(name)) { if (last == true && s.trim().startsWith(name)) {
int begins = s.indexOf(name); int begins = s.indexOf(name);
if (begins > 0) { if (begins > 0) {
@@ -137,7 +143,8 @@ public class Java {
} }
} }
} }
if (s.trim().equals(location)) last = true; if (s.trim().equals(location))
last = true;
} }
return null; return null;
} }

View File

@@ -34,7 +34,8 @@ public class JavaProcess {
public JavaProcess(List<String> commands, Process process, ProcessManager pm) { public JavaProcess(List<String> commands, Process process, ProcessManager pm) {
this.commands = commands; this.commands = commands;
this.process = process; this.process = process;
if (pm != null) pm.registerProcess(this); if (pm != null)
pm.registerProcess(this);
} }
public JavaProcess(String[] commands, Process process, ProcessManager pm) { public JavaProcess(String[] commands, Process process, ProcessManager pm) {

View File

@@ -40,16 +40,16 @@ public class JavaProcessMonitor {
public void start() { public void start() {
Event<JavaProcess> event = (sender2, t) -> { Event<JavaProcess> event = (sender2, t) -> {
if(t.getExitCode() != 0) { if (t.getExitCode() != 0)
MessageBox.Show(C.i18n("launch.exited_abnormally")); MessageBox.Show(C.i18n("launch.exited_abnormally"));
}
processThreadStopped((ProcessThread) sender2, false); processThreadStopped((ProcessThread) sender2, false);
return true; return true;
}; };
Event<JavaProcess> event2 = (sender3, p1) -> { Event<JavaProcess> event2 = (sender3, p1) -> {
if (p1.getExitCode() != 0 && p1.getStdErrLines().size() > 0 && StrUtils.containsOne(p1.getStdErrLines(), Arrays.asList("Could not create the Java Virtual Machine.", if (p1.getExitCode() != 0 && p1.getStdErrLines().size() > 0 && StrUtils.containsOne(p1.getStdErrLines(), Arrays.asList("Could not create the Java Virtual Machine.",
"Error occurred during initialization of VM", "Error occurred during initialization of VM",
"A fatal exception has occurred. Program will exit."))) MessageBox.Show(C.i18n("launch.cannot_create_jvm")); "A fatal exception has occurred. Program will exit.")))
MessageBox.Show(C.i18n("launch.cannot_create_jvm"));
processThreadStopped((ProcessThread) sender3, false); processThreadStopped((ProcessThread) sender3, false);
return true; return true;
}; };
@@ -71,7 +71,8 @@ public class JavaProcessMonitor {
al.remove(t); al.remove(t);
al.removeAll(CollectionUtils.sortOut(al, t1 -> !t1.isAlive())); al.removeAll(CollectionUtils.sortOut(al, t1 -> !t1.isAlive()));
if (al.isEmpty() || forceTermintate) { if (al.isEmpty() || forceTermintate) {
for (Thread a : al) a.interrupt(); for (Thread a : al)
a.interrupt();
al.clear(); al.clear();
stoppedEvent.execute(p); stoppedEvent.execute(p);
} }

Some files were not shown because too many files have changed in this diff Show More