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

View File

@@ -53,10 +53,14 @@ public final class Launcher {
ArrayList<String> cmdList = new ArrayList<>(); ArrayList<String> cmdList = new ArrayList<>();
for (String s : args) for (String s : args)
if (s.startsWith("-cp=")) classPath = classPath.concat(s.substring("-cp=".length())); if (s.startsWith("-cp="))
else if (s.startsWith("-mainClass=")) mainClass = s.substring("-mainClass=".length()); classPath = classPath.concat(s.substring("-cp=".length()));
else if (s.equals("-debug")) showInfo = true; else if (s.startsWith("-mainClass="))
else cmdList.add(s); mainClass = s.substring("-mainClass=".length());
else if (s.equals("-debug"))
showInfo = true;
else
cmdList.add(s);
String[] tokenized = StrUtils.tokenize(classPath, File.pathSeparator); String[] tokenized = StrUtils.tokenize(classPath, File.pathSeparator);
int len = tokenized.length; int len = tokenized.length;
@@ -65,7 +69,8 @@ public final class Launcher {
LogWindow.instance.setTerminateGame(() -> Utils.shutdownForcely(1)); LogWindow.instance.setTerminateGame(() -> Utils.shutdownForcely(1));
try { try {
File logFile = new File("hmclmc.log"); File logFile = new File("hmclmc.log");
if (!logFile.exists()) logFile.createNewFile(); if (!logFile.exists())
logFile.createNewFile();
FileOutputStream tc = new FileOutputStream(logFile); FileOutputStream tc = new FileOutputStream(logFile);
DoubleOutputStream out = new DoubleOutputStream(tc, System.out); DoubleOutputStream out = new DoubleOutputStream(tc, System.out);
System.setOut(new LauncherPrintStream(out)); System.setOut(new LauncherPrintStream(out));

View File

@@ -231,7 +231,8 @@ public final class Main implements Runnable {
url = map.get(OS.os().checked_name); url = map.get(OS.os().checked_name);
else if (map.containsKey(OS.UNKOWN.checked_name)) else if (map.containsKey(OS.UNKOWN.checked_name))
url = map.get(OS.UNKOWN.checked_name); url = map.get(OS.UNKOWN.checked_name);
if (url == null) url = C.URL_PUBLISH; if (url == null)
url = C.URL_PUBLISH;
try { try {
java.awt.Desktop.getDesktop().browse(new URI(url)); java.awt.Desktop.getDesktop().browse(new URI(url));
} catch (URISyntaxException | IOException e) { } catch (URISyntaxException | IOException e) {

View File

@@ -66,7 +66,8 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
JdkVersion jv = new JdkVersion(str); JdkVersion jv = new JdkVersion(str);
if (Settings.getInstance().getJava().contains(jv)) if (Settings.getInstance().getJava().contains(jv))
jv = Settings.getInstance().getJava().get(Settings.getInstance().getJava().indexOf(jv)); jv = Settings.getInstance().getJava().get(Settings.getInstance().getJava().indexOf(jv));
else try { else
try {
jv = JdkVersion.getJavaVersionFromExecutable(str); jv = JdkVersion.getJavaVersionFromExecutable(str);
Settings.getInstance().getJava().add(jv); Settings.getInstance().getJava().add(jv);
Settings.save(); Settings.save();
@@ -119,7 +120,8 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
MessageBox.Show(C.i18n("launch.too_big_memory_alloc_free_space_too_low", a)); MessageBox.Show(C.i18n("launch.too_big_memory_alloc_free_space_too_low", a));
} }
String a = "-Xmx" + v.getMaxMemory(); String a = "-Xmx" + v.getMaxMemory();
if (MathUtils.canParseInt(v.getMaxMemory())) a += "m"; if (MathUtils.canParseInt(v.getMaxMemory()))
a += "m";
res.add(a); res.add(a);
} }
@@ -164,9 +166,11 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
res.add(args.length > 1 ? args[1] : "25565"); res.add(args.length > 1 ? args[1] : "25565");
} }
if (v.isFullscreen()) res.add("--fullscreen"); if (v.isFullscreen())
res.add("--fullscreen");
if (v.isDebug() && !v.isCanceledWrapper()) res.add("-debug"); if (v.isDebug() && !v.isCanceledWrapper())
res.add("-debug");
if (StrUtils.isNotBlank(v.getMinecraftArgs())) if (StrUtils.isNotBlank(v.getMinecraftArgs()))
res.addAll(Arrays.asList(v.getMinecraftArgs().split(" "))); res.addAll(Arrays.asList(v.getMinecraftArgs().split(" ")));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -90,7 +90,8 @@ public final class Settings {
HMCLog.log("Settings file is empty, use the default settings."); HMCLog.log("Settings file is empty, use the default settings.");
else { else {
Config d = C.gsonPrettyPrinting.fromJson(str, Config.class); Config d = C.gsonPrettyPrinting.fromJson(str, Config.class);
if (d != null) c = d; if (d != null)
c = d;
} }
HMCLog.log("Initialized settings."); HMCLog.log("Initialized settings.");
} catch (IOException | JsonSyntaxException e) { } catch (IOException | JsonSyntaxException e) {

View File

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

View File

@@ -131,7 +131,8 @@ public final class MCUtils {
return r; return r;
} }
int k = i; int k = i;
while (tmp[k] >= 48 && tmp[k] <= 57 || tmp[k] == 46) k--; while (tmp[k] >= 48 && tmp[k] <= 57 || tmp[k] == 46)
k--;
k++; k++;
r.version = new String(tmp, k, i - k + 1); r.version = new String(tmp, k, i - k + 1);
} }
@@ -214,7 +215,8 @@ public final class MCUtils {
} }
public static String minecraft() { public static String minecraft() {
if (OS.os() == OS.OSX) return "minecraft"; if (OS.os() == OS.OSX)
return "minecraft";
return ".minecraft"; return ".minecraft";
} }
@@ -224,7 +226,8 @@ public final class MCUtils {
gameDir = new File(gameDir, MCUtils.minecraft()); gameDir = new File(gameDir, MCUtils.minecraft());
if (!gameDir.exists()) { if (!gameDir.exists()) {
File newFile = MCUtils.getLocation(); File newFile = MCUtils.getLocation();
if (newFile.exists()) gameDir = newFile; if (newFile.exists())
gameDir = newFile;
} }
} }
return gameDir; return gameDir;

View File

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

View File

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

View File

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

View File

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

View File

