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,19 +53,24 @@ public final class Launcher {
ArrayList<String> cmdList = new ArrayList<>();
for (String s : args)
if (s.startsWith("-cp=")) classPath = classPath.concat(s.substring("-cp=".length()));
else if (s.startsWith("-mainClass=")) mainClass = s.substring("-mainClass=".length());
else if (s.equals("-debug")) showInfo = true;
else cmdList.add(s);
if (s.startsWith("-cp="))
classPath = classPath.concat(s.substring("-cp=".length()));
else if (s.startsWith("-mainClass="))
mainClass = s.substring("-mainClass=".length());
else if (s.equals("-debug"))
showInfo = true;
else
cmdList.add(s);
String[] tokenized = StrUtils.tokenize(classPath, File.pathSeparator);
int len = tokenized.length;
if (showInfo) {
LogWindow.instance.setTerminateGame(() -> Utils.shutdownForcely(1));
try {
File logFile = new File("hmclmc.log");
if (!logFile.exists()) logFile.createNewFile();
if (!logFile.exists())
logFile.createNewFile();
FileOutputStream tc = new FileOutputStream(logFile);
DoubleOutputStream out = new DoubleOutputStream(tc, System.out);
System.setOut(new LauncherPrintStream(out));
@ -112,7 +117,7 @@ public final class Launcher {
int flag = 0;
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) {
String trace = StrUtils.getStackTrace(throwable);
final String advice = MinecraftCrashAdvicer.getAdvice(trace);
@ -123,7 +128,7 @@ public final class Launcher {
System.err.println(advice);
System.err.println(trace);
LogWindow.instance.setVisible(true);
flag = 1;
}

View File

@ -91,7 +91,7 @@ public final class Main implements Runnable {
try {
sslContext = SSLContext.getInstance("TLS");
X509TrustManager[] xtmArray = new X509TrustManager[]{XTM};
X509TrustManager[] xtmArray = new X509TrustManager[] {XTM};
sslContext.init(null, xtmArray, new java.security.SecureRandom());
} catch (GeneralSecurityException gse) {
}
@ -143,9 +143,9 @@ public final class Main implements Runnable {
if (mainClass != null) {
ArrayList<String> al = new ArrayList<>(Arrays.asList(args));
al.add("notfound");
new URLClassLoader(new URL[]{jar.toURI().toURL()},
URLClassLoader.getSystemClassLoader().getParent()).loadClass(mainClass)
.getMethod("main", String[].class).invoke(null, new Object[]{al.toArray(new String[0])});
new URLClassLoader(new URL[] {jar.toURI().toURL()},
URLClassLoader.getSystemClassLoader().getParent()).loadClass(mainClass)
.getMethod("main", String[].class).invoke(null, new Object[] {al.toArray(new String[0])});
return;
}
}
@ -155,7 +155,7 @@ public final class Main implements Runnable {
} catch (Throwable t) {
t.printStackTrace();
}
System.setProperty("sun.java2d.noddraw", "true");
Thread.setDefaultUncaughtExceptionHandler(new CrashReporter(true));
@ -174,7 +174,7 @@ public final class Main implements Runnable {
LogWindow.instance.clean();
LogWindow.instance.setTerminateGame(GameLauncher.PROCESS_MANAGER::stopAllProcesses);
try {
UIManager.setLookAndFeel(new HelloMinecraftLookAndFeel());
} catch (ParseException | UnsupportedLookAndFeelException ex) {
@ -216,22 +216,23 @@ public final class Main implements Runnable {
if (map != null && map.containsKey("pack"))
try {
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);
}
} catch (IOException 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"
+ C.i18n("update.should_open_link"),
MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
+ C.i18n("update.should_open_link"),
MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
String url = C.URL_PUBLISH;
if (map != null)
if (map.containsKey(OS.os().checked_name))
url = map.get(OS.os().checked_name);
else if (map.containsKey(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 {
java.awt.Desktop.getDesktop().browse(new URI(url));
} catch (URISyntaxException | IOException e) {

View File

@ -58,7 +58,7 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
HMCLog.log("On making head command.");
String str = v.getJavaDir();
if(!v.getJavaDirFile().exists()) {
if (!v.getJavaDirFile().exists()) {
MessageBox.Show(C.i18n("launch.wrong_javadir"));
v.setJava(null);
str = v.getJavaDir();
@ -66,14 +66,15 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
JdkVersion jv = new JdkVersion(str);
if (Settings.getInstance().getJava().contains(jv))
jv = Settings.getInstance().getJava().get(Settings.getInstance().getJava().indexOf(jv));
else try {
jv = JdkVersion.getJavaVersionFromExecutable(str);
Settings.getInstance().getJava().add(jv);
Settings.save();
} catch (IOException ex) {
HMCLog.warn("Failed to get java version", ex);
jv = null;
}
else
try {
jv = JdkVersion.getJavaVersionFromExecutable(str);
Settings.getInstance().getJava().add(jv);
Settings.save();
} catch (IOException ex) {
HMCLog.warn("Failed to get java version", ex);
jv = null;
}
res.add(str);
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));
}
String a = "-Xmx" + v.getMaxMemory();
if (MathUtils.canParseInt(v.getMaxMemory())) a += "m";
if (MathUtils.canParseInt(v.getMaxMemory()))
a += "m";
res.add(a);
}
@ -130,7 +132,7 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
if (OS.os() != OS.WINDOWS)
res.add("-Duser.home=" + gameDir.getParent());
res.add("-Dhellominecraftlauncher.gamedir=" + gameDir.getAbsolutePath());
if (!v.isCanceledWrapper()) {
res.add("-cp");
res.add(StrUtils.parseParams("", Utils.getURL(), File.pathSeparator));
@ -164,9 +166,11 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
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()))
res.addAll(Arrays.asList(v.getMinecraftArgs().split(" ")));

View File

@ -49,13 +49,15 @@ public class DefaultGameLauncher extends GameLauncher {
parallelTask.addDependsTask(new LibraryDownloadTask(s));
dw.addTask(parallelTask);
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)
flag = true;
return flag;
});
decompressNativesEvent.register((sender, value) -> {
if (value == null) return false;
if (value == null)
return false;
for (int i = 0; i < value.decompressFiles.length; i++)
try {
Compressor.unzip(value.decompressFiles[i], value.decompressTo, value.extractRules[i]);

View File

@ -154,8 +154,10 @@ public class GameLauncher {
* According to the name...
*
* @param launcherName the name of launch bat/sh
* @param str launch command
* @param str launch command
*
* @return launcher location
*
* @throws java.io.IOException write contents failed.
*/
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.
*
* @see org.jackhuang.hellominecraft.launcher.version.MinecraftVersionManager
* @author huangyuhui
*/
@ -40,14 +41,18 @@ public abstract class IMinecraftProvider {
/**
* Get the run directory of given version.
*
* @param id the given version name
*
* @return the run directory
*/
public abstract File getRunDirectory(String id);
/**
* Get the libraries that need to download.
*
* @param type where to download
*
* @return the library collection
*/
public abstract List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType type);
@ -57,11 +62,12 @@ public abstract class IMinecraftProvider {
public abstract void open(String version, String folder);
public abstract File getAssets();
public abstract List<ModInfo> listMods();
/**
* Returns the thing like ".minecraft/resourcepacks".
*
* @return the thing
*/
public abstract File getResourcePacks();
@ -84,63 +90,78 @@ public abstract class IMinecraftProvider {
* Provide the Minecraft Loader to generate the launching command.
*
* @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
*
* @return what you want
*
* @throws IllegalStateException circular denpendency versions
*/
public abstract IMinecraftLoader provideMinecraftLoader(UserProfileProvider p, DownloadType type) throws IllegalStateException;
/**
* Rename version
*
* @param from The old name
* @param to The new name
* @param to The new name
*
* @return Is the action successful?
*/
public abstract boolean renameVersion(String from, String to);
/**
* Remove the given version from disk.
*
* @param a the version name
*
* @return Is the action successful?
*/
public abstract boolean removeVersionFromDisk(String a);
/**
* Redownload the Minecraft json of the given version.
*
* @param a the given version name
*
* @return Is the action successful?
*/
public abstract boolean refreshJson(String a);
/**
* Redownload the Asset index json of the given version.
*
* @param a the given version name
*
* @return Is the action successful?
*/
public abstract boolean refreshAssetsIndex(String a);
/**
* Choose a version randomly.
*
* @return the version
*/
public abstract MinecraftVersion getOneVersion();
/**
* All Minecraft version in this profile.
*
* @return the collection of all Minecraft version
*/
public abstract Collection<MinecraftVersion> getVersions();
/**
* Get the Minecraft json instance of given version.
*
* @param id the given version name
*
* @return the Minecraft json instance
*/
public abstract MinecraftVersion getVersionById(String id);
/**
* getVersions().size()
*
* @return getVersions().size()
*/
public abstract int getVersionCount();
@ -152,8 +173,10 @@ public abstract class IMinecraftProvider {
/**
* Install a new version to this profile.
*
* @param version the new version name
* @param type where to download
* @param type where to download
*
* @return Is the action successful?
*/
public abstract boolean install(String version, DownloadType type);

View File

@ -36,7 +36,8 @@ public class LaunchScriptFinisher implements Event<List<String>> {
boolean flag = false;
try {
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;
} catch (IOException ex) {
MessageBox.Show(C.i18n("mainwindow.make_launch_script_failed"));

View File

@ -71,7 +71,7 @@ public class LibraryDownloadTask extends FileDownloadTask {
return false;
}
}
boolean download(URL url, File filePath) {
this.url = url;
this.filePath = filePath;
@ -79,7 +79,7 @@ public class LibraryDownloadTask extends FileDownloadTask {
}
public static void unpackLibrary(File output, File input)
throws IOException {
throws IOException {
HMCLog.log("Unpacking " + input);
if (output.exists())
output.delete();

View File

@ -67,7 +67,8 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
}
library += IOUtils.tryGetCanonicalFilePath(provider.getMinecraftJar()) + File.pathSeparator;
library = library.substring(0, library.length() - File.pathSeparator.length());
if (v.isCanceledWrapper()) res.add("-cp");
if (v.isCanceledWrapper())
res.add("-cp");
res.add(library);
String mainClass = version.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);
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) -> {
if (value != null)
TaskWindow.getInstance().addTask(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(dt.getProvider())).start();
});
}
if (value != null)
TaskWindow.getInstance().addTask(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(dt.getProvider())).start();
});
String game_assets = reconstructAssets().getAbsolutePath();
@ -133,7 +133,8 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
try {
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())
if (!new File(new File(objectDir, ((AssetsObject) entry.getValue()).getHash().substring(0, 2)), ((AssetsObject) entry.getValue()).getHash()).exists())
return false;
@ -159,7 +160,8 @@ public class MinecraftLoader extends AbstractMinecraftLoader {
try {
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()) {
int cnt = 0;
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 (cnt * 10 < tot) return assetsDir;
if (cnt * 10 < tot)
return assetsDir;
}
} catch (IOException | JsonSyntaxException e) {
HMCLog.warn("Failed to create virutal assets.", e);

View File

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

View File

@ -69,7 +69,7 @@ public final class Settings {
e.checkFormat();
UPDATE_CHECKER = new UpdateChecker(new VersionNumber(Main.firstVer, Main.secondVer, Main.thirdVer),
"hmcl", Main::invokeUpdate);
"hmcl", Main::invokeUpdate);
List<Java> temp = new ArrayList<>();
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.");
else {
Config d = C.gsonPrettyPrinting.fromJson(str, Config.class);
if (d != null) c = d;
if (d != null)
c = d;
}
HMCLog.log("Initialized settings.");
} catch (IOException | JsonSyntaxException e) {

View File

@ -60,7 +60,7 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
t.printStackTrace();
}
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"));
try {
MessageBox.Show(C.i18n("crash.NoClassDefFound"));
@ -68,7 +68,7 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
t.printStackTrace();
}
return false;
} else if(s.contains("java.lang.OutOfMemoryError")) {
} else if (s.contains("java.lang.OutOfMemoryError")) {
System.out.println("FUCKING MEMORY LIMIT!");
return false;
}
@ -78,7 +78,8 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
String s = StrUtils.getStackTrace(e);
if (!s.contains("org.jackhuang.hellominecraft")) return;
if (!s.contains("org.jackhuang.hellominecraft"))
return;
try {
String text = "\n---- Hello Minecraft! Crash Report ----\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 += " 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";
if (enableLogger) HMCLog.err(text);
else System.out.println(text);
if (enableLogger)
HMCLog.err(text);
else
System.out.println(text);
if (checkThrowable(e)) {
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<>();
void reportToServer(String text, String stacktrace) {
if (throwableSet.contains(stacktrace)) return;
if (throwableSet.contains(stacktrace))
return;
throwableSet.add(stacktrace);
new Thread(() -> {
HashMap<String, String> map = new HashMap<>();

View File

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

View File

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

View File

@ -107,7 +107,8 @@ public class AssetsMojangLoader extends IAssetsHandler {
@Override
public boolean isVersionAllowed(String 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;
}
}

View File

@ -63,9 +63,10 @@ public class AssetsMojangOldLoader extends IAssetsHandler {
@Override
public boolean isVersionAllowed(String 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
&& VersionNumber.check("1.6.0").compareTo(r) <= 0;
&& VersionNumber.check("1.6.0").compareTo(r) <= 0;
}
@Override

View File

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

View File

@ -70,7 +70,7 @@ public abstract class IAssetsHandler {
*
* @param mv The version that needs assets
* @param mp The Minecraft Provider
* @param x finished event
* @param x finished event
*/
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".
*
* @param sourceType Download Source
*
* @return Download File Task
*/
public abstract Task getDownloadTask(IDownloadProvider sourceType);
@ -106,8 +107,10 @@ public abstract class IAssetsHandler {
String mark = assetsDownloadURLs.get(i);
String url = u + mark;
File location = assetsLocalNames.get(i);
if (!location.getParentFile().exists()) location.getParentFile().mkdirs();
if (location.isDirectory()) continue;
if (!location.getParentFile().exists())
location.getParentFile().mkdirs();
if (location.isDirectory())
continue;
boolean need = true;
try {
if (location.exists()) {
@ -126,7 +129,8 @@ public abstract class IAssetsHandler {
HMCLog.warn("Failed to get hash: " + location, e);
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;
}

View File

@ -42,7 +42,7 @@ public abstract class IAuthenticator {
YGGDRASIL_LOGIN.onLoadSettings(Settings.getInstance().getYggdrasilConfig());
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
*
* @param info username & password
*
* @return login result
*/
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 {
if ($char == null)
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
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
@ -61,53 +61,53 @@ public final class SkinmeAuthenticator extends IAuthenticator {
String hashCode = DigestUtils.sha1Hex(DigestUtils.md5Hex(DigestUtils.sha1Hex(pwd) + pwd) + str);
String data = getCharacter(usr, hashCode, null);
String[] sl = data.split(":");
if (null != sl[0]) switch (sl[0]) {
case "0":
req.setSuccess(false);
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) {
if (null != sl[0])
switch (sl[0]) {
case "0":
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]);
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.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");
return req;

View File

@ -70,7 +70,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
ua.setUsername(usr);
try {
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[] profiles = ua.getAvailableProfiles();
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.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()));
String authToken = ua.getAuthenticatedToken();
if (authToken == null) authToken = "0";
if (authToken == null)
authToken = "0";
result.setAccessToken(authToken);
result.setSession(authToken);
} catch (Exception ex) {
@ -123,7 +125,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
}
public void onLoadSettings(Map settings) {
if (settings == null) return;
if (settings == null)
return;
ua.loadFromStorage(settings);
}
@ -132,7 +135,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
UserProfileProvider info = new UserProfileProvider();
try {
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();
info.setUserName(profile.name);
info.setSuccess(true);

View File

@ -12,7 +12,7 @@ public class AuthenticationRequest {
agent = new HashMap<>();
agent.put("name", "Minecraft");
agent.put("version", 1);
this.username = username;
this.password = password;
this.clientToken = clientToken;

View File

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

View File

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

View File

@ -8,7 +8,7 @@ public class Response {
public GameProfile selectedProfile;
public GameProfile[] availableProfiles;
public User user;
public String error;
public String errorMessage;
public String cause;

View File

@ -15,16 +15,16 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
import org.jackhuang.hellominecraft.utils.StrUtils;
public class YggdrasilAuthentication {
public static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(GameProfile.class, new GameProfile.GameProfileSerializer())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
.registerTypeAdapter(GameProfile.class, new GameProfile.GameProfileSerializer())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
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_REFRESH = NetUtils.constantURL(BASE_URL + "refresh");
protected static final String STORAGE_KEY_ACCESS_TOKEN = "accessToken";
protected static final String STORAGE_KEY_PROFILE_NAME = "displayName";
protected static final String STORAGE_KEY_PROFILE_ID = "uuid";
@ -32,11 +32,11 @@ public class YggdrasilAuthentication {
protected static final String STORAGE_KEY_USER_NAME = "username";
protected static final String STORAGE_KEY_USER_ID = "userid";
protected static final String STORAGE_KEY_USER_PROPERTIES = "userProperties";
private final Proxy proxy;
private final String clientToken;
private final PropertyMap userProperties = new PropertyMap();
private String userid, username, password, accessToken;
private GameProfile selectedProfile;
private GameProfile[] profiles;
@ -48,7 +48,6 @@ public class YggdrasilAuthentication {
}
// <editor-fold defaultstate="collapsed" desc="Get/Set">
public void setUsername(String username) {
if ((isLoggedIn()) && (canPlayOnline()))
throw new IllegalStateException("Cannot change username while logged in & online");
@ -104,7 +103,7 @@ public class YggdrasilAuthentication {
protected void setUserId(String userid) {
this.userid = userid;
}
public Proxy getProxy() {
return this.proxy;
}
@ -120,22 +119,20 @@ public class YggdrasilAuthentication {
@Deprecated
public String getSessionToken() {
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;
}
public String getAuthenticatedToken() {
return this.accessToken;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Log In/Out">
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Log In/Out">
public boolean canPlayOnline() {
return isLoggedIn() && getSelectedProfile() != null && this.isOnline;
}
public boolean canLogIn() {
return !canPlayOnline() && StrUtils.isNotBlank(getUsername()) && (StrUtils.isNotBlank(getPassword()) || StrUtils.isNotBlank(getAuthenticatedToken()));
}
@ -209,7 +206,6 @@ public class YggdrasilAuthentication {
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Settings Storage">
public void loadFromStorage(Map<String, Object> credentials) {
logOut();
@ -257,9 +253,8 @@ public class YggdrasilAuthentication {
return result;
}
// </editor-fold>
protected Response request(URL url, Object input) throws AuthenticationException {
try {
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
public InstallerVersionList getInstallerByType(String type) {
if (type.equalsIgnoreCase("forge")) return getForgeInstaller();
if (type.equalsIgnoreCase("liteloader")) return getLiteLoaderInstaller();
if (type.equalsIgnoreCase("optifine")) return getOptiFineInstaller();
if (type.equalsIgnoreCase("forge"))
return getForgeInstaller();
if (type.equalsIgnoreCase("liteloader"))
return getLiteLoaderInstaller();
if (type.equalsIgnoreCase("optifine"))
return getOptiFineInstaller();
return null;
}

View File

@ -41,7 +41,7 @@ public interface IDownloadProvider {
String getVersionsListDownloadURL();
String getAssetsDownloadURL();
String getParsedLibraryDownloadURL(String str);
boolean isAllowedToUseSelfURL();

View File

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

View File

@ -46,11 +46,10 @@ public class RapidDataDownloadProvider extends MojangDownloadProvider {
public String getVersionsListDownloadURL() {
return "http://mirrors.rapiddata.org/Minecraft.Download/versions/versions.json";
}
@Override
public String getParsedLibraryDownloadURL(String str) {
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.
*
* @param versions Minecraft versions you need to refresh
*
* @throws java.lang.Exception
*/
public abstract void refreshList(String[] versions) throws Exception;

View File

@ -40,7 +40,8 @@ public class PackMinecraftInstaller {
public void install() throws IOException {
File file = new File(IOUtils.currentDir(), "HMCL-MERGE-TEMP");
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);
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");
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");
/*for (MinecraftLibrary library : profile.versionInfo.libraries)
if (library.name.startsWith("net.minecraftforge:forge:"))
@ -98,7 +98,8 @@ public class ForgeInstaller extends Task {
try (FileOutputStream fos = new FileOutputStream(file)) {
BufferedOutputStream bos = new BufferedOutputStream(fos);
int c;
while ((c = is.read()) != -1) bos.write((byte) c);
while ((c = is.read()) != -1)
bos.write((byte) c);
bos.close();
}
return true;

View File

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

View File

@ -49,7 +49,8 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
@Override
public void refreshList(String[] needed) throws Exception {
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);
@ -96,10 +97,13 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
@Override
public List<InstallerVersion> getVersions(String mcVersion) {
if (versions == null || versionMap == null) return null;
if (StrUtils.isBlank(mcVersion)) return versions;
if (versions == null || versionMap == null)
return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion);
if (c == null) return versions;
if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c;
}

View File

@ -55,7 +55,8 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrar
setFailReason(new RuntimeException(C.i18n("install.no_version")));
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)
installer = pre.get(pre.size() - 1).getResult();
try {

View File

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

View File

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

View File

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

View File

@ -41,7 +41,8 @@ public class OptiFineDownloadFormatter extends Task implements PreviousResult<St
String content = NetUtils.doGet(url);
Pattern p = Pattern.compile("\"downloadx\\?f=OptiFine(.*)\"");
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;
return true;
} catch (Exception ex) {

View File

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

View File

@ -64,11 +64,13 @@ public class Upgrader extends Task {
HashMap<String, String> json = new HashMap<>();
File f = getSelf(newestVersion);
try {
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");
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");
f.createNewFile();
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(f))) {
Pack200.newUnpacker().unpack(new XZInputStream(new FileInputStream(tempFile)), jos);
}

View File

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

View File

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

View File

@ -95,18 +95,21 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
File version = new File(baseFolder, "versions");
File[] files = version.listFiles();
if (files == null || files.length == 0) return;
if (files == null || files.length == 0)
return;
for (File dir : files) {
String id = dir.getName();
File jsonFile = new File(dir, id + ".json");
if (!dir.isDirectory()) continue;
if (!dir.isDirectory())
continue;
boolean ask = false;
File[] jsons = null;
if (!jsonFile.exists()) {
jsons = FileUtils.searchSuffix(dir, "json");
if (jsons.length == 1) ask = true;
if (jsons.length == 1)
ask = true;
}
if (ask) {
HMCLog.warn("Found not matched filenames version: " + id + ", json: " + jsons[0].getName());
@ -121,20 +124,23 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
MinecraftVersion mcVersion;
try {
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) {
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) {
refreshJson(id);
try {
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) {
HMCLog.err("Retried but still failed.");
HMCLog.warn("Ignoring: " + dir + ", the json of this Minecraft is malformed.", ex);
continue;
}
} else continue;
} else
continue;
}
try {
if (!id.equals(mcVersion.id)) {
@ -156,7 +162,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override
public boolean removeVersionFromDisk(String name) {
File version = new File(baseFolder, "versions/" + name);
if (!version.exists()) return true;
if (!version.exists())
return true;
versions.remove(name);
return FileUtils.deleteDirectoryQuietly(version);
@ -192,7 +199,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override
public boolean refreshAssetsIndex(String 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());
}
@ -218,7 +226,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override
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");
ArrayList<ModInfo> mods = new ArrayList<>();
File[] fs = modsFolder.listFiles();
@ -245,7 +254,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override
public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) {
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());
if (v.libraries != null)
for (IMinecraftLibrary l : v.libraries) {
@ -281,7 +291,8 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override
public GameLauncher.DecompressLibraryJob getDecompressLibraries() {
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<String[]> extractRules = new ArrayList<>();
for (IMinecraftLibrary l : v.libraries) {
@ -307,7 +318,7 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override
public IMinecraftLoader provideMinecraftLoader(UserProfileProvider p, DownloadType type)
throws IllegalStateException {
throws IllegalStateException {
return new MinecraftLoader(profile, this, p, type);
}
@ -334,6 +345,7 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override
public void onLaunch() {
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
*/
public class DraggableFrame extends JFrame
implements MouseListener, MouseMotionListener {
implements MouseListener, MouseMotionListener {
private int dragGripX;
private int dragGripY;
@SuppressWarnings("LeakingThisInConstructor")
public DraggableFrame() {
setUndecorated(true);
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.addActionListener((e) -> {
Profile v = getProfile();
if (v != null) v.getMinecraftProvider().openSelf(mcVersion);
if (v != null)
v.getMinecraftProvider().openSelf(mcVersion);
});
ppmExplore.add(itm);
itm = new JMenuItem(C.i18n("folder.mod"));
@ -227,13 +228,19 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
@Override
public void stateChanged(ChangeEvent e) {
switch (tabInstallers.getSelectedIndex()) {
case 0: if (!a) forge.refreshVersions();
case 0:
if (!a)
forge.refreshVersions();
a = true;
break;
case 1: if (!b) optifine.refreshVersions();
case 1:
if (!b)
optifine.refreshVersions();
b = true;
break;
case 2: if (!c) liteloader.refreshVersions();
case 2:
if (!c)
liteloader.refreshVersions();
c = true;
break;
}
@ -242,8 +249,10 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
for (Java j : Settings.JAVA) {
String name = j.getName();
if (name.equals("Default")) name = C.i18n("settings.default");
if (name.equals("Custom")) name = C.i18n("settings.custom");
if (name.equals("Default"))
name = C.i18n("settings.default");
if (name.equals("Custom"))
name = C.i18n("settings.custom");
cboJava.addItem(name);
}
@ -1122,7 +1131,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}// </editor-fold>//GEN-END:initComponents
// <editor-fold defaultstate="collapsed" desc="UI Events">
private void cboProfilesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboProfilesItemStateChanged
if (isLoading) return;
if (isLoading)
return;
profile = getProfile();
if (profile.getMinecraftProvider().getVersionCount() <= 0)
versionChanged(profile, null);
@ -1136,8 +1146,10 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_btnNewProfileActionPerformed
private void btnRemoveProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveProfileActionPerformed
if (profile == null) return;
if (MessageBox.Show(C.i18n("ui.message.sure_remove", profile.getName()), MessageBox.YES_NO_OPTION) == MessageBox.NO_OPTION) return;
if (profile == null)
return;
if (MessageBox.Show(C.i18n("ui.message.sure_remove", profile.getName()), MessageBox.YES_NO_OPTION) == MessageBox.NO_OPTION)
return;
if (Settings.delProfile(profile)) {
cboProfiles.removeItem(profile.getName());
profile = Settings.getOneProfile();
@ -1180,9 +1192,9 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
if (v.installer != null) {
url = Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(v.installer);
TaskWindow.getInstance()
.addTask(new FileDownloadTask(url, filepath).setTag("forge"))
.addTask(new ForgeInstaller(profile.getMinecraftProvider(), filepath, v))
.start();
.addTask(new FileDownloadTask(url, filepath).setTag("forge"))
.addTask(new ForgeInstaller(profile.getMinecraftProvider(), filepath, v))
.start();
refreshVersions();
}
}//GEN-LAST:event_btnDownloadForgeActionPerformed
@ -1203,9 +1215,9 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
SwingUtilities.invokeLater(() -> {
OptiFineDownloadFormatter task = new OptiFineDownloadFormatter(v.installer);
TaskWindow.getInstance().addTask(task)
.addTask(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.addTask(new OptiFineInstaller(profile, v.selfVersion, filepath))
.start();
.addTask(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.addTask(new OptiFineInstaller(profile, v.selfVersion, filepath))
.start();
refreshVersions();
});
}//GEN-LAST:event_btnDownloadOptifineActionPerformed
@ -1222,8 +1234,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
url = v.universal;
FileDownloadTask task = (FileDownloadTask) new FileDownloadTask(url, filepath).setTag("LiteLoader");
TaskWindow.getInstance()
.addTask(task).addTask(new LiteLoaderInstaller(profile, (LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.start();
.addTask(task).addTask(new LiteLoaderInstaller(profile, (LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.start();
refreshVersions();
}//GEN-LAST:event_btnInstallLiteLoaderActionPerformed
@ -1332,13 +1344,15 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_txtWidthFocusLost
private void txtGameDirFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtGameDirFocusLost
if (profile == null) return;
if (profile == null)
return;
profile.setGameDir(txtGameDir.getText());
loadVersions();
}//GEN-LAST:event_txtGameDirFocusLost
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();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setDialogTitle(C.i18n("settings.choose_javapath"));
@ -1376,25 +1390,29 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setDialogTitle(C.I18N.getString("mods.choose_mod"));
fc.setMultiSelectionEnabled(true);
if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
return;
boolean flag = false;
for (File f : fc.getSelectedFiles())
if (!addMod(f)) flag |= true;
if (!addMod(f))
flag |= true;
if (flag)
MessageBox.Show(C.I18N.getString("mods.failed"));
}//GEN-LAST:event_btnAddModActionPerformed
boolean addMod(File f) {
try {
if (!ModInfo.isFileMod(f) || mods == null) return false;
if (!ModInfo.isFileMod(f) || mods == null)
return false;
File newf = profile.getFolder("mods");
if (newf == null) return false;
if (newf == null)
return false;
newf.mkdirs();
newf = new File(newf, f.getName());
FileUtils.copyFile(f, newf);
ModInfo i = ModInfo.readModInfo(f);
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;
} catch (IOException 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
File f = getProfile().getMinecraftProvider().getRunDirectory(mcVersion);
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"};
for (String s : files) new File(f, s).delete();
for (String s : files)
new File(f, s).delete();
for (MinecraftVersion s : getProfile().getMinecraftProvider().getVersions())
FileUtils.deleteDirectoryQuietly(new File(getProfile().getGameDirFile(), "versions" + File.separator + s.id + File.separator + s.id + "-natives"));
}//GEN-LAST:event_btnCleanGameActionPerformed
@ -1475,7 +1495,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
Profile firstProfile = null, selectedProfile = null;
int index = 0, i = 0;
for (Profile s : Settings.getProfilesFiltered()) {
if (firstProfile == null) firstProfile = s;
if (firstProfile == null)
firstProfile = s;
cboProfiles.addItem(s.getName());
if (Settings.getInstance().getLast() != null && Settings.getInstance().getLast().equals(s.getName())) {
index = i;
@ -1483,13 +1504,15 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}
i++;
}
if (selectedProfile == null) selectedProfile = Settings.getOneProfile();
if (selectedProfile == null)
selectedProfile = Settings.getOneProfile();
isLoading = false;
if (index < cboProfiles.getItemCount()) {
cboProfiles.setSelectedIndex(index);
profile = selectedProfile;
if (profile == null) profile = firstProfile;
if (profile == null)
profile = firstProfile;
prepare(profile);
loadVersions();
}
@ -1498,11 +1521,13 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
final Profile getProfile() {
if (cboProfiles.getSelectedIndex() >= 0)
return Settings.getProfile(cboProfiles.getSelectedItem().toString());
else return null;
else
return null;
}
void prepare(Profile profile) {
if (profile == null) return;
if (profile == null)
return;
txtWidth.setText(profile.getWidth());
txtHeight.setText(profile.getHeight());
txtMaxMemory.setText(profile.getMaxMemory());
@ -1530,7 +1555,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}
void loadVersions() {
if (profile == null) return;
if (profile == null)
return;
isLoading = true;
cboVersions.removeAllItems();
int index = 0, i = 0;
@ -1538,11 +1564,13 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
String selectedMC = selVersion == null ? null : selVersion.id;
for (MinecraftVersion each : profile.getMinecraftProvider().getVersions()) {
cboVersions.addItem(each.id);
if (each.id.equals(selectedMC)) index = i;
if (each.id.equals(selectedMC))
index = i;
i++;
}
isLoading = false;
if (index < cboVersions.getItemCount()) cboVersions.setSelectedIndex(index);
if (index < cboVersions.getItemCount())
cboVersions.setSelectedIndex(index);
reloadMods();
}
@ -1563,7 +1591,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
*/
void loadMinecraftVersion(MinecraftVersion v) {
txtMinecraftVersion.setText("");
if (v == null) return;
if (v == null)
return;
File minecraftJar = v.getJar(profile.getGameDirFile());
minecraftVersion = MCUtils.minecraftVersion(minecraftJar);
txtMinecraftVersion.setText(MinecraftVersionRequest.getResponse(minecraftVersion));
@ -1573,11 +1602,12 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
public int assetsType;
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) -> {
if (value != null)
SwingUtilities.invokeLater(() -> TaskWindow.getInstance().addTask(type.getDownloadTask(Settings.getInstance().getDownloadSource().getProvider())).start());
});
if (value != null)
SwingUtilities.invokeLater(() -> TaskWindow.getInstance().addTask(type.getDownloadTask(Settings.getInstance().getDownloadSource().getProvider())).start());
});
}
// </editor-fold>
@ -1593,14 +1623,16 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
return true;
SwingUtilities.invokeLater(() -> {
DefaultTableModel model = (DefaultTableModel) lstDownloads.getModel();
while (model.getRowCount() > 0) model.removeRow(0);
while (model.getRowCount() > 0)
model.removeRow(0);
for (MinecraftRemoteVersion ver : v.versions) {
Object[] line = new Object[3];
line[0] = ver.id;
line[1] = ver.time;
if (StrUtils.equalsOne(ver.type, "old_beta", "old_alpha", "release", "snapshot"))
line[2] = C.i18n("versions." + ver.type);
else line[2] = ver.type;
else
line[2] = ver.type;
model.addRow(line);
}
lstDownloads.updateUI();
@ -1621,7 +1653,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}
void downloadMinecraft(DownloadType index) {
if (profile == null) return;
if (profile == null)
return;
if (lstDownloads.getSelectedRow() < 0)
refreshDownloads(Settings.getInstance().getDownloadSource());
if (lstDownloads.getSelectedRow() < 0) {
@ -1687,8 +1720,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
void refreshVersions() {
list = Settings.getInstance().getDownloadSource().getProvider().getInstallerByType(id);
if (TaskWindow.getInstance().addTask(new TaskRunnableArg1<>(C.i18n("install." + id + ".get_list"), list)
.registerPreviousResult(new DefaultPreviousResult<>(new String[]{getMinecraftVersionFormatted()})))
.start())
.registerPreviousResult(new DefaultPreviousResult<>(new String[] {getMinecraftVersionFormatted()})))
.start())
loadVersions();
}
@ -1708,7 +1741,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
for (InstallerVersionList.InstallerVersion v : ver) {
Object a = v.selfVersion == null ? "null" : v.selfVersion;
Object b = v.mcVersion == null ? "null" : v.mcVersion;
Object[] row = new Object[]{a, b};
Object[] row = new Object[] {a, b};
model.addRow(row);
}
table.updateUI();
@ -1744,7 +1777,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
SwingUtils.clearDefaultTable(lstExternalMods);
DefaultTableModel model = (DefaultTableModel) lstExternalMods.getModel();
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,12 +1796,14 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
public void onSelected() {
loadProfiles();
if (profile == null) return;
if (profile == null)
return;
if (profile.getMinecraftProvider().getVersionCount() <= 0)
versionChanged(profile, null);
else versionChanged(getProfile(), (String) cboVersions.getSelectedItem());
else
versionChanged(getProfile(), (String) cboVersions.getSelectedItem());
}
public void showGameDownloads() {
tabVersionEdit.setSelectedComponent(pnlGameDownloads);
}

View File

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

View File

@ -39,7 +39,7 @@ public class LauncherSettingsPanel extends javax.swing.JPanel {
*/
public LauncherSettingsPanel() {
initComponents();
String[] strings = new String[DownloadType.values().length];
for (int i = 0; i < strings.length; i++)
strings[i] = DownloadType.values()[i].getName();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -73,7 +73,7 @@ public enum Level {
level = DEBUG;
} else {
if (line.contains("[INFO]") || line.contains("[CONFIG]") || line.contains("[FINE]")
|| line.contains("[FINER]") || line.contains("[FINEST]"))
|| line.contains("[FINER]") || line.contains("[FINEST]"))
level = INFO;
if (line.contains("[SEVERE]") || line.contains("[STDERR]"))
level = ERROR;
@ -84,12 +84,12 @@ public enum Level {
}
if (line.contains("overwriting existing"))
return FATAL;
if (line.contains("Exception in thread")
|| line.matches("\\s+at " + 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("... \\d+ more$"))
|| line.matches("\\s+at " + 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("... \\d+ more$"))
return ERROR;
return level;
}

View File

@ -23,10 +23,10 @@ import org.jackhuang.hellominecraft.logging.message.IMessage;
* @author huangyuhui
*/
public class LogEvent {
public Level level;
public String threadName;
public Throwable thrown;
public IMessage message;
}

View File

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

View File

@ -30,27 +30,27 @@ public abstract class AbstractAppender implements IAppender {
private final boolean ignoreExceptions;
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) {
this.name = name;
this.layout = layout;
this.ignoreExceptions = ignoreExceptions;
this.name = name;
this.layout = layout;
this.ignoreExceptions = ignoreExceptions;
}
@Override
public String getName() {
return name;
return name;
}
@Override
public boolean ignoreExceptions() {
return ignoreExceptions;
return ignoreExceptions;
}
@Override
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 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 {
@Override
public void close() {
}
@Override
public void close() {
}
@Override
public void flush() {
System.out.flush();
}
@Override
public void flush() {
System.out.flush();
}
@Override
public void write(byte[] b) throws IOException {
System.out.write(b);
}
@Override
public void write(byte[] b) throws IOException {
System.out.write(b);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.out.write(b, off, len);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.out.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
System.out.write(b);
}
@Override
public void write(int b) throws IOException {
System.out.write(b);
}
}
public static class SystemErrStream extends OutputStream {
@Override
public void close() {
}
@Override
public void close() {
}
@Override
public void flush() {
System.err.flush();
}
@Override
public void flush() {
System.err.flush();
}
@Override
public void write(byte[] b) throws IOException {
System.err.write(b);
}
@Override
public void write(byte[] b) throws IOException {
System.err.write(b);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.err.write(b, off, len);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.err.write(b, off, len);
}
@Override
public void write(int b) {
System.err.write(b);
}
@Override
public void write(int b) {
System.err.write(b);
}
}
}

View File

@ -25,10 +25,13 @@ import org.jackhuang.hellominecraft.logging.layout.ILayout;
* @author huangyuhui
*/
public interface IAppender {
void append(LogEvent event);
String getName();
boolean ignoreExceptions();
ILayout<? extends Serializable> getLayout();
}

View File

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

View File

@ -26,7 +26,7 @@ public abstract class AbstractStringLayout implements ILayout<String> {
@Override
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
*/
public class DefaultLayout extends AbstractStringLayout {
private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
@Override
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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -42,9 +42,9 @@ public abstract class Task {
aborted = true;
return false;
}
protected boolean aborted = false;
public boolean isAborted() {
return aborted;
}
@ -73,7 +73,7 @@ public abstract class Task {
public void setParallelExecuting(boolean parallelExecuting) {
this.parallelExecuting = parallelExecuting;
}
ArrayList<DoingDoneListener<Task>> taskListener = new ArrayList();
public Task addTaskListener(DoingDoneListener<Task> l) {
@ -94,7 +94,7 @@ public abstract class Task {
public Collection<Task> getAfterTasks() {
return null;
}
protected ProgressProviderListener ppl;
public Task setProgressProviderListener(ProgressProviderListener p) {

View File

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

View File

@ -27,7 +27,9 @@ import org.jackhuang.hellominecraft.utils.functions.Consumer;
* @param <T> Runnable&lt;T&gt;
*/
public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegistrar<T> {
private final Consumer<T> r;
public TaskRunnableArg1(String info, Consumer<T> r) {
super(info);
this.r = r;
@ -35,16 +37,17 @@ public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegis
@Override
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 {
r.accept(al.get(0).getResult());
return true;
} catch(Throwable t) {
} catch (Throwable t) {
setFailReason(t);
return false;
}
}
ArrayList<PreviousResult<T>> al = new ArrayList();
@Override
@ -52,7 +55,5 @@ public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegis
al.add(pr);
return this;
}
}
}

View File

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

View File

@ -22,7 +22,7 @@ package org.jackhuang.hellominecraft.tasks.communication;
* @param <T> Task result type
*/
public interface PreviousResult<T> {
T getResult();
}

View File

@ -24,10 +24,11 @@ import org.jackhuang.hellominecraft.tasks.Task;
* @param <T> Previous task result type
*/
public interface PreviousResultRegistrar<T> {
/**
*
*
* @param pr previous task handler
*
* @return task self instance
*/
Task registerPreviousResult(PreviousResult<T> pr);

View File

@ -37,7 +37,7 @@ public class ContentGetAndShowTask extends HTTPGetTask implements Event<String>
}
String info;
@Override
public String getInfo() {
return info;

View File

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

View File

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

View File

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

View File

@ -21,17 +21,17 @@ package org.jackhuang.hellominecraft.tasks.download;
* @author huangyuhui
*/
public class NetException extends RuntimeException {
public NetException(Exception message) {
super(message);
}
public NetException(String message) {
super(message);
}
public NetException(String message, Exception e) {
super(message, e);
}
}

View File

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

View File

@ -29,14 +29,16 @@ import java.util.Iterator;
public final class CollectionUtils {
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) {
ArrayList<T> newColl = new ArrayList<>();
forEach(coll, t -> {
if (p.apply(t)) newColl.add(t);
});
if (p.apply(t))
newColl.add(t);
});
return newColl;
}

View File

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

View File

@ -27,7 +27,7 @@ import org.jackhuang.hellominecraft.views.LogWindow;
* @author huangyuhui
*/
public class LogWindowOutputStream extends OutputStream {
private static final Timer TIMER = new Timer();
private final LogWindow txt;
@ -84,9 +84,9 @@ public class LogWindowOutputStream extends OutputStream {
@Override
public final void write(int paramInt) {
append(new String(new byte[]{(byte) paramInt}));
append(new String(new byte[] {(byte) paramInt}));
}
public static void dispose() {
TIMER.cancel();
}

View File

@ -44,9 +44,12 @@ public class MathUtils {
return Integer.parseInt(s);
} catch (Exception e) {
int a = parseInt(s.substring(0, s.length() - 1), def);
if (s.endsWith("g")) return a * 1024;
else if (s.endsWith("k")) return a / 1024;
else return a;
if (s.endsWith("g"))
return a * 1024;
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)
throws IOException {
throws IOException {
StringBuilder sb = new StringBuilder();
try (InputStreamReader br = new InputStreamReader(is, encoding)) {
int len;
@ -82,15 +82,16 @@ public final class NetUtils {
/**
* Sends an HTTP GET request to a url
*
* @param endpoint - The URL of the server. (Example: "
* http://www.yahoo.com/search")
* @param endpoint - The URL of the server. (Example: "
* http://www.yahoo.com/search")
* @param requestParameters - all the request parameters (Example:
* "param1=val1&param2=val2"). Note: This method will add the question mark
* (?) to the request - DO NOT add it yourself
* "param1=val1&param2=val2"). Note: This method will add the question mark
* (?) to the request - DO NOT add it yourself
*
* @return - The response from the end point
*/
public static String sendGetRequest(String endpoint,
String requestParameters) {
String requestParameters) {
String result = null;
if (endpoint.startsWith("http://"))
// Send a GET request to the servlet
@ -118,7 +119,7 @@ public final class NetUtils {
}
return result;
}
public static String post(URL u, Map<String, String> params) {
StringBuilder sb = new StringBuilder();
if (params != null) {
@ -136,11 +137,11 @@ public final class NetUtils {
public static String post(URL u, String post) {
return post(u, post, "application/x-www-form-urlencoded");
}
public static String post(URL u, String post, String contentType) {
return post(u, post, contentType, Proxy.NO_PROXY);
}
public static String post(URL u, String post, String contentType, Proxy proxy) {
try {
HttpURLConnection con = (HttpURLConnection) u.openConnection(proxy);
@ -157,16 +158,18 @@ public final class NetUtils {
os = con.getOutputStream();
IOUtils.write(post, os, DEFAULT_CHARSET);
} finally {
if (os != null) IOUtils.closeQuietly(os);
if (os != null)
IOUtils.closeQuietly(os);
}
String result = null;
InputStream is = null;
try {
is = con.getInputStream();
result = getStreamContent(is);
} catch(IOException ex) {
if (is != null) IOUtils.closeQuietly(is);
} catch (IOException ex) {
if (is != null)
IOUtils.closeQuietly(is);
is = con.getErrorStream();
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) {
byte[] b = src.getBytes();
String tgt = "";
for (int i = start_idx; i <= end_idx; i++) {
for (int i = start_idx; i <= end_idx; i++)
tgt += (char) b[i];
}
return tgt;
}
public static String makeCommand(List<String> cmd) {
StringBuilder cmdbuf = new StringBuilder(120);
for (int i = 0; i < cmd.size(); i++) {
if (i > 0) {
if (i > 0)
cmdbuf.append(' ');
}
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) != '"') {
cmdbuf.append('"');
cmdbuf.append(s);
if (s.endsWith("\\")) {
if (s.endsWith("\\"))
cmdbuf.append("\\");
}
cmdbuf.append('"');
} else if (s.endsWith("\"")) {
} else if (s.endsWith("\""))
/* The argument has already been quoted. */
cmdbuf.append(s);
} else {
else
/* Unmatched quote for the argument. */
throw new IllegalArgumentException();
}
} else {
else
cmdbuf.append(s);
}
}
String str = cmdbuf.toString();
@ -76,61 +71,49 @@ public final class StrUtils {
}
public static boolean startsWithOne(String[] a, String match) {
if (a == null) {
if (a == null)
return false;
}
for (String b : a) {
if (startsWith(match, b)) {
for (String b : a)
if (startsWith(match, b))
return true;
}
}
return false;
}
public static boolean equalsOne(String base, String... a) {
for (String s : a) {
if (base.equals(s)) {
for (String s : a)
if (base.equals(s))
return true;
}
}
return false;
}
public static boolean containsOne(List<String> base, List<String> match) {
for (String a : base) {
for (String b : match) {
if (a.toLowerCase().contains(b.toLowerCase())) {
for (String a : base)
for (String b : match)
if (a.toLowerCase().contains(b.toLowerCase()))
return true;
}
}
}
return false;
}
public static int getCharShowTime(String s, char c) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == c)
res++;
}
}
return res;
}
public static String formatVersion(String ver) {
if (isBlank(ver)) {
if (isBlank(ver))
return null;
} else {
for(char ch : ver.toCharArray()) {
if((ch < '0' || ch > '9') && ch != '.') return null;
}
}
else
for (char ch : ver.toCharArray())
if ((ch < '0' || ch > '9') && ch != '.')
return null;
int i = getCharShowTime(ver, '.');
if (i == 1) {
if (i == 1)
return ver + ".0";
} else {
else
return ver;
}
}
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) {
if (paramArrayOfObject == null) {
if (paramArrayOfObject == null)
return "";
}
StringBuilder localStringBuffer = new StringBuilder();
for (int i = 0; i < paramArrayOfObject.length; i++) {
Object localObject = paramArrayOfObject[i];
if (i > 0) {
if (i > 0)
localStringBuffer.append(addBefore).append(paramString);
}
if (localObject == null) {
if (localObject == null)
localStringBuffer.append("null");
} else if (localObject.getClass().isArray()) {
else if (localObject.getClass().isArray()) {
localStringBuffer.append("[");
if ((localObject instanceof Object[])) {
Object[] arrayOfObject = (Object[]) localObject;
localStringBuffer.append(parseParams(addBefore, arrayOfObject, paramString));
} else {
} else
for (int j = 0; j < Array.getLength(localObject); j++) {
if (j > 0) {
if (j > 0)
localStringBuffer.append(paramString);
}
localStringBuffer.append(addBefore).append(Array.get(localObject, j));
}
}
localStringBuffer.append("]");
} else {
} else
localStringBuffer.append(addBefore).append(paramArrayOfObject[i]);
}
}
return localStringBuffer.toString();
}
public static boolean isEquals(String base, String to) {
if (base == null) {
if (base == null)
return (to == null);
} else {
else
return base.equals(to);
}
}
public static Dimension parseDimension(String str) {
String[] tokenized = tokenize(str, "x,");
if (tokenized.length != 2) {
if (tokenized.length != 2)
return null;
}
int i = MathUtils.parseInt(tokenized[0], -1);
int j = MathUtils.parseInt(tokenized[1], -1);
if ((i < 0) || (j < 0)) {
if ((i < 0) || (j < 0))
return null;
}
return new Dimension(i, j);
}
@ -210,9 +185,8 @@ public final class StrUtils {
public static String trimExtension(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int i = filename.lastIndexOf('.');
if ((i > -1) && (i < (filename.length()))) {
if ((i > -1) && (i < (filename.length())))
return filename.substring(0, i);
}
}
return filename;
}

View File

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

View File

@ -60,7 +60,9 @@ public final class Utils {
Field field = ClassLoader.class.getDeclaredField("usr_paths");
field.setAccessible(true);
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];
System.arraycopy(paths, 0, tmp, 0, paths.length);
tmp[paths.length] = s;
@ -166,6 +168,7 @@ public final class Utils {
/**
* In order to fight against the permission manager by Minecraft Forge.
*
* @param status exit code
*/
public static void shutdownForcely(int status) {
@ -181,6 +184,7 @@ public final class Utils {
}
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
public int compareTo(VersionNumber o) {
if (isOlder(this, o)) return -1;
else if (isOlder(o, this)) return 1;
else return 0;
if (isOlder(this, o))
return -1;
else if (isOlder(o, this))
return 1;
else
return 0;
}
}

View File

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

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