@@ -78,6 +78,7 @@ public abstract class IAssetsHandler {
* Will be invoked when the user invoked "Download all assets". * Will be invoked when the user invoked "Download all assets".
* *
* @param sourceType Download Source * @param sourceType Download Source
*
* @return Download File Task * @return Download File Task
*/ */
public abstract Task getDownloadTask(IDownloadProvider sourceType); public abstract Task getDownloadTask(IDownloadProvider sourceType);
@@ -106,8 +107,10 @@ public abstract class IAssetsHandler {
String mark = assetsDownloadURLs.get(i); String mark = assetsDownloadURLs.get(i);
String url = u + mark; String url = u + mark;
File location = assetsLocalNames.get(i); File location = assetsLocalNames.get(i);
if (!location.getParentFile().exists()) location.getParentFile().mkdirs(); if (!location.getParentFile().exists())
if (location.isDirectory()) continue; location.getParentFile().mkdirs();
if (location.isDirectory())
continue;
boolean need = true; boolean need = true;
try { try {
if (location.exists()) { if (location.exists()) {
@@ -126,7 +129,8 @@ public abstract class IAssetsHandler {
HMCLog.warn("Failed to get hash: " + location, e); HMCLog.warn("Failed to get hash: " + location, e);
need = !location.exists(); need = !location.exists();
} }
if (need) al.add(new FileDownloadTask(url, location).setTag(mark)); if (need)
al.add(new FileDownloadTask(url, location).setTag(mark));
} }
return true; return true;
} }

View File

@@ -56,6 +56,7 @@ public abstract class IAuthenticator {
* Login Method * Login Method
* *
* @param info username & password * @param info username & password
*
* @return login result * @return login result
*/ */
public abstract UserProfileProvider login(LoginInfo info); public abstract UserProfileProvider login(LoginInfo info);

View File

@@ -61,12 +61,12 @@ public final class SkinmeAuthenticator extends IAuthenticator {
String hashCode = DigestUtils.sha1Hex(DigestUtils.md5Hex(DigestUtils.sha1Hex(pwd) + pwd) + str); String hashCode = DigestUtils.sha1Hex(DigestUtils.md5Hex(DigestUtils.sha1Hex(pwd) + pwd) + str);
String data = getCharacter(usr, hashCode, null); String data = getCharacter(usr, hashCode, null);
String[] sl = data.split(":"); String[] sl = data.split(":");
if (null != sl[0]) switch (sl[0]) { if (null != sl[0])
switch (sl[0]) {
case "0": case "0":
req.setSuccess(false); req.setSuccess(false);
if(sl[1].contains("No Valid Character")) { if (sl[1].contains("No Valid Character"))
sl[1] = C.i18n("login.no_valid_character"); sl[1] = C.i18n("login.no_valid_character");
}
req.setErrorReason(sl[1]); req.setErrorReason(sl[1]);
break; break;
case "1": { case "1": {

View File

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

View File

@@ -48,7 +48,6 @@ public class YggdrasilAuthentication {
} }
// <editor-fold defaultstate="collapsed" desc="Get/Set"> // <editor-fold defaultstate="collapsed" desc="Get/Set">
public void setUsername(String username) { public void setUsername(String username) {
if ((isLoggedIn()) && (canPlayOnline())) if ((isLoggedIn()) && (canPlayOnline()))
throw new IllegalStateException("Cannot change username while logged in & online"); throw new IllegalStateException("Cannot change username while logged in & online");
@@ -129,9 +128,7 @@ public class YggdrasilAuthentication {
} }
// </editor-fold> // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Log In/Out"> // <editor-fold defaultstate="collapsed" desc="Log In/Out">
public boolean canPlayOnline() { public boolean canPlayOnline() {
return isLoggedIn() && getSelectedProfile() != null && this.isOnline; return isLoggedIn() && getSelectedProfile() != null && this.isOnline;
} }
@@ -209,7 +206,6 @@ public class YggdrasilAuthentication {
// </editor-fold> // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Settings Storage"> // <editor-fold defaultstate="collapsed" desc="Settings Storage">
public void loadFromStorage(Map<String, Object> credentials) { public void loadFromStorage(Map<String, Object> credentials) {
logOut(); logOut();
@@ -259,7 +255,6 @@ public class YggdrasilAuthentication {
} }
// </editor-fold> // </editor-fold>
protected Response request(URL url, Object input) throws AuthenticationException { protected Response request(URL url, Object input) throws AuthenticationException {
try { try {
String jsonResult = input == null ? NetUtils.doGet(url) : NetUtils.post(url, GSON.toJson(input), "application/json", proxy); String jsonResult = input == null ? NetUtils.doGet(url) : NetUtils.post(url, GSON.toJson(input), "application/json", proxy);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -98,7 +98,8 @@ public class ForgeInstaller extends Task {
try (FileOutputStream fos = new FileOutputStream(file)) { try (FileOutputStream fos = new FileOutputStream(file)) {
BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedOutputStream bos = new BufferedOutputStream(fos);
int c; int c;
while ((c = is.read()) != -1) bos.write((byte) c); while ((c = is.read()) != -1)
bos.write((byte) c);
bos.close(); bos.close();
} }
return true; return true;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -121,8 +121,10 @@ public class MinecraftLibrary extends IMinecraftLibrary {
@Override @Override
public String getDownloadURL(String urlBase, DownloadType downloadType) { public String getDownloadURL(String urlBase, DownloadType downloadType) {
if (StrUtils.isNotBlank(url) && downloadType.getProvider().isAllowedToUseSelfURL()) urlBase = this.url; if (StrUtils.isNotBlank(url) && downloadType.getProvider().isAllowedToUseSelfURL())
if (urlBase.endsWith(".jar")) return urlBase; urlBase = this.url;
if (urlBase.endsWith(".jar"))
return urlBase;
return urlBase + formatted.replace('\\', '/'); return urlBase + formatted.replace('\\', '/');
} }

View File

@@ -56,7 +56,8 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
this.inheritsFrom = inheritsFrom; this.inheritsFrom = inheritsFrom;
this.minimumLauncherVersion = minimumLauncherVersion; this.minimumLauncherVersion = minimumLauncherVersion;
this.hidden = hidden; this.hidden = hidden;
if (libraries == null) this.libraries = new ArrayList<>(); if (libraries == null)
this.libraries = new ArrayList<>();
else { else {
this.libraries = new ArrayList<>(libraries.size()); this.libraries = new ArrayList<>(libraries.size());
for (IMinecraftLibrary library : libraries) for (IMinecraftLibrary library : libraries)
@@ -81,7 +82,8 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
MinecraftVersion parent = manager.getVersionById(inheritsFrom); MinecraftVersion parent = manager.getVersionById(inheritsFrom);
if (parent == null) { if (parent == null) {
if (!manager.install(inheritsFrom, sourceType)) return this; if (!manager.install(inheritsFrom, sourceType))
return this;
parent = manager.getVersionById(inheritsFrom); parent = manager.getVersionById(inheritsFrom);
} }
parent = parent.resolve(manager, resolvedSoFar, sourceType); parent = parent.resolve(manager, resolvedSoFar, sourceType);

View File

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

View File

@@ -31,6 +31,7 @@ public class DraggableFrame extends JFrame
private int dragGripX; private int dragGripX;
private int dragGripY; private int dragGripY;
@SuppressWarnings("LeakingThisInConstructor")
public DraggableFrame() { public DraggableFrame() {
setUndecorated(true); setUndecorated(true);
addMouseListener(this); addMouseListener(this);

View File

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

View File

@@ -186,7 +186,8 @@ public final class MainFrame extends DraggableFrame {
@Override @Override
public void mouseClicked(MouseEvent e) { public void mouseClicked(MouseEvent e) {
if (UpdateChecker.OUT_DATED) Main.update(); if (UpdateChecker.OUT_DATED)
Main.update();
} }
@Override @Override

View File

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

View File

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

View File

@@ -37,9 +37,8 @@ public class AppenderControl {
public void callAppender(LogEvent event) { public void callAppender(LogEvent event) {
if ((this.level != null) if ((this.level != null)
&& (this.intLevel < event.level.level)) { && (this.intLevel < event.level.level))
return; return;
}
if (this.recursive.get() != null) { if (this.recursive.get() != null) {
System.err.println("Recursive call to appender " + this.appender.getName()); System.err.println("Recursive call to appender " + this.appender.getName());
@@ -53,16 +52,14 @@ public class AppenderControl {
} catch (RuntimeException ex) { } catch (RuntimeException ex) {
System.err.println("An exception occurred processing Appender " + this.appender.getName()); System.err.println("An exception occurred processing Appender " + this.appender.getName());
ex.printStackTrace(); ex.printStackTrace();
if (!this.appender.ignoreExceptions()) { if (!this.appender.ignoreExceptions())
throw ex; throw ex;
}
} catch (Exception ex) { } catch (Exception ex) {
System.err.println("An exception occurred processing Appender " + this.appender.getName()); System.err.println("An exception occurred processing Appender " + this.appender.getName());
ex.printStackTrace(); ex.printStackTrace();
if (!this.appender.ignoreExceptions()) { if (!this.appender.ignoreExceptions())
throw new LoggingException(ex); throw new LoggingException(ex);
} }
}
} finally { } finally {
this.recursive.set(null); this.recursive.set(null);
} }

View File

@@ -25,7 +25,6 @@ import org.jackhuang.hellominecraft.logging.layout.DefaultLayout;
* *
* @author huangyuhui * @author huangyuhui
*/ */
public class Configuration { public class Configuration {
public ArrayList<IAppender> appenders = new ArrayList<IAppender>(); public ArrayList<IAppender> appenders = new ArrayList<IAppender>();

View File

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

View File

@@ -48,9 +48,8 @@ public abstract class OutputStreamAppender extends AbstractAppender {
this.readLock.lock(); this.readLock.lock();
try { try {
byte[] bytes = getLayout().toByteArray(event); byte[] bytes = getLayout().toByteArray(event);
if (bytes.length > 0) { if (bytes.length > 0)
stream.write(bytes); stream.write(bytes);
}
if (event.thrown != null) if (event.thrown != null)
event.thrown.printStackTrace(new PrintStream(stream)); event.thrown.printStackTrace(new PrintStream(stream));
} catch (IOException ex) { } catch (IOException ex) {

View File

@@ -25,6 +25,7 @@ import org.jackhuang.hellominecraft.logging.LogEvent;
* @author huangyuhui * @author huangyuhui
*/ */
public class DefaultLayout extends AbstractStringLayout { public class DefaultLayout extends AbstractStringLayout {
private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
@Override @Override

View File

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

View File

@@ -60,10 +60,9 @@ public abstract class AbstractLogger
@Override @Override
public void catching(Level level, Throwable t) { public void catching(Level level, Throwable t) {
if (isEnabled(level, (Object) null, null)) { if (isEnabled(level, (Object) null, null))
log(level, this.messageFactory.newMessage(CATCHING), t); log(level, this.messageFactory.newMessage(CATCHING), t);
} }
}
@Override @Override
public void catching(Throwable t) { public void catching(Throwable t) {
@@ -72,38 +71,33 @@ public abstract class AbstractLogger
@Override @Override
public void debug(IMessage msg) { public void debug(IMessage msg) {
if (isEnabled(Level.DEBUG, msg, null)) { if (isEnabled(Level.DEBUG, msg, null))
log(Level.DEBUG, msg, null); log(Level.DEBUG, msg, null);
} }
}
@Override @Override
public void debug(IMessage msg, Throwable t) { public void debug(IMessage msg, Throwable t) {
if (isEnabled(Level.DEBUG, msg, t)) { if (isEnabled(Level.DEBUG, msg, t))
log(Level.DEBUG, msg, t); log(Level.DEBUG, msg, t);
} }
}
@Override @Override
public void debug(Object message) { public void debug(Object message) {
if (isEnabled(Level.DEBUG, message, null)) { if (isEnabled(Level.DEBUG, message, null))
log(Level.DEBUG, this.messageFactory.newMessage(message), null); log(Level.DEBUG, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void debug(Object message, Throwable t) { public void debug(Object message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t)) { if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t); log(Level.DEBUG, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void debug(String message) { public void debug(String message) {
if (isEnabled(Level.DEBUG, message)) { if (isEnabled(Level.DEBUG, message))
log(Level.DEBUG, this.messageFactory.newMessage(message), null); log(Level.DEBUG, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void debug(String message, Object[] params) { public void debug(String message, Object[] params) {
@@ -115,10 +109,9 @@ public abstract class AbstractLogger
@Override @Override
public void debug(String message, Throwable t) { public void debug(String message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t)) { if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t); log(Level.DEBUG, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void entry() { public void entry() {
@@ -127,66 +120,57 @@ public abstract class AbstractLogger
@Override @Override
public void entry(Object[] params) { public void entry(Object[] params) {
if (isEnabled(Level.TRACE, (Object) null, null)) { if (isEnabled(Level.TRACE, (Object) null, null))
log(Level.TRACE, entryMsg(params.length, params), null); log(Level.TRACE, entryMsg(params.length, params), null);
} }
}
private IMessage entryMsg(int count, Object[] params) { private IMessage entryMsg(int count, Object[] params) {
if (count == 0) { if (count == 0)
return this.messageFactory.newMessage("entry"); return this.messageFactory.newMessage("entry");
}
StringBuilder sb = new StringBuilder("entry params("); StringBuilder sb = new StringBuilder("entry params(");
int i = 0; int i = 0;
for (Object parm : params) { for (Object parm : params) {
if (parm != null) { if (parm != null)
sb.append(parm.toString()); sb.append(parm.toString());
} else { else
sb.append("null"); sb.append("null");
}
i++; i++;
if (i < params.length) { if (i < params.length)
sb.append(", "); sb.append(", ");
} }
}
sb.append(")"); sb.append(")");
return this.messageFactory.newMessage(sb.toString()); return this.messageFactory.newMessage(sb.toString());
} }
@Override @Override
public void error(IMessage msg) { public void error(IMessage msg) {
if (isEnabled(Level.ERROR, msg, null)) { if (isEnabled(Level.ERROR, msg, null))
log(Level.ERROR, msg, null); log(Level.ERROR, msg, null);
} }
}
@Override @Override
public void error(IMessage msg, Throwable t) { public void error(IMessage msg, Throwable t) {
if (isEnabled(Level.ERROR, msg, t)) { if (isEnabled(Level.ERROR, msg, t))
log(Level.ERROR, msg, t); log(Level.ERROR, msg, t);
} }
}
@Override @Override
public void error(Object message) { public void error(Object message) {
if (isEnabled(Level.ERROR, message, null)) { if (isEnabled(Level.ERROR, message, null))
log(Level.ERROR, this.messageFactory.newMessage(message), null); log(Level.ERROR, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void error(Object message, Throwable t) { public void error(Object message, Throwable t) {
if (isEnabled(Level.ERROR, message, t)) { if (isEnabled(Level.ERROR, message, t))
log(Level.ERROR, this.messageFactory.newMessage(message), t); log(Level.ERROR, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void error(String message) { public void error(String message) {
if (isEnabled(Level.ERROR, message)) { if (isEnabled(Level.ERROR, message))
log(Level.ERROR, this.messageFactory.newMessage(message), null); log(Level.ERROR, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void error(String message, Object[] params) { public void error(String message, Object[] params) {
@@ -198,45 +182,39 @@ public abstract class AbstractLogger
@Override @Override
public void error(String message, Throwable t) { public void error(String message, Throwable t) {
if (isEnabled(Level.ERROR, message, t)) { if (isEnabled(Level.ERROR, message, t))
log(Level.ERROR, this.messageFactory.newMessage(message), t); log(Level.ERROR, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void fatal(IMessage msg) { public void fatal(IMessage msg) {
if (isEnabled(Level.FATAL, msg, null)) { if (isEnabled(Level.FATAL, msg, null))
log(Level.FATAL, msg, null); log(Level.FATAL, msg, null);
} }
}
@Override @Override
public void fatal(IMessage msg, Throwable t) { public void fatal(IMessage msg, Throwable t) {
if (isEnabled(Level.FATAL, msg, t)) { if (isEnabled(Level.FATAL, msg, t))
log(Level.FATAL, msg, t); log(Level.FATAL, msg, t);
} }
}
@Override @Override
public void fatal(Object message) { public void fatal(Object message) {
if (isEnabled(Level.FATAL, message, null)) { if (isEnabled(Level.FATAL, message, null))
log(Level.FATAL, this.messageFactory.newMessage(message), null); log(Level.FATAL, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void fatal(Object message, Throwable t) { public void fatal(Object message, Throwable t) {
if (isEnabled(Level.FATAL, message, t)) { if (isEnabled(Level.FATAL, message, t))
log(Level.FATAL, this.messageFactory.newMessage(message), t); log(Level.FATAL, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void fatal(String message) { public void fatal(String message) {
if (isEnabled(Level.FATAL, message)) { if (isEnabled(Level.FATAL, message))
log(Level.FATAL, this.messageFactory.newMessage(message), null); log(Level.FATAL, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void fatal(String message, Object[] params) { public void fatal(String message, Object[] params) {
@@ -248,10 +226,9 @@ public abstract class AbstractLogger
@Override @Override
public void fatal(String message, Throwable t) { public void fatal(String message, Throwable t) {
if (isEnabled(Level.FATAL, message, t)) { if (isEnabled(Level.FATAL, message, t))
log(Level.FATAL, this.messageFactory.newMessage(message), t); log(Level.FATAL, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public String getName() { public String getName() {
@@ -260,38 +237,33 @@ public abstract class AbstractLogger
@Override @Override
public void info(IMessage msg) { public void info(IMessage msg) {
if (isEnabled(Level.INFO, msg, null)) { if (isEnabled(Level.INFO, msg, null))
log(Level.INFO, msg, null); log(Level.INFO, msg, null);
} }
}
@Override @Override
public void info(IMessage msg, Throwable t) { public void info(IMessage msg, Throwable t) {
if (isEnabled(Level.INFO, msg, t)) { if (isEnabled(Level.INFO, msg, t))
log(Level.INFO, msg, t); log(Level.INFO, msg, t);
} }
}
@Override @Override
public void info(Object message) { public void info(Object message) {
if (isEnabled(Level.INFO, message, null)) { if (isEnabled(Level.INFO, message, null))
log(Level.INFO, this.messageFactory.newMessage(message), null); log(Level.INFO, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void info(Object message, Throwable t) { public void info(Object message, Throwable t) {
if (isEnabled(Level.INFO, message, t)) { if (isEnabled(Level.INFO, message, t))
log(Level.INFO, this.messageFactory.newMessage(message), t); log(Level.INFO, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void info(String message) { public void info(String message) {
if (isEnabled(Level.INFO, message)) { if (isEnabled(Level.INFO, message))
log(Level.INFO, this.messageFactory.newMessage(message), null); log(Level.INFO, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void info(String message, Object[] params) { public void info(String message, Object[] params) {
@@ -303,10 +275,9 @@ public abstract class AbstractLogger
@Override @Override
public void info(String message, Throwable t) { public void info(String message, Throwable t) {
if (isEnabled(Level.INFO, message, t)) { if (isEnabled(Level.INFO, message, t))
log(Level.INFO, this.messageFactory.newMessage(message), t); log(Level.INFO, this.messageFactory.newMessage(message), t);
} }
}
protected abstract boolean isEnabled(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable); protected abstract boolean isEnabled(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable);
@@ -358,38 +329,33 @@ public abstract class AbstractLogger
@Override @Override
public void log(Level level, IMessage msg) { public void log(Level level, IMessage msg) {
if (isEnabled(level, msg, null)) { if (isEnabled(level, msg, null))
log(level, msg, null); log(level, msg, null);
} }
}
@Override @Override
public void log(Level level, IMessage msg, Throwable t) { public void log(Level level, IMessage msg, Throwable t) {
if (isEnabled(level, msg, t)) { if (isEnabled(level, msg, t))
abstractLog(level, msg, t); abstractLog(level, msg, t);
} }
}
@Override @Override
public void log(Level level, Object message) { public void log(Level level, Object message) {
if (isEnabled(level, message, null)) { if (isEnabled(level, message, null))
log(level, this.messageFactory.newMessage(message), null); log(level, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void log(Level level, Object message, Throwable t) { public void log(Level level, Object message, Throwable t) {
if (isEnabled(level, message, t)) { if (isEnabled(level, message, t))
log(level, this.messageFactory.newMessage(message), t); log(level, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void log(Level level, String message) { public void log(Level level, String message) {
if (isEnabled(level, message)) { if (isEnabled(level, message))
log(level, this.messageFactory.newMessage(message), null); log(level, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void log(Level level, String message, Object[] params) { public void log(Level level, String message, Object[] params) {
@@ -401,10 +367,9 @@ public abstract class AbstractLogger
@Override @Override
public void log(Level level, String message, Throwable t) { public void log(Level level, String message, Throwable t) {
if (isEnabled(level, message, t)) { if (isEnabled(level, message, t))
log(level, this.messageFactory.newMessage(message), t); log(level, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void printf(Level level, String format, Object[] params) { public void printf(Level level, String format, Object[] params) {
@@ -421,9 +386,8 @@ public abstract class AbstractLogger
@Override @Override
public <T extends Throwable> T throwing(Level level, T t) { public <T extends Throwable> T throwing(Level level, T t) {
if (isEnabled(level, (Object) null, null)) { if (isEnabled(level, (Object) null, null))
log(level, this.messageFactory.newMessage(THROWING), t); log(level, this.messageFactory.newMessage(THROWING), t);
}
return t; return t;
} }
@@ -434,38 +398,33 @@ public abstract class AbstractLogger
@Override @Override
public void trace(IMessage msg) { public void trace(IMessage msg) {
if (isEnabled(Level.TRACE, msg, null)) { if (isEnabled(Level.TRACE, msg, null))
log(Level.TRACE, msg, null); log(Level.TRACE, msg, null);
} }
}
@Override @Override
public void trace(IMessage msg, Throwable t) { public void trace(IMessage msg, Throwable t) {
if (isEnabled(Level.TRACE, msg, t)) { if (isEnabled(Level.TRACE, msg, t))
log(Level.TRACE, msg, t); log(Level.TRACE, msg, t);
} }
}
@Override @Override
public void trace(Object message) { public void trace(Object message) {
if (isEnabled(Level.TRACE, message, null)) { if (isEnabled(Level.TRACE, message, null))
log(Level.TRACE, this.messageFactory.newMessage(message), null); log(Level.TRACE, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void trace(Object message, Throwable t) { public void trace(Object message, Throwable t) {
if (isEnabled(Level.TRACE, message, t)) { if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t); log(Level.TRACE, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void trace(String message) { public void trace(String message) {
if (isEnabled(Level.TRACE, message)) { if (isEnabled(Level.TRACE, message))
log(Level.TRACE, this.messageFactory.newMessage(message), null); log(Level.TRACE, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void trace(String message, Object[] params) { public void trace(String message, Object[] params) {
@@ -477,45 +436,39 @@ public abstract class AbstractLogger
@Override @Override
public void trace(String message, Throwable t) { public void trace(String message, Throwable t) {
if (isEnabled(Level.TRACE, message, t)) { if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t); log(Level.TRACE, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void warn(IMessage msg) { public void warn(IMessage msg) {
if (isEnabled(Level.WARN, msg, null)) { if (isEnabled(Level.WARN, msg, null))
log(Level.WARN, msg, null); log(Level.WARN, msg, null);
} }
}
@Override @Override
public void warn(IMessage msg, Throwable t) { public void warn(IMessage msg, Throwable t) {
if (isEnabled(Level.WARN, msg, t)) { if (isEnabled(Level.WARN, msg, t))
log(Level.WARN, msg, t); log(Level.WARN, msg, t);
} }
}
@Override @Override
public void warn(Object message) { public void warn(Object message) {
if (isEnabled(Level.WARN, message, null)) { if (isEnabled(Level.WARN, message, null))
log(Level.WARN, this.messageFactory.newMessage(message), null); log(Level.WARN, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void warn(Object message, Throwable t) { public void warn(Object message, Throwable t) {
if (isEnabled(Level.WARN, message, t)) { if (isEnabled(Level.WARN, message, t))
log(Level.WARN, this.messageFactory.newMessage(message), t); log(Level.WARN, this.messageFactory.newMessage(message), t);
} }
}
@Override @Override
public void warn(String message) { public void warn(String message) {
if (isEnabled(Level.WARN, message)) { if (isEnabled(Level.WARN, message))
log(Level.WARN, this.messageFactory.newMessage(message), null); log(Level.WARN, this.messageFactory.newMessage(message), null);
} }
}
@Override @Override
public void warn(String message, Object[] params) { public void warn(String message, Object[] params) {
@@ -527,8 +480,7 @@ public abstract class AbstractLogger
@Override @Override
public void warn(String message, Throwable t) { public void warn(String message, Throwable t) {
if (isEnabled(Level.WARN, message, t)) { if (isEnabled(Level.WARN, message, t))
log(Level.WARN, this.messageFactory.newMessage(message), t); log(Level.WARN, this.messageFactory.newMessage(message), t);
} }
} }
}

View File

@@ -42,10 +42,9 @@ public class Logger extends AbstractLogger {
} }
public synchronized void setLevel(Level level) { public synchronized void setLevel(Level level) {
if (level != null) { if (level != null)
this.config = new PrivateConfig(this.config, level); this.config = new PrivateConfig(this.config, level);
} }
}
public Level getLevel() { public Level getLevel() {
return this.config.level; return this.config.level;
@@ -67,10 +66,9 @@ public class Logger extends AbstractLogger {
} }
protected void callAppenders(LogEvent event) { protected void callAppenders(LogEvent event) {
for (AppenderControl control : this.appenders.values()) { for (AppenderControl control : this.appenders.values())
control.callAppender(event); control.callAppender(event);
} }
}
@Override @Override
public boolean isEnabled(Level level, String msg) { public boolean isEnabled(Level level, String msg) {
@@ -107,9 +105,8 @@ public class Logger extends AbstractLogger {
public Map<String, IAppender> getAppenders() { public Map<String, IAppender> getAppenders() {
Map map = new HashMap(); Map map = new HashMap();
for (Map.Entry entry : this.appenders.entrySet()) { for (Map.Entry entry : this.appenders.entrySet())
map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender()); map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender());
}
return map; return map;
} }

View File

@@ -40,28 +40,25 @@ public class SimpleLogger extends AbstractLogger {
this.level = defaultLevel; this.level = defaultLevel;
if (showShortLogName) { if (showShortLogName) {
int index = name.lastIndexOf("."); int index = name.lastIndexOf(".");
if ((index > 0) && (index < name.length())) { if ((index > 0) && (index < name.length()))
this.logName = name.substring(index + 1); this.logName = name.substring(index + 1);
} else { else
this.logName = name; this.logName = name;
} } else if (showLogName)
} else if (showLogName) {
this.logName = name; this.logName = name;
} else { else
this.logName = null; this.logName = null;
}
this.showDateTime = showDateTime; this.showDateTime = showDateTime;
this.showContextMap = showContextMap; this.showContextMap = showContextMap;
this.stream = stream; this.stream = stream;
if (showDateTime) { if (showDateTime)
try { try {
this.dateFormatter = new SimpleDateFormat(dateTimeFormat); this.dateFormatter = new SimpleDateFormat(dateTimeFormat);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
this.dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS zzz"); this.dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS zzz");
} }
} }
}
public void setStream(PrintStream stream) { public void setStream(PrintStream stream) {
this.stream = stream; this.stream = stream;
@@ -72,10 +69,9 @@ public class SimpleLogger extends AbstractLogger {
} }
public void setLevel(Level level) { public void setLevel(Level level) {
if (level != null) { if (level != null)
this.level = level; this.level = level;
} }
}
@Override @Override
public void abstractLog(Level level, IMessage msg, Throwable throwable) { public void abstractLog(Level level, IMessage msg, Throwable throwable) {
@@ -100,11 +96,10 @@ public class SimpleLogger extends AbstractLogger {
sb.append(msg.getFormattedMessage()); sb.append(msg.getFormattedMessage());
Object[] params = msg.getParameters(); Object[] params = msg.getParameters();
Throwable t; Throwable t;
if ((throwable == null) && (params != null) && ((params[(params.length - 1)] instanceof Throwable))) { if ((throwable == null) && (params != null) && ((params[(params.length - 1)] instanceof Throwable)))
t = (Throwable) params[(params.length - 1)]; t = (Throwable) params[(params.length - 1)];
} else { else
t = throwable; t = throwable;
}
if (t != null) { if (t != null) {
sb.append(' '); sb.append(' ');
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();

View File

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

View File

@@ -23,9 +23,8 @@ public class ObjectMessage
private final transient Object obj; private final transient Object obj;
public ObjectMessage(Object obj) { public ObjectMessage(Object obj) {
if (obj == null) { if (obj == null)
obj = "null"; obj = "null";
}
this.obj = obj; this.obj = obj;
} }
@@ -46,12 +45,10 @@ public class ObjectMessage
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o)
return true; return true;
} if ((o == null) || (getClass() != o.getClass()))
if ((o == null) || (getClass() != o.getClass())) {
return false; return false;
}
ObjectMessage that = (ObjectMessage) o; ObjectMessage that = (ObjectMessage) o;

View File

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

View File

@@ -51,12 +51,10 @@ public class SimpleMessage
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o)
return true; return true;
} if ((o == null) || (getClass() != o.getClass()))
if ((o == null) || (getClass() != o.getClass())) {
return false; return false;
}
SimpleMessage that = (SimpleMessage) o; SimpleMessage that = (SimpleMessage) o;

View File

@@ -32,16 +32,14 @@ public class StringFormattedMessage
public StringFormattedMessage(String messagePattern, Object[] arguments) { public StringFormattedMessage(String messagePattern, Object[] arguments) {
this.messagePattern = messagePattern; this.messagePattern = messagePattern;
this.argArray = arguments; this.argArray = arguments;
if ((arguments != null) && (arguments.length > 0) && ((arguments[(arguments.length - 1)] instanceof Throwable))) { if ((arguments != null) && (arguments.length > 0) && ((arguments[(arguments.length - 1)] instanceof Throwable)))
this.throwable = ((Throwable) arguments[(arguments.length - 1)]); this.throwable = ((Throwable) arguments[(arguments.length - 1)]);
} }
}
@Override @Override
public String getFormattedMessage() { public String getFormattedMessage() {
if (this.formattedMessage == null) { if (this.formattedMessage == null)
this.formattedMessage = formatMessage(this.messagePattern, this.argArray); this.formattedMessage = formatMessage(this.messagePattern, this.argArray);
}
return this.formattedMessage; return this.formattedMessage;
} }
@@ -52,9 +50,8 @@ public class StringFormattedMessage
@Override @Override
public Object[] getParameters() { public Object[] getParameters() {
if (this.argArray != null) { if (this.argArray != null)
return this.argArray; return this.argArray;
}
return this.stringArgs; return this.stringArgs;
} }
@@ -70,18 +67,15 @@ public class StringFormattedMessage
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o)
return true; return true;
} if ((o == null) || (getClass() != o.getClass()))
if ((o == null) || (getClass() != o.getClass())) {
return false; return false;
}
StringFormattedMessage that = (StringFormattedMessage) o; StringFormattedMessage that = (StringFormattedMessage) o;
if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null) { if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null)
return false; return false;
}
return Arrays.equals(this.stringArgs, that.stringArgs); return Arrays.equals(this.stringArgs, that.stringArgs);
} }

View File

@@ -98,7 +98,8 @@ public class TaskList extends Thread {
} }
while (!runningThread.isEmpty()) while (!runningThread.isEmpty())
try { try {
if (this.isInterrupted()) return; if (this.isInterrupted())
return;
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException ignore) { } catch (InterruptedException ignore) {
} }
@@ -160,7 +161,8 @@ public class TaskList extends Thread {
while (!threadPool.isEmpty()) while (!threadPool.isEmpty())
synchronized (threadPool) { synchronized (threadPool) {
InvokeThread it = threadPool.iterator().next(); InvokeThread it = threadPool.iterator().next();
if (!it.task.abort()) it.interrupt(); if (!it.task.abort())
it.interrupt();
threadPool.remove(it); threadPool.remove(it);
} }
this.interrupt(); this.interrupt();

View File

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

View File

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

View File

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

View File

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

View File

@@ -167,7 +167,8 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
if (aborted) if (aborted)
tempFile.delete(); tempFile.delete();
else { else {
if (filePath.exists()) filePath.delete(); if (filePath.exists())
filePath.delete();
tempFile.renameTo(filePath); tempFile.renameTo(filePath);
} }
if (ppl != null) if (ppl != null)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -87,6 +87,7 @@ public final class NetUtils {
* @param requestParameters - all the request parameters (Example: * @param requestParameters - all the request parameters (Example:
* "param1=val1&param2=val2"). Note: This method will add the question mark * "param1=val1&param2=val2"). Note: This method will add the question mark
* (?) to the request - DO NOT add it yourself * (?) to the request - DO NOT add it yourself
*
* @return - The response from the end point * @return - The response from the end point
*/ */
public static String sendGetRequest(String endpoint, public static String sendGetRequest(String endpoint,
@@ -157,7 +158,8 @@ public final class NetUtils {
os = con.getOutputStream(); os = con.getOutputStream();
IOUtils.write(post, os, DEFAULT_CHARSET); IOUtils.write(post, os, DEFAULT_CHARSET);
} finally { } finally {
if (os != null) IOUtils.closeQuietly(os); if (os != null)
IOUtils.closeQuietly(os);
} }
String result = null; String result = null;
@@ -166,7 +168,8 @@ public final class NetUtils {
is = con.getInputStream(); is = con.getInputStream();
result = getStreamContent(is); result = getStreamContent(is);
} catch (IOException ex) { } catch (IOException ex) {
if (is != null) IOUtils.closeQuietly(is); if (is != null)
IOUtils.closeQuietly(is);
is = con.getErrorStream(); is = con.getErrorStream();
result = getStreamContent(is); result = getStreamContent(is);
} }

View File

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

View File

@@ -41,6 +41,7 @@ public class SwingUtils {
* @param titleA The title of each column. * @param titleA The title of each column.
* @param typesA The type of each column value. * @param typesA The type of each column value.
* @param canEditA Is column editable? * @param canEditA Is column editable?
*
* @return * @return
*/ */
public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) { public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) {
@@ -99,6 +100,7 @@ public class SwingUtils {
* Get the DefaultListModel from JList. * Get the DefaultListModel from JList.
* *
* @param list * @param list
*
* @return Forcely Type casted to DefaultListModel * @return Forcely Type casted to DefaultListModel
*/ */
public static DefaultListModel getDefaultListModel(JList list) { public static DefaultListModel getDefaultListModel(JList list) {
@@ -152,12 +154,14 @@ public class SwingUtils {
} }
public static String getParsedJPanelText(JLabel jLabel1, String longString) { public static String getParsedJPanelText(JLabel jLabel1, String longString) {
if (StrUtils.isBlank(longString)) return longString; if (StrUtils.isBlank(longString))
return longString;
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
char[] chars = longString.toCharArray(); char[] chars = longString.toCharArray();
FontMetrics fontMetrics = jLabel1.getFontMetrics(jLabel1.getFont()); FontMetrics fontMetrics = jLabel1.getFontMetrics(jLabel1.getFont());
for (int beginIndex = 0, limit = 1;; limit++) { for (int beginIndex = 0, limit = 1;; limit++) {
if (beginIndex + limit >= chars.length) break; if (beginIndex + limit >= chars.length)
break;
if (fontMetrics.charsWidth(chars, beginIndex, limit) < jLabel1.getWidth()) { if (fontMetrics.charsWidth(chars, beginIndex, limit) < jLabel1.getWidth()) {
if (beginIndex + limit < chars.length) if (beginIndex + limit < chars.length)
continue; continue;

View File

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

View File

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

View File

@@ -61,12 +61,10 @@ public class Base64 {
public static byte[] decode(char[] data) { public static byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3; int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 && data[data.length - 1] == '=') { if (data.length > 0 && data[data.length - 1] == '=')
--len; --len;
} if (data.length > 1 && data[data.length - 2] == '=')
if (data.length > 1 && data[data.length - 2] == '=') {
--len; --len;
}
byte[] out = new byte[len]; byte[] out = new byte[len];
int shift = 0; int shift = 0;
int accum = 0; int accum = 0;
@@ -83,9 +81,8 @@ public class Base64 {
} }
} }
} }
if (index != out.length) { if (index != out.length)
throw new Error("miscalculated data length!"); throw new Error("miscalculated data length!");
}
return out; return out;
} }
private static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" private static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
@@ -93,18 +90,14 @@ public class Base64 {
private static final byte[] codes = new byte[256]; private static final byte[] codes = new byte[256];
static { static {
for (int i = 0; i < 256; i++) { for (int i = 0; i < 256; i++)
codes[i] = -1; codes[i] = -1;
} for (int i = 'A'; i <= 'Z'; i++)
for (int i = 'A'; i <= 'Z'; i++) {
codes[i] = (byte) (i - 'A'); codes[i] = (byte) (i - 'A');
} for (int i = 'a'; i <= 'z'; i++)
for (int i = 'a'; i <= 'z'; i++) {
codes[i] = (byte) (26 + i - 'a'); codes[i] = (byte) (26 + i - 'a');
} for (int i = '0'; i <= '9'; i++)
for (int i = '0'; i <= '9'; i++) {
codes[i] = (byte) (52 + i - '0'); codes[i] = (byte) (52 + i - '0');
}
codes['+'] = 62; codes['+'] = 62;
codes['/'] = 63; codes['/'] = 63;
} }

View File

@@ -30,9 +30,8 @@ public class Hex {
public static byte[] decodeHex(char[] data) throws Exception { public static byte[] decodeHex(char[] data) throws Exception {
int len = data.length; int len = data.length;
if ((len & 0x1) != 0) { if ((len & 0x1) != 0)
throw new Exception("Odd number of characters."); throw new Exception("Odd number of characters.");
}
byte[] out = new byte[len >> 1]; byte[] out = new byte[len >> 1];
@@ -74,9 +73,8 @@ public class Hex {
protected static int toDigit(char ch, int index) throws Exception { protected static int toDigit(char ch, int index) throws Exception {
int digit = Character.digit(ch, 16); int digit = Character.digit(ch, 16);
if (digit == -1) { if (digit == -1)
throw new Exception("Illegal hexadecimal character " + ch + " at index " + index); throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
}
return digit; return digit;
} }

View File

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

View File

@@ -44,6 +44,7 @@ public class Compressor {
* *
* @param sourceDir 源文件夹 * @param sourceDir 源文件夹
* @param zipFile 压缩生成的zip文件路径。 * @param zipFile 压缩生成的zip文件路径。
*
* @throws java.io.IOException 压缩失败或无法读取 * @throws java.io.IOException 压缩失败或无法读取
*/ */
public static void zip(File sourceDir, File zipFile) throws IOException { public static void zip(File sourceDir, File zipFile) throws IOException {
@@ -113,6 +114,7 @@ public class Compressor {
* @param zipFileName zip文件路径 * @param zipFileName zip文件路径
* @param extPlace 待压缩文件根目录 * @param extPlace 待压缩文件根目录
* @param without 带前缀的不解压 * @param without 带前缀的不解压
*
* @throws java.io.IOException 解压失败或无法写入 * @throws java.io.IOException 解压失败或无法写入
*/ */
public static void unzip(File zipFileName, File extPlace, String[] without) throws IOException { public static void unzip(File zipFileName, File extPlace, String[] without) throws IOException {
@@ -125,7 +127,8 @@ public class Compressor {
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
ZipEntry zipEnt = (ZipEntry) e.nextElement(); ZipEntry zipEnt = (ZipEntry) e.nextElement();
gbkPath = zipEnt.getName(); gbkPath = zipEnt.getName();
if (StrUtils.startsWithOne(without, gbkPath)) continue; if (StrUtils.startsWithOne(without, gbkPath))
continue;
if (zipEnt.isDirectory()) { if (zipEnt.isDirectory()) {
strtemp = strPath + File.separator + gbkPath; strtemp = strPath + File.separator + gbkPath;
File dir = new File(strtemp); File dir = new File(strtemp);
@@ -161,6 +164,7 @@ public class Compressor {
* *
* @param destFile zip1 * @param destFile zip1
* @param srcFile zip2 * @param srcFile zip2
*
* @throws java.io.IOException 无法写入或读取 * @throws java.io.IOException 无法写入或读取
*/ */
public static void merge(File destFile, File srcFile) throws IOException { public static void merge(File destFile, File srcFile) throws IOException {

View File

@@ -435,9 +435,11 @@ public class FileUtils {
public static File[] searchSuffix(File dir, String suffix) { public static File[] searchSuffix(File dir, String suffix) {
ArrayList<File> al = new ArrayList(); ArrayList<File> al = new ArrayList();
File[] files = dir.listFiles(); File[] files = dir.listFiles();
if (files == null) return new File[0]; if (files == null)
return new File[0];
for (File f : files) for (File f : files)
if (f.getName().endsWith(suffix)) al.add(f); if (f.getName().endsWith(suffix))
al.add(f);
return al.toArray(new File[0]); return al.toArray(new File[0]);
} }
} }

View File

@@ -284,10 +284,9 @@ public class IOUtils {
try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getInputStream()))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getInputStream()))) {
jp.getRawProcess().waitFor(); jp.getRawProcess().waitFor();
String line; String line;
while((line = br.readLine()) != null) { while ((line = br.readLine()) != null)
lines.add(line); lines.add(line);
} }
}
return lines; return lines;
} }
@@ -297,10 +296,9 @@ public class IOUtils {
try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getErrorStream()))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getErrorStream()))) {
jp.getRawProcess().waitFor(); jp.getRawProcess().waitFor();
String line; String line;
while((line = br.readLine()) != null) { while ((line = br.readLine()) != null)
lines.add(line); lines.add(line);
} }
}
return lines; return lines;
} }
} }

View File

@@ -52,7 +52,8 @@ public class Java {
if (obj instanceof Java) { if (obj instanceof Java) {
Java j = (Java) obj; Java j = (Java) obj;
return (j.getName() == null && this.getName() == null) || ((Java) obj).getName().equals(this.getName()); return (j.getName() == null && this.getName() == null) || ((Java) obj).getName().equals(this.getName());
} else return false; } else
return false;
} }
@Override @Override
@@ -88,8 +89,10 @@ public class Java {
for (String java : javas) { for (String java : javas) {
int s = 0; int s = 0;
for (char c : java.toCharArray()) for (char c : java.toCharArray())
if (c == '.') s++; if (c == '.')
if (s <= 1) continue; s++;
if (s <= 1)
continue;
String javahome = queryRegValue(java, "JavaHome"); String javahome = queryRegValue(java, "JavaHome");
if (javahome != null) if (javahome != null)
ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\".length()), javahome)); ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\".length()), javahome));
@@ -98,8 +101,10 @@ public class Java {
for (String java : javas) { for (String java : javas) {
int s = 0; int s = 0;
for (char c : java.toCharArray()) for (char c : java.toCharArray())
if (c == '.') s++; if (c == '.')
if (s <= 1) continue; s++;
if (s <= 1)
continue;
String javahome = queryRegValue(java, "JavaHome"); String javahome = queryRegValue(java, "JavaHome");
if (javahome != null) if (javahome != null)
ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\".length()), javahome)); ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\".length()), javahome));
@@ -125,7 +130,8 @@ public class Java {
List<String> l = IOUtils.readProcessByInputStream(cmd); List<String> l = IOUtils.readProcessByInputStream(cmd);
boolean last = false; boolean last = false;
for (String s : l) { for (String s : l) {
if (s.trim().isEmpty()) continue; if (s.trim().isEmpty())
continue;
if (last == true && s.trim().startsWith(name)) { if (last == true && s.trim().startsWith(name)) {
int begins = s.indexOf(name); int begins = s.indexOf(name);
if (begins > 0) { if (begins > 0) {
@@ -137,7 +143,8 @@ public class Java {
} }
} }
} }
if (s.trim().equals(location)) last = true; if (s.trim().equals(location))
last = true;
} }
return null; return null;
} }

View File

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

View File

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

View File

@@ -55,7 +55,8 @@ public final class JdkVersion {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof JdkVersion)) return false; if (!(obj instanceof JdkVersion))
return false;
JdkVersion b = (JdkVersion) obj; JdkVersion b = (JdkVersion) obj;
if (b.location == null || location == null) if (b.location == null || location == null)
return b.location == location; return b.location == location;
@@ -69,7 +70,8 @@ public final class JdkVersion {
public JdkVersion(String location) { public JdkVersion(String location) {
File f = new File(location); File f = new File(location);
if (f.exists() && f.isFile()) f = f.getParentFile(); if (f.exists() && f.isFile())
f = f.getParentFile();
this.location = f.getAbsolutePath(); this.location = f.getAbsolutePath();
} }
@@ -110,12 +112,17 @@ public final class JdkVersion {
} }
private static int parseVersion(String javaVersion) { private static int parseVersion(String javaVersion) {
if (StrUtils.isBlank(javaVersion)) return UNKOWN; if (StrUtils.isBlank(javaVersion))
return UNKOWN;
int a = UNKOWN; int a = UNKOWN;
if (javaVersion.contains("1.9.")) a = JAVA_19; if (javaVersion.contains("1.9."))
else if (javaVersion.contains("1.8.")) a = JAVA_18; a = JAVA_19;
else if (javaVersion.contains("1.7.")) a = JAVA_17; else if (javaVersion.contains("1.8."))
else if (javaVersion.contains("1.6.")) a = JAVA_16; a = JAVA_18;
else if (javaVersion.contains("1.7."))
a = JAVA_17;
else if (javaVersion.contains("1.6."))
a = JAVA_16;
return a; return a;
} }
@@ -124,6 +131,7 @@ public final class JdkVersion {
* <code>System.getProperty("java.version")</code>. * <code>System.getProperty("java.version")</code>.
* *
* @return the full Java version string * @return the full Java version string
*
* @see System#getProperty(String) * @see System#getProperty(String)
*/ */
public static String getJavaVersion() { public static String getJavaVersion() {
@@ -138,6 +146,7 @@ public final class JdkVersion {
* rn a code comparable to the JAVA_XX codes in this class * rn a code comparable to the JAVA_XX codes in this class
* *
* @return * @return
*
* @see #JAVA_13 * @see #JAVA_13
* @see #JAVA_14 * @see #JAVA_14
* @see #JAVA_15 * @see #JAVA_15

View File

@@ -88,6 +88,7 @@ public class MessageBox {
* @param Msg The Message * @param Msg The Message
* @param Title The title of MsgBox. * @param Title The title of MsgBox.
* @param Option The type of MsgBox. * @param Option The type of MsgBox.
*
* @return user operation. * @return user operation.
*/ */
public static int Show(String Msg, String Title, int Option) { public static int Show(String Msg, String Title, int Option) {
@@ -107,6 +108,7 @@ public class MessageBox {
* *
* @param Msg The Message * @param Msg The Message
* @param Option The type of MsgBox. * @param Option The type of MsgBox.
*
* @return User Operation * @return User Operation
*/ */
public static int Show(String Msg, int Option) { public static int Show(String Msg, int Option) {
@@ -117,6 +119,7 @@ public class MessageBox {
* Show Default MsgBox * Show Default MsgBox
* *
* @param Msg The Message * @param Msg The Message
*
* @return User Operation * @return User Operation
*/ */
public static int Show(String Msg) { public static int Show(String Msg) {

View File

@@ -56,8 +56,8 @@ public class ProcessThread extends Thread {
HMCLog.warn("Unsupported encoding: " + System.getProperty("sun.jnu.encoding", "UTF-8"), ex); HMCLog.warn("Unsupported encoding: " + System.getProperty("sun.jnu.encoding", "UTF-8"), ex);
br = new InputStreamReader(in); br = new InputStreamReader(in);
} }
} } else
else br = null; br = null;
int ch; int ch;
String line = ""; String line = "";

View File

@@ -27,9 +27,8 @@ public class FastBlurFilter extends AbstractFilter {
} }
public FastBlurFilter(int radius) { public FastBlurFilter(int radius) {
if (radius < 1) { if (radius < 1)
radius = 1; radius = 1;
}
this.radius = radius; this.radius = radius;
} }
@@ -43,9 +42,8 @@ public class FastBlurFilter extends AbstractFilter {
int width = src.getWidth(); int width = src.getWidth();
int height = src.getHeight(); int height = src.getHeight();
if (dst == null) { if (dst == null)
dst = createCompatibleDestImage(src, null); dst = createCompatibleDestImage(src, null);
}
int[] srcPixels = new int[width * height]; int[] srcPixels = new int[width * height];
int[] dstPixels = new int[width * height]; int[] dstPixels = new int[width * height];
@@ -68,23 +66,19 @@ public class FastBlurFilter extends AbstractFilter {
int srcIndex = 0; int srcIndex = 0;
int[] sumLookupTable = new int[256 * windowSize]; int[] sumLookupTable = new int[256 * windowSize];
for (int i = 0; i < sumLookupTable.length; i++) { for (int i = 0; i < sumLookupTable.length; i++)
sumLookupTable[i] = (i / windowSize); sumLookupTable[i] = (i / windowSize);
}
int[] indexLookupTable = new int[radiusPlusOne]; int[] indexLookupTable = new int[radiusPlusOne];
if (radius < width) { if (radius < width)
for (int i = 0; i < indexLookupTable.length; i++) { for (int i = 0; i < indexLookupTable.length; i++)
indexLookupTable[i] = i; indexLookupTable[i] = i;
} else {
} else { for (int i = 0; i < width; i++)
for (int i = 0; i < width; i++) {
indexLookupTable[i] = i; indexLookupTable[i] = i;
} for (int i = width; i < indexLookupTable.length; i++)
for (int i = width; i < indexLookupTable.length; i++) {
indexLookupTable[i] = (width - 1); indexLookupTable[i] = (width - 1);
} }
}
for (int y = 0; y < height; y++) { for (int y = 0; y < height; y++) {
int sumBlue; int sumBlue;
@@ -113,14 +107,12 @@ public class FastBlurFilter extends AbstractFilter {
dstIndex += height; dstIndex += height;
int nextPixelIndex = x + radiusPlusOne; int nextPixelIndex = x + radiusPlusOne;
if (nextPixelIndex >= width) { if (nextPixelIndex >= width)
nextPixelIndex = width - 1; nextPixelIndex = width - 1;
}
int previousPixelIndex = x - radius; int previousPixelIndex = x - radius;
if (previousPixelIndex < 0) { if (previousPixelIndex < 0)
previousPixelIndex = 0; previousPixelIndex = 0;
}
int nextPixel = srcPixels[(srcIndex + nextPixelIndex)]; int nextPixel = srcPixels[(srcIndex + nextPixelIndex)];
int previousPixel = srcPixels[(srcIndex + previousPixelIndex)]; int previousPixel = srcPixels[(srcIndex + previousPixelIndex)];

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.InputStream; import java.io.InputStream;
@@ -16,6 +15,7 @@ import org.tukaani.xz.simple.ARM;
* BCJ filter for little endian ARM instructions. * BCJ filter for little endian ARM instructions.
*/ */
public class ARMOptions extends BCJOptions { public class ARMOptions extends BCJOptions {
private static final int ALIGNMENT = 4; private static final int ALIGNMENT = 4;
public ARMOptions() { public ARMOptions() {

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.InputStream; import java.io.InputStream;
@@ -16,6 +15,7 @@ import org.tukaani.xz.simple.ARMThumb;
* BCJ filter for little endian ARM-Thumb instructions. * BCJ filter for little endian ARM-Thumb instructions.
*/ */
public class ARMThumbOptions extends BCJOptions { public class ARMThumbOptions extends BCJOptions {
private static final int ALIGNMENT = 2; private static final int ALIGNMENT = 2;
public ARMThumbOptions() { public ARMThumbOptions() {

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
abstract class BCJCoder implements FilterCoder { abstract class BCJCoder implements FilterCoder {
public static final long X86_FILTER_ID = 0x04; public static final long X86_FILTER_ID = 0x04;
public static final long POWERPC_FILTER_ID = 0x05; public static final long POWERPC_FILTER_ID = 0x05;
public static final long IA64_FILTER_ID = 0x06; public static final long IA64_FILTER_ID = 0x06;

View File

@@ -6,13 +6,13 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.InputStream; import java.io.InputStream;
import org.tukaani.xz.simple.*; import org.tukaani.xz.simple.*;
class BCJDecoder extends BCJCoder implements FilterDecoder { class BCJDecoder extends BCJCoder implements FilterDecoder {
private final long filterID; private final long filterID;
private final int startOffset; private final int startOffset;
@@ -21,19 +21,18 @@ class BCJDecoder extends BCJCoder implements FilterDecoder {
assert isBCJFilterID(filterID); assert isBCJFilterID(filterID);
this.filterID = filterID; this.filterID = filterID;
if (props.length == 0) { if (props.length == 0)
startOffset = 0; startOffset = 0;
} else if (props.length == 4) { else if (props.length == 4) {
int n = 0; int n = 0;
for (int i = 0; i < 4; ++i) for (int i = 0; i < 4; ++i)
n |= (props[i] & 0xFF) << (i * 8); n |= (props[i] & 0xFF) << (i * 8);
startOffset = n; startOffset = n;
} else { } else
throw new UnsupportedOptionsException( throw new UnsupportedOptionsException(
"Unsupported BCJ filter properties"); "Unsupported BCJ filter properties");
} }
}
public int getMemoryUsage() { public int getMemoryUsage() {
return SimpleInputStream.getMemoryUsage(); return SimpleInputStream.getMemoryUsage();

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
class BCJEncoder extends BCJCoder implements FilterEncoder { class BCJEncoder extends BCJCoder implements FilterEncoder {
private final BCJOptions options; private final BCJOptions options;
private final long filterID; private final long filterID;
private final byte[] props; private final byte[] props;
@@ -18,9 +18,9 @@ class BCJEncoder extends BCJCoder implements FilterEncoder {
assert isBCJFilterID(filterID); assert isBCJFilterID(filterID);
int startOffset = options.getStartOffset(); int startOffset = options.getStartOffset();
if (startOffset == 0) { if (startOffset == 0)
props = new byte[0]; props = new byte[0];
} else { else {
props = new byte[4]; props = new byte[4];
for (int i = 0; i < 4; ++i) for (int i = 0; i < 4; ++i)
props[i] = (byte) (startOffset >>> (i * 8)); props[i] = (byte) (startOffset >>> (i * 8));

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
abstract class BCJOptions extends FilterOptions { abstract class BCJOptions extends FilterOptions {
private final int alignment; private final int alignment;
int startOffset = 0; int startOffset = 0;

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.InputStream; import java.io.InputStream;
@@ -18,6 +17,7 @@ import org.tukaani.xz.common.DecoderUtil;
import org.tukaani.xz.check.Check; import org.tukaani.xz.check.Check;
class BlockInputStream extends InputStream { class BlockInputStream extends InputStream {
private final DataInputStream inData; private final DataInputStream inData;
private final CountingInputStream inCounted; private final CountingInputStream inCounted;
private InputStream filterChain; private InputStream filterChain;
@@ -158,7 +158,7 @@ class BlockInputStream extends InputStream {
// supported by this decoder implementation. // supported by this decoder implementation.
FilterDecoder[] filters = new FilterDecoder[filterIDs.length]; FilterDecoder[] filters = new FilterDecoder[filterIDs.length];
for (int i = 0; i < filters.length; ++i) { for (int i = 0; i < filters.length; ++i)
if (filterIDs[i] == LZMA2Coder.FILTER_ID) if (filterIDs[i] == LZMA2Coder.FILTER_ID)
filters[i] = new LZMA2Decoder(filterProps[i]); filters[i] = new LZMA2Decoder(filterProps[i]);
@@ -171,7 +171,6 @@ class BlockInputStream extends InputStream {
else else
throw new UnsupportedOptionsException( throw new UnsupportedOptionsException(
"Unknown Filter ID " + filterIDs[i]); "Unknown Filter ID " + filterIDs[i]);
}
RawCoder.validate(filters); RawCoder.validate(filters);

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.OutputStream; import java.io.OutputStream;
@@ -16,6 +15,7 @@ import org.tukaani.xz.common.EncoderUtil;
import org.tukaani.xz.check.Check; import org.tukaani.xz.check.Check;
class BlockOutputStream extends FinishableOutputStream { class BlockOutputStream extends FinishableOutputStream {
private final OutputStream out; private final OutputStream out;
private final CountingOutputStream outCounted; private final CountingOutputStream outCounted;
private FinishableOutputStream filterChain; private FinishableOutputStream filterChain;

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
/** /**
@@ -15,6 +14,7 @@ package org.tukaani.xz;
* already read from the input stream was corrupt too. * already read from the input stream was corrupt too.
*/ */
public class CorruptedInputException extends XZIOException { public class CorruptedInputException extends XZIOException {
private static final long serialVersionUID = 3L; private static final long serialVersionUID = 3L;
/** /**

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.FilterInputStream; import java.io.FilterInputStream;
@@ -17,6 +16,7 @@ import java.io.IOException;
* Counts the number of bytes read from an input stream. * Counts the number of bytes read from an input stream.
*/ */
class CountingInputStream extends FilterInputStream { class CountingInputStream extends FilterInputStream {
private long size = 0; private long size = 0;
public CountingInputStream(InputStream in) { public CountingInputStream(InputStream in) {

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.OutputStream; import java.io.OutputStream;
@@ -21,6 +20,7 @@ import java.io.IOException;
* using this as the output stream for a chain of raw filters. * using this as the output stream for a chain of raw filters.
*/ */
class CountingOutputStream extends FinishableOutputStream { class CountingOutputStream extends FinishableOutputStream {
private final OutputStream out; private final OutputStream out;
private long size = 0; private long size = 0;

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
abstract class DeltaCoder implements FilterCoder { abstract class DeltaCoder implements FilterCoder {
public static final long FILTER_ID = 0x03; public static final long FILTER_ID = 0x03;
public boolean changesSize() { public boolean changesSize() {

View File

@@ -6,12 +6,12 @@
* This file has been put into the public domain. * This file has been put into the public domain.
* You can do whatever you want with this file. * You can do whatever you want with this file.
*/ */
package org.tukaani.xz; package org.tukaani.xz;
import java.io.InputStream; import java.io.InputStream;
class DeltaDecoder extends DeltaCoder implements FilterDecoder { class DeltaDecoder extends DeltaCoder implements FilterDecoder {
private final int distance; private final int distance;
DeltaDecoder(byte[] props) throws UnsupportedOptionsException { DeltaDecoder(byte[] props) throws UnsupportedOptionsException {

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