Reconstruct the codes.

This commit is contained in:
huanghongxun
2015-07-11 17:34:25 +08:00
parent 0be056ac04
commit 2b63d46ffd
113 changed files with 1281 additions and 1343 deletions

View File

@@ -64,7 +64,7 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
String str = v.getJavaDir(); String str = v.getJavaDir();
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);
@@ -153,11 +153,9 @@ 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()) if (v.isFullscreen()) res.add("--fullscreen");
res.add("--fullscreen");
if (v.isDebug() && !v.isCanceledWrapper()) if (v.isDebug() && !v.isCanceledWrapper()) res.add("-debug");
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(" ")));
@@ -172,6 +170,7 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
* <li>main class</li> * <li>main class</li>
* <li>minecraft arguments</li> * <li>minecraft arguments</li>
* </ul> * </ul>
*
* @param list the command list you shoud edit. * @param list the command list you shoud edit.
*/ */
protected abstract void makeSelf(List<String> list); protected abstract void makeSelf(List<String> list);

View File

@@ -57,17 +57,12 @@ public class DefaultGameLauncher extends GameLauncher {
return flag; return flag;
}); });
decompressNativesEvent.register((sender, value) -> { decompressNativesEvent.register((sender, value) -> {
//boolean flag = true;
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]);
} catch (IOException ex) { } catch (IOException ex) {
HMCLog.err("Unable to decompress library file: " + value.decompressFiles[i] + " to " + value.decompressTo, ex); HMCLog.err("Unable to decompress library file: " + value.decompressFiles[i] + " to " + value.decompressTo, ex);
//flag = false;
} }
/*if(!flag)
if(MessageBox.Show(C.i18n("launch.not_finished_decompressing_natives"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
flag = true;*/
return true; return true;
}); });
} }

View File

@@ -104,8 +104,14 @@ public class GameLauncher {
File file = provider.getDecompressNativesToLocation(); File file = provider.getDecompressNativesToLocation();
if (file != null) FileUtils.cleanDirectoryQuietly(file); if (file != null) FileUtils.cleanDirectoryQuietly(file);
if(!downloadLibrariesEvent.execute(provider.getDownloadLibraries(downloadType))) { failEvent.execute(C.i18n("launch.failed")); return null; } if (!downloadLibrariesEvent.execute(provider.getDownloadLibraries(downloadType))) {
if(!decompressNativesEvent.execute(provider.getDecompressLibraries())) { failEvent.execute(C.i18n("launch.failed")); return null; } failEvent.execute(C.i18n("launch.failed"));
return null;
}
if (!decompressNativesEvent.execute(provider.getDecompressLibraries())) {
failEvent.execute(C.i18n("launch.failed"));
return null;
}
successEvent.execute(loader.makeLaunchingCommand()); successEvent.execute(loader.makeLaunchingCommand());
return loader; return loader;
} }
@@ -185,6 +191,7 @@ public class GameLauncher {
} }
public static class DecompressLibraryJob { public static class DecompressLibraryJob {
File[] decompressFiles; File[] decompressFiles;
String[][] extractRules; String[][] extractRules;
File decompressTo; File decompressTo;

View File

@@ -23,5 +23,6 @@ import java.util.List;
* @author huangyuhui * @author huangyuhui
*/ */
public interface IMinecraftLoader { public interface IMinecraftLoader {
List<String> makeLaunchingCommand(); List<String> makeLaunchingCommand();
} }

View File

@@ -29,6 +29,7 @@ import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion;
* @author huangyuhui * @author huangyuhui
*/ */
public abstract class IMinecraftProvider { public abstract class IMinecraftProvider {
Profile profile; Profile profile;
public IMinecraftProvider(Profile profile) { public IMinecraftProvider(Profile profile) {
@@ -36,18 +37,28 @@ public abstract class IMinecraftProvider {
} }
public abstract File getRunDirectory(String id); public abstract File getRunDirectory(String id);
public abstract List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType type); public abstract List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType type);
public abstract void openSelf(String version); public abstract void openSelf(String version);
public abstract void open(String version, String folder); public abstract void open(String version, String folder);
public abstract File getAssets(); public abstract File getAssets();
public abstract File getResourcePacks(); public abstract File getResourcePacks();
public abstract GameLauncher.DecompressLibraryJob getDecompressLibraries(); public abstract GameLauncher.DecompressLibraryJob getDecompressLibraries();
public abstract File getDecompressNativesToLocation(); public abstract File getDecompressNativesToLocation();
public abstract File getMinecraftJar(); public abstract File getMinecraftJar();
public abstract File getBaseFolder(); public abstract File getBaseFolder();
/** /**
* Launch * Launch
*
* @param p player informations, including username & auth_token * @param p player informations, including username & auth_token
* @param type according to the class name 233 * @param type according to the class name 233
* @return what you want * @return what you want
@@ -57,14 +68,21 @@ public abstract class IMinecraftProvider {
// Versions // Versions
public abstract boolean renameVersion(String from, String to); public abstract boolean renameVersion(String from, String to);
public abstract boolean removeVersionFromDisk(String a); public abstract boolean removeVersionFromDisk(String a);
public abstract boolean refreshJson(String a); public abstract boolean refreshJson(String a);
public abstract boolean refreshAssetsIndex(String a); public abstract boolean refreshAssetsIndex(String a);
public abstract MinecraftVersion getOneVersion(); public abstract MinecraftVersion getOneVersion();
public abstract Collection<MinecraftVersion> getVersions(); public abstract Collection<MinecraftVersion> getVersions();
public abstract MinecraftVersion getVersionById(String id); public abstract MinecraftVersion getVersionById(String id);
public abstract int getVersionCount(); public abstract int getVersionCount();
public abstract void refreshVersions(); public abstract void refreshVersions();
public abstract boolean install(String version, DownloadType type); public abstract boolean install(String version, DownloadType type);

View File

@@ -36,7 +36,7 @@ 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

@@ -31,25 +31,24 @@ public final class MinecraftCrashAdvicer {
public static String getAdvice(String trace, boolean selfCrash) { public static String getAdvice(String trace, boolean selfCrash) {
trace = trace.toLowerCase(); trace = trace.toLowerCase();
if(trace.contains("pixel format not accelerated")) { if (trace.contains("pixel format not accelerated"))
return C.i18n("crash.advice.LWJGLException"); return C.i18n("crash.advice.LWJGLException");
} else if (trace.contains("unsupportedclassversionrrror")) { else if (trace.contains("unsupportedclassversionrrror"))
return C.i18n("crash.advice.UnsupportedClassVersionError"); return C.i18n("crash.advice.UnsupportedClassVersionError");
} else if (trace.contains("concurrentmodificationexception")) { else if (trace.contains("concurrentmodificationexception"))
return C.i18n("crash.advice.ConcurrentModificationException"); return C.i18n("crash.advice.ConcurrentModificationException");
} else if (trace.contains("securityexception")) { else if (trace.contains("securityexception"))
return C.i18n("crash.advice.SecurityException"); return C.i18n("crash.advice.SecurityException");
} else if (trace.contains("nosuchfieldexception") || trace.contains("nosuchfielderror")) { else if (trace.contains("nosuchfieldexception") || trace.contains("nosuchfielderror"))
return C.i18n("crash.advice.NoSuchFieldError"); return C.i18n("crash.advice.NoSuchFieldError");
} else if (trace.contains("outofmemory") || trace.contains("out of memory")) { else if (trace.contains("outofmemory") || trace.contains("out of memory"))
return C.i18n("crash.advice.OutOfMemoryError"); return C.i18n("crash.advice.OutOfMemoryError");
} else if (trace.contains("noclassdeffounderror") || trace.contains("classnotfoundexception")) { else if (trace.contains("noclassdeffounderror") || trace.contains("classnotfoundexception"))
return C.i18n("crash.advice.ClassNotFoundException"); return C.i18n("crash.advice.ClassNotFoundException");
} else if (trace.contains("no lwjgl in java.library.path")) { else if (trace.contains("no lwjgl in java.library.path"))
return C.i18n("crash.advice.no_lwjgl"); return C.i18n("crash.advice.no_lwjgl");
} else if (trace.contains("opengl") || trace.contains("openal")) { else if (trace.contains("opengl") || trace.contains("openal"))
return C.i18n("crash.advice.OpenGL"); return C.i18n("crash.advice.OpenGL");
}
return C.i18n(selfCrash ? "crash.advice.no" : "crash.advice.otherwise"); return C.i18n(selfCrash ? "crash.advice.no" : "crash.advice.otherwise");
} }

View File

@@ -31,6 +31,7 @@ import org.jackhuang.hellominecraft.utils.system.OS;
* @author huangyuhui * @author huangyuhui
*/ */
public final class Config { public final class Config {
@SerializedName("last") @SerializedName("last")
private String last; private String last;
@SerializedName("bgpath") @SerializedName("bgpath")
@@ -119,7 +120,7 @@ public final class Config {
} }
public TreeMap<String, Profile> getConfigurations() { public TreeMap<String, Profile> getConfigurations() {
if(configurations == null) if (configurations == null)
configurations = new TreeMap<>(); configurations = new TreeMap<>();
return configurations; return configurations;
} }
@@ -153,21 +154,20 @@ public final class Config {
@SerializedName("yggdrasil") @SerializedName("yggdrasil")
private Map yggdrasil; private Map yggdrasil;
public Config() public Config() {
{
clientToken = UUID.randomUUID().toString(); clientToken = UUID.randomUUID().toString();
username = ""; username = "";
logintype = downloadtype = 0; logintype = downloadtype = 0;
checkUpdate = true; checkUpdate = true;
configurations = new TreeMap<>(); configurations = new TreeMap<>();
Profile profile = new Profile(); Profile profile = new Profile();
configurations.put(profile.getName(), profile); configurations.put(profile.getName(), profile);
enableShadow = OS.os() == OS.WINDOWS; enableShadow = OS.os() == OS.WINDOWS;
theme = 0; theme = 0;
} }
public DownloadType getDownloadSource() { public DownloadType getDownloadSource() {
if(downloadtype >= DownloadType.values().length || downloadtype < 0) return null; if (downloadtype >= DownloadType.values().length || downloadtype < 0) return null;
return DownloadType.values()[downloadtype]; return DownloadType.values()[downloadtype];
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.settings;
* @author huangyuhui * @author huangyuhui
*/ */
public enum LauncherVisibility { public enum LauncherVisibility {
CLOSE, CLOSE,
HIDE, HIDE,
KEEP KEEP

View File

@@ -53,32 +53,30 @@ public final class Profile {
protected transient IMinecraftProvider minecraftProvider; protected transient IMinecraftProvider minecraftProvider;
public Profile() { public Profile() {
this("Default"); this("Default");
} }
public Profile(String name) { public Profile(String name) {
this.name = name; this.name = name;
gameDir = MCUtils.getInitGameDir().getPath(); gameDir = MCUtils.getInitGameDir().getPath();
debug = fullscreen = canceledWrapper = false; debug = fullscreen = canceledWrapper = false;
javaDir = IOUtils.getJavaDir(); javaDir = IOUtils.getJavaDir();
launcherVisibility = gameDirType = 0; launcherVisibility = gameDirType = 0;
minecraftArgs = serverIp = ""; minecraftArgs = serverIp = "";
} }
public Profile(Profile v) { public Profile(Profile v) {
this(); this();
if (v == null) { if (v == null) return;
return; name = v.name;
} gameDir = v.gameDir;
name = v.name; maxMemory = v.maxMemory;
gameDir = v.gameDir; width = v.width;
maxMemory = v.maxMemory; height = v.height;
width = v.width; fullscreen = v.fullscreen;
height = v.height; javaArgs = v.javaArgs;
fullscreen = v.fullscreen; javaDir = v.javaDir;
javaArgs = v.javaArgs; debug = v.debug;
javaDir = v.javaDir;
debug = v.debug;
minecraftArgs = v.minecraftArgs; minecraftArgs = v.minecraftArgs;
permSize = v.permSize; permSize = v.permSize;
gameDirType = v.gameDirType; gameDirType = v.gameDirType;
@@ -90,89 +88,84 @@ 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) { if (v == null) return null;
return null; selectedMinecraftVersion = v.id;
} return v;
selectedMinecraftVersion = v.id; }
return v; MinecraftVersion v = getMinecraftProvider().getVersionById(selectedMinecraftVersion);
} if (v == null) v = getMinecraftProvider().getOneVersion();
MinecraftVersion v = getMinecraftProvider().getVersionById(selectedMinecraftVersion); if (v != null) setSelectedMinecraftVersion(v.id);
if(v == null) v = getMinecraftProvider().getOneVersion(); return v;
if(v != null) setSelectedMinecraftVersion(v.id);
return v;
} }
public String getGameDir() { public String getGameDir() {
if (StrUtils.isBlank(gameDir)) { if (StrUtils.isBlank(gameDir)) gameDir = MCUtils.getInitGameDir().getPath();
gameDir = MCUtils.getInitGameDir().getPath(); return IOUtils.addSeparator(gameDir);
}
return IOUtils.addSeparator(gameDir);
} }
public String getCanonicalGameDir() { public String getCanonicalGameDir() {
return IOUtils.tryGetCanonicalFolderPath(getGameDirFile()); return IOUtils.tryGetCanonicalFolderPath(getGameDirFile());
} }
public File getCanonicalGameDirFile() { public File getCanonicalGameDirFile() {
return IOUtils.tryGetCanonicalFile(getGameDirFile()); return IOUtils.tryGetCanonicalFile(getGameDirFile());
} }
public File getGameDirFile() { public File getGameDirFile() {
return new File(getGameDir()); return new File(getGameDir());
} }
public Profile setGameDir(String gameDir) { public Profile setGameDir(String gameDir) {
this.gameDir = gameDir; this.gameDir = gameDir;
Settings.save(); Settings.save();
return this; return this;
} }
public String getJavaDir() { public String getJavaDir() {
if (StrUtils.isBlank(javaDir)) { if (StrUtils.isBlank(javaDir))
javaDir = IOUtils.getJavaDir(); javaDir = IOUtils.getJavaDir();
} return javaDir;
return javaDir;
} }
public File getJavaDirFile() { public File getJavaDirFile() {
return new File(getJavaDir()); return new File(getJavaDir());
} }
public void setJavaDir(String javaDir) { public void setJavaDir(String javaDir) {
this.javaDir = javaDir; this.javaDir = javaDir;
Settings.save(); Settings.save();
} }
public File getFolder(String folder) { public File getFolder(String folder) {
return new File(getGameDir(), folder); return new File(getGameDir(), folder);
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public void setSelectedMinecraftVersion(String selectedMinecraftVersion) { public void setSelectedMinecraftVersion(String selectedMinecraftVersion) {
this.selectedMinecraftVersion = selectedMinecraftVersion; this.selectedMinecraftVersion = selectedMinecraftVersion;
} }
public String getJavaArgs() { public String getJavaArgs() {
if(StrUtils.isBlank(javaArgs)) return ""; if (StrUtils.isBlank(javaArgs)) return "";
return javaArgs; return javaArgs;
} }
public void setJavaArgs(String javaArgs) { public void setJavaArgs(String javaArgs) {
this.javaArgs = javaArgs; this.javaArgs = javaArgs;
Settings.save(); Settings.save();
} }
@@ -181,76 +174,76 @@ 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;
} }
public void setMaxMemory(String maxMemory) { public void setMaxMemory(String maxMemory) {
this.maxMemory = maxMemory; this.maxMemory = maxMemory;
Settings.save(); Settings.save();
} }
public String getWidth() { public String getWidth() {
if(StrUtils.isBlank(width)) return "854"; if (StrUtils.isBlank(width)) return "854";
return width; return width;
} }
public void setWidth(String width) { public void setWidth(String width) {
this.width = width; this.width = width;
} }
public String getHeight() { public String getHeight() {
if(StrUtils.isBlank(height)) return "480"; if (StrUtils.isBlank(height)) return "480";
return height; return height;
} }
public void setHeight(String height) { public void setHeight(String height) {
this.height = height; this.height = height;
Settings.save(); Settings.save();
} }
public String getUserProperties() { public String getUserProperties() {
if(userProperties == null) return ""; if (userProperties == null) return "";
return userProperties; return userProperties;
} }
public void setUserProperties(String userProperties) { public void setUserProperties(String userProperties) {
this.userProperties = userProperties; this.userProperties = userProperties;
} }
public boolean isFullscreen() { public boolean isFullscreen() {
return fullscreen; return fullscreen;
} }
public void setFullscreen(boolean fullscreen) { public void setFullscreen(boolean fullscreen) {
this.fullscreen = fullscreen; this.fullscreen = fullscreen;
Settings.save(); Settings.save();
} }
public boolean isDebug() { public boolean isDebug() {
return debug; return debug;
} }
public void setDebug(boolean debug) { public void setDebug(boolean debug) {
this.debug = debug; this.debug = debug;
Settings.save(); Settings.save();
} }
public LauncherVisibility getLauncherVisibility() { public LauncherVisibility getLauncherVisibility() {
return LauncherVisibility.values()[launcherVisibility]; return LauncherVisibility.values()[launcherVisibility];
} }
public void setLauncherVisibility(LauncherVisibility launcherVisibility) { public void setLauncherVisibility(LauncherVisibility launcherVisibility) {
this.launcherVisibility = launcherVisibility.ordinal(); this.launcherVisibility = launcherVisibility.ordinal();
Settings.save(); Settings.save();
} }
public GameDirType getGameDirType() { public GameDirType getGameDirType() {
return GameDirType.values()[gameDirType]; return GameDirType.values()[gameDirType];
} }
public void setGameDirType(GameDirType gameDirType) { public void setGameDirType(GameDirType gameDirType) {
this.gameDirType = gameDirType.ordinal(); this.gameDirType = gameDirType.ordinal();
Settings.save(); Settings.save();
} }

View File

@@ -61,9 +61,8 @@ public final class Settings {
if (!getVersions().containsKey(DEFAULT_PROFILE)) if (!getVersions().containsKey(DEFAULT_PROFILE))
getVersions().put(DEFAULT_PROFILE, new Profile()); getVersions().put(DEFAULT_PROFILE, new Profile());
for(Profile e : getVersions().values()) { for (Profile e : getVersions().values())
e.checkFormat(); e.checkFormat();
}
UPDATE_CHECKER = new UpdateChecker(new VersionNumber(Main.firstVer, Main.secondVer, Main.thirdVer), UPDATE_CHECKER = new UpdateChecker(new VersionNumber(Main.firstVer, Main.secondVer, Main.thirdVer),
"hmcl", settings.isCheckUpdate(), () -> Main.invokeUpdate()); "hmcl", settings.isCheckUpdate(), () -> Main.invokeUpdate());

View File

@@ -84,8 +84,8 @@ public final class MCUtils {
String ver = new String(tmp, i, j - i, "ASCII"); String ver = new String(tmp, i, j - i, "ASCII");
r.version = ver; r.version = ver;
r.type = file.getEntry("META-INF/MANIFEST.MF") == null ? r.type = file.getEntry("META-INF/MANIFEST.MF") == null
MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK; ? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r; return r;
} }
@@ -134,8 +134,8 @@ public final class MCUtils {
k++; k++;
r.version = new String(tmp, k, i - k + 1); r.version = new String(tmp, k, i - k + 1);
} }
r.type = file.getEntry("META-INF/MANIFEST.MF") == null ? r.type = file.getEntry("META-INF/MANIFEST.MF") == null
MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK; ? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r; return r;
} }
@@ -297,9 +297,10 @@ public final class MCUtils {
} }
public static String profile = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}"; public static String profile = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}";
public static void tryWriteProfile(File gameDir) throws IOException { public static void tryWriteProfile(File gameDir) throws IOException {
File file = new File(gameDir, "launcher_profiles.json"); File file = new File(gameDir, "launcher_profiles.json");
if(!file.exists()) if (!file.exists())
FileUtils.writeStringToFile(file, profile); FileUtils.writeStringToFile(file, profile);
} }
} }

View File

@@ -32,18 +32,18 @@ public class AssetsIndex {
private boolean virtual; private boolean virtual;
public AssetsIndex() { public AssetsIndex() {
this.objects = new LinkedHashMap(); this.objects = new LinkedHashMap();
} }
public Map<String, AssetsObject> getFileMap() { public Map<String, AssetsObject> getFileMap() {
return this.objects; return this.objects;
} }
public Set<AssetsObject> getUniqueObjects() { public Set<AssetsObject> getUniqueObjects() {
return new HashSet(this.objects.values()); return new HashSet(this.objects.values());
} }
public boolean isVirtual() { public boolean isVirtual() {
return this.virtual; return this.virtual;
} }
} }

View File

@@ -54,21 +54,16 @@ public class AssetsLoader extends Thread {
for (int i = 0; i < contents.getLength(); i++) { for (int i = 0; i < contents.getLength(); i++) {
Node result = contents.item(i); Node result = contents.item(i);
if (result.getNodeType() == Node.ELEMENT_NODE) { if (result.getNodeType() == Node.ELEMENT_NODE) {
if (result.getNodeName().equalsIgnoreCase("Key")) { if (result.getNodeName().equalsIgnoreCase("Key"))
ret.key = result.getTextContent(); ret.key = result.getTextContent();
} if (result.getNodeName().equalsIgnoreCase("ETag"))
if (result.getNodeName().equalsIgnoreCase("ETag")) {
ret.eTag = result.getTextContent(); ret.eTag = result.getTextContent();
} if (result.getNodeName().equalsIgnoreCase("LastModified"))
if (result.getNodeName().equalsIgnoreCase("LastModified")) {
ret.lastModified = result.getTextContent(); ret.lastModified = result.getTextContent();
} if (result.getNodeName().equalsIgnoreCase("Size"))
if (result.getNodeName().equalsIgnoreCase("Size")) {
ret.size = MathUtils.parseInt(result.getTextContent(), 0); ret.size = MathUtils.parseInt(result.getTextContent(), 0);
} if (result.getNodeName().equalsIgnoreCase("StorageClass"))
if (result.getNodeName().equalsIgnoreCase("StorageClass")) {
ret.storageClass = result.getTextContent(); ret.storageClass = result.getTextContent();
}
} }
} }
return ret; return ret;
@@ -90,7 +85,7 @@ public class AssetsLoader extends Thread {
Node result = nodes.item(i); Node result = nodes.item(i);
if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("Contents")) { if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("Contents")) {
Contents c = modifyContents(result.getChildNodes()); Contents c = modifyContents(result.getChildNodes());
if(c.key != null) if (c.key != null)
al.add(c); al.add(c);
} }
} }

View File

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

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.assets;
* @author huangyuhui * @author huangyuhui
*/ */
public class AssetsObject { public class AssetsObject {
private String hash; private String hash;
private long size; private long size;
@@ -28,26 +29,26 @@ public class AssetsObject {
} }
public String getHash() { public String getHash() {
return this.hash; return this.hash;
} }
public long getSize() { public long getSize() {
return this.size; return this.size;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; 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);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = this.hash.hashCode(); int result = this.hash.hashCode();
result = 31 * result + (int) (this.size ^ this.size >>> 32); result = 31 * result + (int) (this.size ^ this.size >>> 32);
return result; return result;
} }
} }

View File

@@ -62,7 +62,6 @@ public abstract class IAssetsHandler {
static { static {
assetsHandlers.add(new AssetsMojangLoader(C.i18n("assets.list.1_7_3_after"))); assetsHandlers.add(new AssetsMojangLoader(C.i18n("assets.list.1_7_3_after")));
//assetsHandlers.add(new AssetsMojangOldLoader(C.i18n("assets.list.1_6")));
} }
/** /**

View File

@@ -30,28 +30,26 @@ public abstract class IAuthenticator {
public static final YggdrasilAuthenticator yggdrasilLogin; public static final YggdrasilAuthenticator yggdrasilLogin;
public static final OfflineAuthenticator offlineLogin; public static final OfflineAuthenticator offlineLogin;
public static final SkinmeAuthenticator skinmeLogin; public static final SkinmeAuthenticator skinmeLogin;
//public static final BestLogin bestLogin;
public static final List<IAuthenticator> logins; public static final List<IAuthenticator> logins;
static { static {
String clientToken = Settings.getInstance().getClientToken(); String clientToken = Settings.getInstance().getClientToken();
logins = new ArrayList<>(); logins = new ArrayList<>();
logins.add(offlineLogin = new OfflineAuthenticator(clientToken)); logins.add(offlineLogin = new OfflineAuthenticator(clientToken));
logins.add(yggdrasilLogin = new YggdrasilAuthenticator(clientToken)); logins.add(yggdrasilLogin = new YggdrasilAuthenticator(clientToken));
logins.add(skinmeLogin = new SkinmeAuthenticator(clientToken)); logins.add(skinmeLogin = new SkinmeAuthenticator(clientToken));
//logins.add(bestLogin = new BestLogin(clientToken)); yggdrasilLogin.onLoadSettings(Settings.getInstance().getYggdrasilConfig());
yggdrasilLogin.onLoadSettings(Settings.getInstance().getYggdrasilConfig());
Runtime.getRuntime().addShutdownHook(new Thread(() -> Runtime.getRuntime().addShutdownHook(new Thread(()
Settings.getInstance().setYggdrasilConfig(yggdrasilLogin.onSaveSettings()) -> Settings.getInstance().setYggdrasilConfig(yggdrasilLogin.onSaveSettings())
)); ));
} }
protected String clientToken; protected String clientToken;
public IAuthenticator(String clientToken) { public IAuthenticator(String clientToken) {
this.clientToken = clientToken; this.clientToken = clientToken;
} }
/** /**
@@ -74,11 +72,11 @@ public abstract class IAuthenticator {
* @return Will I hide password box? * @return Will I hide password box?
*/ */
public boolean isHidePasswordBox() { public boolean isHidePasswordBox() {
return false; return false;
} }
public boolean isLoggedIn() { public boolean isLoggedIn() {
return false; return false;
} }
public void setRememberMe(boolean is) { public void setRememberMe(boolean is) {

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.auth;
* @author huangyuhui * @author huangyuhui
*/ */
public final class LoginInfo { public final class LoginInfo {
public String username, password; public String username, password;
public LoginInfo(String username, String password) { public LoginInfo(String username, String password) {

View File

@@ -41,9 +41,9 @@ 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")) return getForgeInstaller();
if(type.equalsIgnoreCase("liteloader")) return getLiteLoaderInstaller(); if (type.equalsIgnoreCase("liteloader")) return getLiteLoaderInstaller();
if(type.equalsIgnoreCase("optifine")) return getOptiFineInstaller(); if (type.equalsIgnoreCase("optifine")) return getOptiFineInstaller();
return null; return null;
} }
@@ -64,12 +64,12 @@ public class BMCLAPIDownloadProvider implements IDownloadProvider {
@Override @Override
public String getVersionsListDownloadURL() { public String getVersionsListDownloadURL() {
return "http://bmclapi2.bangbang93.com/versions/versions.json"; return "http://bmclapi2.bangbang93.com/versions/versions.json";
} }
@Override @Override
public String getAssetsDownloadURL() { public String getAssetsDownloadURL() {
return "http://bmclapi2.bangbang93.com/assets/"; return "http://bmclapi2.bangbang93.com/assets/";
} }
@Override @Override

View File

@@ -23,6 +23,7 @@ import org.jackhuang.hellominecraft.C;
* @author huangyuhui * @author huangyuhui
*/ */
public enum DownloadType { public enum DownloadType {
Mojang(C.i18n("download.mojang"), new MojangDownloadProvider()), Mojang(C.i18n("download.mojang"), new MojangDownloadProvider()),
BMCL(C.i18n("download.BMCL"), new BMCLAPIDownloadProvider()); BMCL(C.i18n("download.BMCL"), new BMCLAPIDownloadProvider());

View File

@@ -23,14 +23,24 @@ import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerVersionLi
* @author huangyuhui * @author huangyuhui
*/ */
public interface IDownloadProvider { public interface IDownloadProvider {
InstallerVersionList getInstallerByType(String type); InstallerVersionList getInstallerByType(String type);
InstallerVersionList getForgeInstaller(); InstallerVersionList getForgeInstaller();
InstallerVersionList getLiteLoaderInstaller(); InstallerVersionList getLiteLoaderInstaller();
InstallerVersionList getOptiFineInstaller(); InstallerVersionList getOptiFineInstaller();
String getLibraryDownloadURL(); String getLibraryDownloadURL();
String getVersionsDownloadURL(); String getVersionsDownloadURL();
String getIndexesDownloadURL(); String getIndexesDownloadURL();
String getVersionsListDownloadURL(); String getVersionsListDownloadURL();
String getAssetsDownloadURL(); String getAssetsDownloadURL();
boolean isAllowedToUseSelfURL(); boolean isAllowedToUseSelfURL();
} }

View File

@@ -41,9 +41,9 @@ 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")) return getForgeInstaller();
if(type.equalsIgnoreCase("liteloader")) return getLiteLoaderInstaller(); if (type.equalsIgnoreCase("liteloader")) return getLiteLoaderInstaller();
if(type.equalsIgnoreCase("optifine")) return getOptiFineInstaller(); if (type.equalsIgnoreCase("optifine")) return getOptiFineInstaller();
return null; return null;
} }

View File

@@ -25,6 +25,7 @@ import org.jackhuang.hellominecraft.launcher.utils.installers.forge.Install;
* @author huangyuhui * @author huangyuhui
*/ */
public class InstallProfile { public class InstallProfile {
@SerializedName("install") @SerializedName("install")
public Install install; public Install install;
@SerializedName("versionInfo") @SerializedName("versionInfo")

View File

@@ -25,24 +25,29 @@ import org.jackhuang.hellominecraft.utils.functions.Consumer;
* @author huangyuhui * @author huangyuhui
*/ */
public abstract class InstallerVersionList implements Consumer<String[]> { 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;
public abstract String getName(); public abstract String getName();
public abstract List<InstallerVersion> getVersions(String mcVersion); public abstract List<InstallerVersion> getVersions(String mcVersion);
public static class InstallerVersion implements Comparable<InstallerVersion> { public static class InstallerVersion implements Comparable<InstallerVersion> {
public String selfVersion, mcVersion;
public String installer, universal; public String selfVersion, mcVersion;
public String installer, universal;
public String changelog; public String changelog;
public InstallerVersion(String selfVersion, String mcVersion) { public InstallerVersion(String selfVersion, String mcVersion) {
this.selfVersion = selfVersion; this.selfVersion = selfVersion;
this.mcVersion = mcVersion; this.mcVersion = mcVersion;
} }
@Override @Override
public int compareTo(InstallerVersion o) { public int compareTo(InstallerVersion o) {
@@ -51,7 +56,9 @@ public abstract class InstallerVersionList implements Consumer<String[]> {
} }
public static class InstallerVersionComparator implements Comparator<InstallerVersion> { public static class InstallerVersionComparator implements Comparator<InstallerVersion> {
public static final InstallerVersionComparator INSTANCE = new InstallerVersionComparator(); public static final InstallerVersionComparator INSTANCE = new InstallerVersionComparator();
@Override @Override
public int compare(InstallerVersion o1, InstallerVersion o2) { public int compare(InstallerVersion o1, InstallerVersion o2) {
return o2.compareTo(o1); return o2.compareTo(o1);

View File

@@ -48,8 +48,8 @@ public class ForgeInstaller extends Task {
public IMinecraftProvider mp; public IMinecraftProvider mp;
public ForgeInstaller(IMinecraftProvider mp, File forgeInstaller) { public ForgeInstaller(IMinecraftProvider mp, File forgeInstaller) {
this.gameDir = mp.getBaseFolder(); this.gameDir = mp.getBaseFolder();
this.forgeInstaller = forgeInstaller; this.forgeInstaller = forgeInstaller;
this.mp = mp; this.mp = mp;
} }
@@ -64,14 +64,12 @@ public class ForgeInstaller extends Task {
InstallProfile profile = gson.fromJson(content, InstallProfile.class); InstallProfile profile = gson.fromJson(content, InstallProfile.class);
File from = new File(gameDir, "versions" + File.separator + profile.install.minecraft); File from = new File(gameDir, "versions" + File.separator + profile.install.minecraft);
if(!from.exists()) { if (!from.exists()) {
if(MessageBox.Show(C.i18n("install.no_version_if_intall")) == MessageBox.YES_OPTION) { if (MessageBox.Show(C.i18n("install.no_version_if_intall")) == MessageBox.YES_OPTION) {
if(!mp.install(profile.install.minecraft, Settings.getInstance().getDownloadSource())) { if (!mp.install(profile.install.minecraft, Settings.getInstance().getDownloadSource()))
setFailReason(new RuntimeException(C.i18n("install.no_version"))); setFailReason(new RuntimeException(C.i18n("install.no_version")));
} } else
} else {
setFailReason(new RuntimeException(C.i18n("install.no_version"))); setFailReason(new RuntimeException(C.i18n("install.no_version")));
}
return false; return false;
} }
@@ -100,7 +98,7 @@ public class ForgeInstaller extends Task {
bos.close(); bos.close();
} }
return true; return true;
} catch(IOException | JsonSyntaxException e) { } catch (IOException | JsonSyntaxException e) {
setFailReason(e); setFailReason(e);
return false; return false;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.forge;
* @author huangyuhui * @author huangyuhui
*/ */
public class Install { public class Install {
public String profileName; public String profileName;
public String target; public String target;
public String path; public String path;

View File

@@ -49,21 +49,21 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] neededVersions) throws Exception { public void refreshList(String[] neededVersions) throws Exception {
if(versionMap == null) { if (versionMap == null) {
versionMap = new HashMap<>(); versionMap = new HashMap<>();
versions = new ArrayList<>(); versions = new ArrayList<>();
} }
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)
continue; continue;
}
try { try {
root = C.gson.fromJson(s, new TypeToken<ArrayList<ForgeVersion>>(){}.getType()); root = C.gson.fromJson(s, new TypeToken<ArrayList<ForgeVersion>>() {
}.getType());
for (ForgeVersion v : root) { for (ForgeVersion v : root) {
InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.minecraft)); InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.minecraft));
@@ -74,7 +74,7 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
al.add(iv); al.add(iv);
versions.add(iv); versions.add(iv);
} }
} catch(JsonSyntaxException e) { } catch (JsonSyntaxException e) {
HMCLog.warn("Failed to parse BMCLAPI2 response.", e); HMCLog.warn("Failed to parse BMCLAPI2 response.", e);
} }
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.forge.bmcl;
* @author huangyuhui * @author huangyuhui
*/ */
public class ForgeVersion { public class ForgeVersion {
public String time, minecraft, version, _id, __v; public String time, minecraft, version, _id, __v;
public Downloads downloads; public Downloads downloads;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.forge.vanilla;
* @author huangyuhui * @author huangyuhui
*/ */
public class MinecraftForgeVersion { public class MinecraftForgeVersion {
public String branch, mcversion, jobver, version; public String branch, mcversion, jobver, version;
public int build; public int build;
public double modified; public double modified;

View File

@@ -32,11 +32,13 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
* @author huangyuhui * @author huangyuhui
*/ */
public class MinecraftForgeVersionList extends InstallerVersionList { public class MinecraftForgeVersionList extends InstallerVersionList {
private static MinecraftForgeVersionList instance; private static MinecraftForgeVersionList instance;
public static MinecraftForgeVersionList getInstance() { public static MinecraftForgeVersionList getInstance() {
if(instance == null) if (instance == null)
instance = new MinecraftForgeVersionList(); instance = new MinecraftForgeVersionList();
return instance; return instance;
} }
public MinecraftForgeVersionRoot root; public MinecraftForgeVersionRoot root;
@@ -46,45 +48,47 @@ 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(C.URL_FORGE_LIST); String s = NetUtils.doGet(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);
versionMap = new HashMap<String, List<InstallerVersion>>(); versionMap = new HashMap<>();
versions = new ArrayList<InstallerVersion>(); versions = new ArrayList<>();
for(Map.Entry<String, int[]> arr : root.mcversion.entrySet()) { for (Map.Entry<String, int[]> arr : root.mcversion.entrySet()) {
String mcver = StrUtils.formatVersion(arr.getKey()); String mcver = StrUtils.formatVersion(arr.getKey());
ArrayList<InstallerVersion> al = new ArrayList<InstallerVersion>(); ArrayList<InstallerVersion> al = new ArrayList<>();
for(int num : arr.getValue()) { for (int num : arr.getValue()) {
MinecraftForgeVersion v = root.number.get(num); MinecraftForgeVersion v = root.number.get(num);
InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.mcversion)); InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.mcversion));
for(String[] f : v.files) { for (String[] f : v.files) {
String ver = v.mcversion + "-" + v.version; String ver = v.mcversion + "-" + v.version;
if(!StrUtils.isBlank(v.branch)) { if (!StrUtils.isBlank(v.branch))
ver = ver + "-" + v.branch; ver = ver + "-" + v.branch;
} String filename = root.artifact + "-" + ver + "-" + f[1] + "." + f[0];
String filename = root.artifact + "-" + ver + "-" + f[1] + "." + f[0]; String url = root.webpath + "/" + ver + "/" + filename;
String url = root.webpath + "/" + ver + "/" + filename; switch (f[1]) {
if(f[1].equals("installer")) { case "installer":
iv.installer = url; iv.installer = url;
} else if(f[1].equals("universal")) { break;
iv.universal = url; case "universal":
} else if(f[1].equals("changelog")) { iv.universal = url;
iv.changelog = url; break;
} case "changelog":
} iv.changelog = url;
if(StrUtils.isBlank(iv.installer) || StrUtils.isBlank(iv.universal)) { break;
continue; }
} }
if (StrUtils.isBlank(iv.installer) || StrUtils.isBlank(iv.universal))
continue;
Collections.sort(al, new InstallerVersionNewerComparator()); Collections.sort(al, new InstallerVersionNewerComparator());
al.add(iv); al.add(iv);
versions.add(iv); versions.add(iv);
} }
versionMap.put(StrUtils.formatVersion(mcver), al); versionMap.put(StrUtils.formatVersion(mcver), al);
} }
Collections.sort(versions, new InstallerVersionComparator()); Collections.sort(versions, new InstallerVersionComparator());
} }
@@ -92,11 +96,11 @@ 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) return null;
if(StrUtils.isBlank(mcVersion)) return versions; 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;
} }
@Override @Override

View File

@@ -23,6 +23,7 @@ import java.util.Map;
* @author huangyuhui * @author huangyuhui
*/ */
public class MinecraftForgeVersionRoot { public class MinecraftForgeVersionRoot {
public String artifact, webpath, adfly, homepage, name; public String artifact, webpath, adfly, homepage, name;
public Map<String, int[]> branches, mcversion; public Map<String, int[]> branches, mcversion;
public Map<String, Integer> promos; public Map<String, Integer> promos;

View File

@@ -51,12 +51,12 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrat
@Override @Override
public boolean executeTask() { public boolean executeTask() {
if(profile == null || profile.getSelectedMinecraftVersion() == null) { if (profile == null || profile.getSelectedMinecraftVersion() == null) {
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 {
MinecraftVersion mv = (MinecraftVersion) profile.getSelectedMinecraftVersion().clone(); MinecraftVersion mv = (MinecraftVersion) profile.getSelectedMinecraftVersion().clone();
@@ -69,7 +69,7 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrat
mv.id += "-LiteLoader" + version.selfVersion; mv.id += "-LiteLoader" + version.selfVersion;
if(!mv.mainClass.startsWith("net.minecraft.launchwrapper.")) { if (!mv.mainClass.startsWith("net.minecraft.launchwrapper.")) {
mv.mainClass = "net.minecraft.launchwrapper.Launch"; mv.mainClass = "net.minecraft.launchwrapper.Launch";
mv.minecraftArguments += " --tweakClass " + version.tweakClass; mv.minecraftArguments += " --tweakClass " + version.tweakClass;
} }
@@ -92,6 +92,7 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrat
} }
ArrayList<PreviousResult<File>> pre = new ArrayList<>(); ArrayList<PreviousResult<File>> pre = new ArrayList<>();
@Override @Override
public Task registerPreviousResult(PreviousResult pr) { public Task registerPreviousResult(PreviousResult pr) {
pre.add(pr); pre.add(pr);

View File

@@ -23,5 +23,6 @@ import java.util.Map;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderMCVersions { public class LiteLoaderMCVersions {
public Map<String, Map<String, LiteLoaderVersion>> artefacts; public Map<String, Map<String, LiteLoaderVersion>> artefacts;
} }

View File

@@ -23,6 +23,7 @@ import org.jackhuang.hellominecraft.launcher.version.MinecraftLibrary;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersion { public class LiteLoaderVersion {
public String tweakClass, file, version, md5, timestamp; public String tweakClass, file, version, md5, timestamp;
public MinecraftLibrary[] libraries; public MinecraftLibrary[] libraries;
} }

View File

@@ -35,12 +35,13 @@ import org.jackhuang.hellominecraft.utils.StrUtils;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersionList extends InstallerVersionList { public class LiteLoaderVersionList extends InstallerVersionList {
private static LiteLoaderVersionList instance; private static LiteLoaderVersionList instance;
public static LiteLoaderVersionList getInstance() { public static LiteLoaderVersionList getInstance() {
if(instance == null) { if (instance == null)
instance = new LiteLoaderVersionList(); instance = new LiteLoaderVersionList();
} return instance;
return instance;
} }
public LiteLoaderVersionsRoot root; public LiteLoaderVersionsRoot root;
@@ -50,30 +51,30 @@ 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);
versionMap = new HashMap<>(); versionMap = new HashMap<>();
versions = new ArrayList<>(); versions = new ArrayList<>();
for(Map.Entry<String, LiteLoaderMCVersions> arr : root.versions.entrySet()) { for (Map.Entry<String, LiteLoaderMCVersions> arr : root.versions.entrySet()) {
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;
iv.tweakClass = v.tweakClass; iv.tweakClass = v.tweakClass;
iv.libraries = Arrays.copyOf(v.libraries, v.libraries.length); iv.libraries = Arrays.copyOf(v.libraries, v.libraries.length);
iv.installer = "http://dl.liteloader.com/redist/" + iv.mcVersion + "/liteloader-installer-" + iv.selfVersion.replace("_", "-") + ".jar"; iv.installer = "http://dl.liteloader.com/redist/" + iv.mcVersion + "/liteloader-installer-" + iv.selfVersion.replace("_", "-") + ".jar";
al.add(iv); al.add(iv);
versions.add(iv); versions.add(iv);
} }
Collections.sort(al, new InstallerVersionNewerComparator()); Collections.sort(al, new InstallerVersionNewerComparator());
versionMap.put(StrUtils.formatVersion(arr.getKey()), al); versionMap.put(StrUtils.formatVersion(arr.getKey()), al);
} }
Collections.sort(versions, InstallerVersionComparator.INSTANCE); Collections.sort(versions, InstallerVersionComparator.INSTANCE);
} }
@@ -81,11 +82,11 @@ 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) return null;
if(StrUtils.isBlank(mcVersion)) return versions; 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;
} }
@Override @Override
@@ -94,12 +95,13 @@ public class LiteLoaderVersionList extends InstallerVersionList {
} }
public static class LiteLoaderInstallerVersion extends InstallerVersion { public static class LiteLoaderInstallerVersion extends InstallerVersion {
public MinecraftLibrary[] libraries;
public String tweakClass;
public LiteLoaderInstallerVersion(String selfVersion, String mcVersion) { public MinecraftLibrary[] libraries;
super(selfVersion, mcVersion); public String tweakClass;
}
public LiteLoaderInstallerVersion(String selfVersion, String mcVersion) {
super(selfVersion, mcVersion);
}
} }
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.liteloader;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersionsMeta { public class LiteLoaderVersionsMeta {
public String description, authors, url; public String description, authors, url;
} }

View File

@@ -23,6 +23,7 @@ import java.util.Map;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersionsRoot { public class LiteLoaderVersionsRoot {
public Map<String, LiteLoaderMCVersions> versions; public Map<String, LiteLoaderMCVersions> versions;
public LiteLoaderVersionsMeta meta; public LiteLoaderVersionsMeta meta;
} }

View File

@@ -59,7 +59,7 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
if (s == null) return; if (s == null) return;
root = C.gson.fromJson(s, new TypeToken<ArrayList<OptiFineVersion>>() { root = C.gson.fromJson(s, new TypeToken<ArrayList<OptiFineVersion>>() {
}.getType()); }.getType());
for(OptiFineVersion v : root) { for (OptiFineVersion v : root) {
v.mirror = v.mirror.replace("http://optifine.net/http://optifine.net/", "http://optifine.net/"); v.mirror = v.mirror.replace("http://optifine.net/http://optifine.net/", "http://optifine.net/");
if (StrUtils.isBlank(v.mcver)) { if (StrUtils.isBlank(v.mcver)) {

View File

@@ -28,6 +28,7 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
* @author huangyuhui * @author huangyuhui
*/ */
public class OptiFineDownloadFormatter extends Task implements PreviousResult<String> { public class OptiFineDownloadFormatter extends Task implements PreviousResult<String> {
String url, result; String url, result;
public OptiFineDownloadFormatter(String url) { public OptiFineDownloadFormatter(String url) {
@@ -40,7 +41,7 @@ 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

@@ -44,13 +44,14 @@ import org.xml.sax.SAXException;
* @author huangyuhui * @author huangyuhui
*/ */
public class OptiFineVersionList extends InstallerVersionList { public class OptiFineVersionList extends InstallerVersionList {
private static OptiFineVersionList instance;
public static OptiFineVersionList getInstance() {
if(null == instance)
instance = new OptiFineVersionList();
return instance;
}
private static OptiFineVersionList instance;
public static OptiFineVersionList getInstance() {
if (null == instance)
instance = new OptiFineVersionList();
return instance;
}
public ArrayList<OptiFineVersion> root = new ArrayList(); public ArrayList<OptiFineVersion> root = new ArrayList();
public Map<String, List<InstallerVersion>> versionMap; public Map<String, List<InstallerVersion>> versionMap;
@@ -59,9 +60,9 @@ 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<>();
content = content.replace("&nbsp;", " ").replace("&gt;", ">").replace("&lt;", "<"); content = content.replace("&nbsp;", " ").replace("&gt;", ">").replace("&lt;", "<");
@@ -71,39 +72,34 @@ public class OptiFineVersionList extends InstallerVersionList {
Document doc = db.parse(new StringBufferInputStream(content)); Document doc = db.parse(new StringBufferInputStream(content));
Element r = doc.getDocumentElement(); Element r = doc.getDocumentElement();
NodeList tables = r.getElementsByTagName("table"); NodeList tables = r.getElementsByTagName("table");
for(int i = 0; i < tables.getLength(); i++) { for (int i = 0; i < tables.getLength(); i++) {
Element e = (Element)tables.item(i); Element e = (Element) tables.item(i);
if("downloadTable".equals(e.getAttribute("class"))) { if ("downloadTable".equals(e.getAttribute("class"))) {
NodeList tr = e.getElementsByTagName("tr"); NodeList tr = e.getElementsByTagName("tr");
for(int k = 0; k < tr.getLength(); k++) { for (int k = 0; k < tr.getLength(); k++) {
NodeList downloadLine = ((Element)tr.item(k)).getElementsByTagName("td"); NodeList downloadLine = ((Element) tr.item(k)).getElementsByTagName("td");
OptiFineVersion v = new OptiFineVersion(); OptiFineVersion v = new OptiFineVersion();
for(int j = 0; j < downloadLine.getLength(); j++) { for (int j = 0; j < downloadLine.getLength(); j++) {
Element td = (Element)downloadLine.item(j); Element td = (Element) downloadLine.item(j);
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineMirror")) { if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineMirror"))
v.mirror = ((Element)td.getElementsByTagName("a").item(0)).getAttribute("href"); v.mirror = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href");
} if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDownload"))
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineDownload")) { v.dl = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href");
v.dl = ((Element)td.getElementsByTagName("a").item(0)).getAttribute("href"); if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDate"))
}
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineDate")) {
v.date = td.getTextContent(); v.date = td.getTextContent();
} if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineFile"))
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineFile")) {
v.ver = td.getTextContent(); v.ver = td.getTextContent();
}
} }
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;
root.add(v); root.add(v);
versions.add(iv); versions.add(iv);
List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.mcver)); List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.mcver));
ivl.add(iv); ivl.add(iv);
} }
@@ -124,11 +120,11 @@ 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) return null;
if(StrUtils.isBlank(mcVersion)) return versions; 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

@@ -23,6 +23,7 @@ import java.util.Arrays;
* @author huangyuhui * @author huangyuhui
*/ */
public class Extract extends Object implements Cloneable { public class Extract extends Object implements Cloneable {
String[] exclude; String[] exclude;
@Override @Override
@@ -32,5 +33,4 @@ public class Extract extends Object implements Cloneable {
return e; return e;
} }
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public enum GameDirType { public enum GameDirType {
ROOT_FOLDER, ROOT_FOLDER,
VERSION_FOLDER; VERSION_FOLDER;
} }

View File

@@ -26,29 +26,35 @@ import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
public abstract class IMinecraftLibrary implements Cloneable { public abstract class IMinecraftLibrary implements Cloneable {
public String name; public String name;
public IMinecraftLibrary(String name) { public IMinecraftLibrary(String name) {
this.name = name; this.name = name;
} }
public abstract boolean isRequiredToUnzip(); public abstract boolean isRequiredToUnzip();
public abstract String[] getDecompressExtractRules(); public abstract String[] getDecompressExtractRules();
public abstract void init(); public abstract void init();
public abstract boolean allow(); public abstract boolean allow();
public abstract File getFilePath(File gameDir); public abstract File getFilePath(File gameDir);
public abstract String getDownloadURL(String urlBase, DownloadType downloadType); public abstract String getDownloadURL(String urlBase, DownloadType downloadType);
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if(obj instanceof MinecraftLibrary) if (obj instanceof MinecraftLibrary)
return ((MinecraftLibrary) obj).name.equals(name); return ((MinecraftLibrary) obj).name.equals(name);
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
int hash = 3; int hash = 3;
hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash; return hash;
} }
@Override @Override

View File

@@ -29,46 +29,46 @@ import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
public class MinecraftClassicVersion extends MinecraftVersion { public class MinecraftClassicVersion extends MinecraftVersion {
public MinecraftClassicVersion() { public MinecraftClassicVersion() {
super(); super();
mainClass = "net.minecraft.client.Minecraft"; mainClass = "net.minecraft.client.Minecraft";
id = "Classic"; id = "Classic";
type = "release"; type = "release";
processArguments = assets = releaseTime = time = null; processArguments = assets = releaseTime = time = null;
minecraftArguments = "${auth_player_name} ${auth_session} --workDir ${game_directory}"; minecraftArguments = "${auth_player_name} ${auth_session} --workDir ${game_directory}";
libraries = new ArrayList<>(); libraries = new ArrayList<>();
libraries.add(new MinecraftOldLibrary("lwjgl")); libraries.add(new MinecraftOldLibrary("lwjgl"));
libraries.add(new MinecraftOldLibrary("jinput")); libraries.add(new MinecraftOldLibrary("jinput"));
libraries.add(new MinecraftOldLibrary("lwjgl_util")); libraries.add(new MinecraftOldLibrary("lwjgl_util"));
} }
@Override @Override
public Object clone() { public Object clone() {
return super.clone(); return super.clone();
} }
@Override @Override
public MinecraftVersion resolve(IMinecraftProvider manager, Set<String> resolvedSoFar, DownloadType sourceType) { public MinecraftVersion resolve(IMinecraftProvider manager, Set<String> resolvedSoFar, DownloadType sourceType) {
return this; return this;
} }
@Override @Override
public File getJar(File gameDir) { public File getJar(File gameDir) {
return new File(gameDir, "bin/minecraft.jar"); return new File(gameDir, "bin/minecraft.jar");
} }
@Override @Override
public File getJar(File gameDir, String suffix) { public File getJar(File gameDir, String suffix) {
return new File(gameDir, "bin/minecraft" + suffix + ".jar"); return new File(gameDir, "bin/minecraft" + suffix + ".jar");
} }
@Override @Override
public File getNatives(File gameDir) { public File getNatives(File gameDir) {
return new File(gameDir, "bin/natives"); return new File(gameDir, "bin/natives");
} }
@Override @Override
public boolean isAllowedToUnpackNatives() { public boolean isAllowedToUnpackNatives() {
return false; return false;
} }
} }

View File

@@ -31,28 +31,28 @@ import org.jackhuang.hellominecraft.utils.StrUtils;
public class MinecraftLibrary extends IMinecraftLibrary { public class MinecraftLibrary extends IMinecraftLibrary {
public ArrayList<Rules> rules; public ArrayList<Rules> rules;
public String url, formatted=null; public String url, formatted = null;
//public boolean serverreq=true, clientreq=true; //public boolean serverreq=true, clientreq=true;
public String[] checksums; public String[] checksums;
public Natives natives; public Natives natives;
public Extract extract; public Extract extract;
public MinecraftLibrary(String name) { public MinecraftLibrary(String name) {
super(name); super(name);
} }
public MinecraftLibrary(ArrayList<Rules> rules, String url, String[] checksums, Natives natives, String name, Extract extract) { public MinecraftLibrary(ArrayList<Rules> rules, String url, String[] checksums, Natives natives, String name, Extract extract) {
super(name); super(name);
this.rules = rules == null ? null : (ArrayList<Rules>) rules.clone(); this.rules = rules == null ? null : (ArrayList<Rules>) rules.clone();
this.url = url; this.url = url;
this.checksums = checksums == null ? null : Arrays.copyOf(checksums, checksums.length); this.checksums = checksums == null ? null : Arrays.copyOf(checksums, checksums.length);
this.natives = natives == null ? null : (Natives)natives.clone(); this.natives = natives == null ? null : (Natives) natives.clone();
this.extract = extract == null ? null :(Extract)extract.clone(); this.extract = extract == null ? null : (Extract) extract.clone();
} }
@Override @Override
public Object clone() { public Object clone() {
return new MinecraftLibrary(rules, url, checksums, natives, name, extract); return new MinecraftLibrary(rules, url, checksums, natives, name, extract);
} }
/** /**
@@ -62,73 +62,68 @@ public class MinecraftLibrary extends IMinecraftLibrary {
*/ */
@Override @Override
public boolean allow() { public boolean allow() {
boolean flag = false; boolean flag = false;
if (rules == null || rules.isEmpty()) { if (rules == null || rules.isEmpty())
flag = true; flag = true;
} else { else
for (Rules r : rules) { for (Rules r : rules)
if (r.action.equals("disallow")) { if (r.action.equals("disallow")) {
if (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString()))) { if (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString()))) {
flag = false; flag = false;
break; break;
} }
} else { } else
if (r.os == null || (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString())))) { if (r.os == null || (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString()))))
flag = true; flag = true;
} return flag;
}
}
}
return flag;
} }
private String formatArch(String nati) { private String formatArch(String nati) {
return nati == null ? "" : nati.replace("${arch}", Platform.getPlatform().getBit()); return nati == null ? "" : nati.replace("${arch}", Platform.getPlatform().getBit());
} }
private String getNative() { private String getNative() {
OS os = OS.os(); OS os = OS.os();
if (os == OS.WINDOWS) { if (os == OS.WINDOWS)
return formatArch(natives.windows); return formatArch(natives.windows);
} else if (os == OS.OSX) { else if (os == OS.OSX)
return formatArch(natives.osx); return formatArch(natives.osx);
} else { else
return formatArch(natives.linux); return formatArch(natives.linux);
}
} }
@Override @Override
public boolean isRequiredToUnzip() { public boolean isRequiredToUnzip() {
return natives != null && allow(); return natives != null && allow();
} }
@Override @Override
public void init() { public void init() {
String str = name; String str = name;
String[] s = str.split(":"); String[] s = str.split(":");
str = s[0]; str = s[0];
str = str.replace('.', File.separatorChar); str = str.replace('.', File.separatorChar);
if (natives == null) { if (natives == null)
str += File.separator + s[1] + File.separator + s[2] str += File.separator + s[1] + File.separator + s[2]
+ File.separator + s[1] + '-' + s[2] + ".jar"; + File.separator + s[1] + '-' + s[2] + ".jar";
} else { else {
str += File.separator + s[1] + File.separator + s[2] str += File.separator + s[1] + File.separator + s[2]
+ File.separator + s[1] + '-' + s[2] + '-'; + File.separator + s[1] + '-' + s[2] + '-';
str += getNative(); str += getNative();
str += ".jar"; str += ".jar";
} }
formatted = str; formatted = str;
} }
@Override @Override
public File getFilePath(File gameDir) { public File getFilePath(File gameDir) {
return new File(gameDir, "libraries" + File.separatorChar + formatted); return new File(gameDir, "libraries" + File.separatorChar + formatted);
} }
@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()) urlBase = this.url;
return urlBase + formatted.replace('\\', '/'); return urlBase + formatted.replace('\\', '/');
} }
@Override @Override

View File

@@ -26,12 +26,12 @@ import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
public class MinecraftOldLibrary extends MinecraftLibrary { public class MinecraftOldLibrary extends MinecraftLibrary {
public MinecraftOldLibrary(String name) { public MinecraftOldLibrary(String name) {
super(name); super(name);
} }
@Override @Override
public boolean isRequiredToUnzip() { public boolean isRequiredToUnzip() {
return false; return false;
} }
@Override @Override
@@ -40,22 +40,22 @@ public class MinecraftOldLibrary extends MinecraftLibrary {
@Override @Override
public boolean allow() { public boolean allow() {
return true; return true;
} }
@Override @Override
public File getFilePath(File gameDir) { public File getFilePath(File gameDir) {
return new File(gameDir, "bin/" + name + ".jar"); return new File(gameDir, "bin/" + name + ".jar");
} }
@Override @Override
public Object clone() { public Object clone() {
return new MinecraftOldLibrary(name); return new MinecraftOldLibrary(name);
} }
@Override @Override
public String getDownloadURL(String urlBase, DownloadType downloadType) { public String getDownloadURL(String urlBase, DownloadType downloadType) {
return null; return null;
} }
} }

View File

@@ -33,7 +33,7 @@ import org.jackhuang.hellominecraft.utils.ArrayUtils;
public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion> { public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion> {
public String minecraftArguments, mainClass, time, id, type, processArguments, public String minecraftArguments, mainClass, time, id, type, processArguments,
releaseTime, assets, jar, inheritsFrom; releaseTime, assets, jar, inheritsFrom;
public int minimumLauncherVersion; public int minimumLauncherVersion;
public boolean hidden; public boolean hidden;
@@ -43,80 +43,77 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
} }
public MinecraftVersion(String minecraftArguments, String mainClass, String time, String id, String type, String processArguments, String releaseTime, String assets, String jar, String inheritsFrom, int minimumLauncherVersion, List<MinecraftLibrary> libraries, boolean hidden) { public MinecraftVersion(String minecraftArguments, String mainClass, String time, String id, String type, String processArguments, String releaseTime, String assets, String jar, String inheritsFrom, int minimumLauncherVersion, List<MinecraftLibrary> libraries, boolean hidden) {
this(); this();
this.minecraftArguments = minecraftArguments; this.minecraftArguments = minecraftArguments;
this.mainClass = mainClass; this.mainClass = mainClass;
this.time = time; this.time = time;
this.id = id; this.id = id;
this.type = type; this.type = type;
this.processArguments = processArguments; this.processArguments = processArguments;
this.releaseTime = releaseTime; this.releaseTime = releaseTime;
this.assets = assets; this.assets = assets;
this.jar = jar; this.jar = jar;
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)
this.libraries.add((MinecraftLibrary) library.clone()); this.libraries.add((MinecraftLibrary) library.clone());
} }
}
} }
@Override @Override
public Object clone() { public Object clone() {
return new MinecraftVersion(minecraftArguments, mainClass, time, id, type, processArguments, releaseTime, assets, jar, inheritsFrom, minimumLauncherVersion, libraries, hidden); return new MinecraftVersion(minecraftArguments, mainClass, time, id, type, processArguments, releaseTime, assets, jar, inheritsFrom, minimumLauncherVersion, libraries, hidden);
} }
public MinecraftVersion resolve(IMinecraftProvider manager, DownloadType sourceType) { public MinecraftVersion resolve(IMinecraftProvider manager, DownloadType sourceType) {
return resolve(manager, new HashSet<>(), sourceType); return resolve(manager, new HashSet<>(), sourceType);
} }
protected MinecraftVersion resolve(IMinecraftProvider manager, Set<String> resolvedSoFar, DownloadType sourceType) { protected MinecraftVersion resolve(IMinecraftProvider manager, Set<String> resolvedSoFar, DownloadType sourceType) {
if (inheritsFrom == null) { if (inheritsFrom == null)
return this; return this;
} if (!resolvedSoFar.add(id))
if (!resolvedSoFar.add(id)) { throw new IllegalStateException("Circular dependency detected.");
throw new IllegalStateException("Circular dependency detected.");
}
MinecraftVersion parent = manager.getVersionById(inheritsFrom); MinecraftVersion parent = manager.getVersionById(inheritsFrom);
if(parent == null) { if (parent == null) {
if(!manager.install(inheritsFrom, sourceType)) return this; if (!manager.install(inheritsFrom, sourceType)) return this;
parent = manager.getVersionById(inheritsFrom); parent = manager.getVersionById(inheritsFrom);
} }
parent = parent.resolve(manager, resolvedSoFar, sourceType); parent = parent.resolve(manager, resolvedSoFar, sourceType);
MinecraftVersion result = new MinecraftVersion( MinecraftVersion result = new MinecraftVersion(
this.minecraftArguments != null ? this.minecraftArguments : parent.minecraftArguments, this.minecraftArguments != null ? this.minecraftArguments : parent.minecraftArguments,
this.mainClass != null ? this.mainClass : parent.mainClass, this.mainClass != null ? this.mainClass : parent.mainClass,
this.time, this.id, this.type, parent.processArguments, this.releaseTime, this.time, this.id, this.type, parent.processArguments, this.releaseTime,
this.assets != null ? this.assets : parent.assets, this.assets != null ? this.assets : parent.assets,
this.jar != null ? this.jar : parent.jar, this.jar != null ? this.jar : parent.jar,
null, parent.minimumLauncherVersion, null, parent.minimumLauncherVersion,
this.libraries != null ? ArrayUtils.merge(this.libraries, parent.libraries) : parent.libraries, this.hidden); this.libraries != null ? ArrayUtils.merge(this.libraries, parent.libraries) : parent.libraries, this.hidden);
return result; return result;
} }
public File getJar(File gameDir) { public File getJar(File gameDir) {
String jarId = this.jar == null ? this.id : this.jar; String jarId = this.jar == null ? this.id : this.jar;
return new File(gameDir, "versions/" + jarId + "/" + jarId + ".jar"); return new File(gameDir, "versions/" + jarId + "/" + jarId + ".jar");
} }
public File getJar(File gameDir, String suffix) { public File getJar(File gameDir, String suffix) {
String jarId = this.jar == null ? this.id : this.jar; String jarId = this.jar == null ? this.id : this.jar;
return new File(gameDir, "versions/" + jarId + "/" + jarId + suffix + ".jar"); return new File(gameDir, "versions/" + jarId + "/" + jarId + suffix + ".jar");
} }
public File getNatives(File gameDir) { public File getNatives(File gameDir) {
return new File(gameDir, "versions/" + id + "/" + id return new File(gameDir, "versions/" + id + "/" + id
+ "-natives"); + "-natives");
} }
public boolean isAllowedToUnpackNatives() { public boolean isAllowedToUnpackNatives() {
return true; return true;
} }
public String getAssets() { public String getAssets() {

View File

@@ -118,12 +118,10 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
if (StrUtils.formatVersion(id) == null) { if (StrUtils.formatVersion(id) == null) {
if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
FileUtils.deleteDirectoryQuietly(dir); FileUtils.deleteDirectoryQuietly(dir);
} else if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_needs_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) { } else if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_needs_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
if (!refreshJson(id)) { if (!refreshJson(id))
if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
FileUtils.deleteDirectoryQuietly(dir); FileUtils.deleteDirectoryQuietly(dir);
}
}
continue; continue;
} }
MinecraftVersion mcVersion; MinecraftVersion mcVersion;
@@ -215,10 +213,10 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
@Override @Override
public File getRunDirectory(String id) { public File getRunDirectory(String id) {
switch (profile.getGameDirType()) { switch (profile.getGameDirType()) {
case VERSION_FOLDER: case VERSION_FOLDER:
return new File(baseFolder, "versions/" + id + "/"); return new File(baseFolder, "versions/" + id + "/");
default: default:
return baseFolder; return baseFolder;
} }
} }
@@ -226,7 +224,7 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) { public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) {
ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>(); ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>();
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) {
l.init(); l.init();
if (l.allow()) { if (l.allow()) {
@@ -239,7 +237,6 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
} }
} }
} }
}
return downloadLibraries; return downloadLibraries;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public class Natives implements Cloneable { public class Natives implements Cloneable {
public String windows, osx, linux; public String windows, osx, linux;
@Override @Override

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public class OS { public class OS {
public String version, name; public String version, name;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public class Rules { public class Rules {
public String action; public String action;
public OS os; public OS os;
} }

View File

@@ -63,9 +63,8 @@ public class DraggableFrame extends JFrame
@Override @Override
public void mouseDragged(MouseEvent e) { public void mouseDragged(MouseEvent e) {
if ((e.getModifiersEx() & 0x400) != 0) { if ((e.getModifiersEx() & 0x400) != 0)
setLocation(e.getXOnScreen() - this.dragGripX, e.getYOnScreen() - this.dragGripY); setLocation(e.getXOnScreen() - this.dragGripX, e.getYOnScreen() - this.dragGripY);
}
} }
@Override @Override

View File

@@ -914,7 +914,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
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) return;
if (MessageBox.Show(C.i18n("ui.message.sure_remove", profile.getName()), MessageBox.YES_NO_OPTION) == MessageBox.NO_OPTION) return; if (MessageBox.Show(C.i18n("ui.message.sure_remove", profile.getName()), MessageBox.YES_NO_OPTION) == MessageBox.NO_OPTION) return;
if(Settings.delVersion(profile)) { if (Settings.delVersion(profile)) {
cboProfiles.removeItem(profile.getName()); cboProfiles.removeItem(profile.getName());
profile = Settings.getOneProfile(); profile = Settings.getOneProfile();
if (profile != null) { if (profile != null) {

View File

@@ -48,7 +48,7 @@ public class HeaderTab extends JLabel
return this.isActive; return this.isActive;
} }
public void setIsActive(boolean isActive) { public final void setIsActive(boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
setOpaque(isActive); setOpaque(isActive);

View File

@@ -259,9 +259,8 @@ public class LauncherSettingsPanel extends javax.swing.JPanel {
fc.setDialogTitle(C.i18n("launcher.choose_bgpath")); fc.setDialogTitle(C.i18n("launcher.choose_bgpath"));
fc.setMultiSelectionEnabled(false); fc.setMultiSelectionEnabled(false);
fc.showOpenDialog(this); fc.showOpenDialog(this);
if (fc.getSelectedFile() == null) { if (fc.getSelectedFile() == null)
return; return;
}
try { try {
String path = fc.getSelectedFile().getCanonicalPath(); String path = fc.getSelectedFile().getCanonicalPath();
path = IOUtils.removeLastSeparator(path); path = IOUtils.removeLastSeparator(path);
@@ -289,7 +288,7 @@ public class LauncherSettingsPanel extends javax.swing.JPanel {
private void cboThemeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboThemeItemStateChanged private void cboThemeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboThemeItemStateChanged
Settings.getInstance().setTheme(cboTheme.getSelectedIndex()); Settings.getInstance().setTheme(cboTheme.getSelectedIndex());
if(MainFrame.instance != null) if (MainFrame.instance != null)
MainFrame.instance.reloadColor(); MainFrame.instance.reloadColor();
}//GEN-LAST:event_cboThemeItemStateChanged }//GEN-LAST:event_cboThemeItemStateChanged

View File

@@ -86,8 +86,7 @@ public final class MainFrame extends DraggableFrame {
if (enableShadow) if (enableShadow)
try { try {
//AWTUtilities.setWindowOpaque(this, false); setBackground(new Color(0, 0, 0, 0));
setBackground(new Color(0,0,0,0));
getRootPane().setBorder(border = new DropShadowBorder(borderColor, 4)); getRootPane().setBorder(border = new DropShadowBorder(borderColor, 4));
} catch (Throwable ex) { } catch (Throwable ex) {
HMCLog.err("Failed to set window transparent.", ex); HMCLog.err("Failed to set window transparent.", ex);
@@ -250,14 +249,14 @@ public final class MainFrame extends DraggableFrame {
this.mainTab.setIsActive(true); this.mainTab.setIsActive(true);
this.mainPanel.onSelected(); this.mainPanel.onSelected();
} else if (tabName.equalsIgnoreCase("game")) { } else if (tabName.equalsIgnoreCase("game")) {
if(gamePanel == null) { if (gamePanel == null) {
gamePanel = new GameSettingsPanel(); gamePanel = new GameSettingsPanel();
gamePanelWrapper.add(gamePanel); gamePanelWrapper.add(gamePanel);
} }
this.gameTab.setIsActive(true); this.gameTab.setIsActive(true);
this.gamePanel.onSelected(); this.gamePanel.onSelected();
} else if (tabName.equalsIgnoreCase("launcher")) { } else if (tabName.equalsIgnoreCase("launcher")) {
if(launcherPanel == null) { if (launcherPanel == null) {
launcherPanel = new LauncherSettingsPanel(); launcherPanel = new LauncherSettingsPanel();
launcherPanelWrapper.add(launcherPanel); launcherPanelWrapper.add(launcherPanel);
} }

View File

@@ -457,7 +457,7 @@ public class MainPagePanel extends javax.swing.JPanel {
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
MessageBox.Show(C.i18n("mainwindow.no_version")); MessageBox.Show(C.i18n("mainwindow.no_version"));
showedNoVersion = true; showedNoVersion = true;
}); });
} else { } else {
for (MinecraftVersion mcVersion : getCurrentProfile().getMinecraftProvider().getVersions()) { for (MinecraftVersion mcVersion : getCurrentProfile().getMinecraftProvider().getVersions()) {
if (mcVersion.hidden) continue; if (mcVersion.hidden) continue;

View File

@@ -25,13 +25,13 @@ import java.util.ResourceBundle;
* @author huangyuhui * @author huangyuhui
*/ */
public final class C { public final class C {
public static final Gson gsonPrettyPrinting = new GsonBuilder().setPrettyPrinting().create(); public static final Gson gsonPrettyPrinting = new GsonBuilder().setPrettyPrinting().create();
public static final Gson gson = new Gson(); public static final Gson gson = new Gson();
public static final ResourceBundle I18N = ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N"); public static final ResourceBundle I18N = ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N");
//http://repo1.maven.org/maven2 //http://repo1.maven.org/maven2
public static final String URL_PUBLISH = "http://www.mcbbs.net/thread-142335-1-1.html"; public static final String URL_PUBLISH = "http://www.mcbbs.net/thread-142335-1-1.html";
public static final String URL_TIEBA = "http://tieba.baidu.com/f?kw=hellominecraftlauncher"; public static final String URL_TIEBA = "http://tieba.baidu.com/f?kw=hellominecraftlauncher";
public static final String URL_GITHUB = "https://github.com/huanghongxun/HMCL/issues"; public static final String URL_GITHUB = "https://github.com/huanghongxun/HMCL/issues";
@@ -44,12 +44,13 @@ public final class C {
public static final String URL_FORGE_LIST = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/json"; public static final String URL_FORGE_LIST = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/json";
public static final String URL_LITELOADER_LIST = "http://dl.liteloader.com/versions/versions.json"; public static final String URL_LITELOADER_LIST = "http://dl.liteloader.com/versions/versions.json";
private C(){} private C() {
}
public static String i18n(String a, Object... format) { public static String i18n(String a, Object... format) {
try { try {
return String.format(C.I18N.getString(a), format); return String.format(C.I18N.getString(a), format);
} catch(Exception e) { } catch (Exception e) {
HMCLog.warn("Failed to read localization lang: " + a, e); HMCLog.warn("Failed to read localization lang: " + a, e);
return a; return a;
} }

View File

@@ -18,7 +18,6 @@ package org.jackhuang.hellominecraft;
import org.jackhuang.hellominecraft.logging.logger.Logger; import org.jackhuang.hellominecraft.logging.logger.Logger;
/** /**
* *
* @author huangyuhui * @author huangyuhui

View File

@@ -21,18 +21,24 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public interface DoingDoneListener<K> { public interface DoingDoneListener<K> {
/** /**
* Task done. * Task done.
*
* @param k * @param k
*/ */
void onDone(K k); void onDone(K k);
/** /**
* Before task executing. * Before task executing.
*
* @param k * @param k
*/ */
void onDoing(K k); void onDoing(K k);
/** /**
* Task failed. * Task failed.
*
* @param k * @param k
*/ */
void onFailed(K k); void onFailed(K k);

View File

@@ -24,6 +24,7 @@ import java.util.HashSet;
* @author huangyuhui * @author huangyuhui
*/ */
public class ParallelTask extends Task { public class ParallelTask extends Task {
Collection<Task> dependsTask = new HashSet<>(); Collection<Task> dependsTask = new HashSet<>();
@Override @Override

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public abstract class ProgressProvider { public abstract class ProgressProvider {
protected ProgressProviderListener ppl; protected ProgressProviderListener ppl;
public ProgressProvider setProgressProviderListener(ProgressProviderListener p) { public ProgressProvider setProgressProviderListener(ProgressProviderListener p) {

View File

@@ -21,7 +21,10 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public interface ProgressProviderListener { public interface ProgressProviderListener {
void setProgress(int prog, int max); void setProgress(int prog, int max);
void setStatus(String sta); void setStatus(String sta);
void onProgressProviderDone(); void onProgressProviderDone();
} }

View File

@@ -26,25 +26,33 @@ public abstract class Task extends ProgressProvider {
/** /**
* Run in a new thread(packed in TaskList). * Run in a new thread(packed in TaskList).
*
* @return is task finished sucessfully. * @return is task finished sucessfully.
*/ */
public abstract boolean executeTask(); public abstract boolean executeTask();
/** /**
* if this func returns false, TaskList will force abort the thread. * if this func returns false, TaskList will force abort the thread. run in
* run in main thread. * main thread.
*
* @return is aborted. * @return is aborted.
*/ */
public boolean abort() { return false; } public boolean abort() {
return false;
}
public Throwable getFailReason() { return failReason; } public Throwable getFailReason() {
return failReason;
}
protected Throwable failReason = null; protected Throwable failReason = null;
protected void setFailReason(Throwable s) { protected void setFailReason(Throwable s) {
failReason = s; failReason = s;
} }
protected String tag; protected String tag;
protected boolean parallelExecuting; protected boolean parallelExecuting;
public Task setTag(String tag) { public Task setTag(String tag) {
this.tag = tag; this.tag = tag;
return this; return this;
@@ -60,6 +68,11 @@ public abstract class Task extends ProgressProvider {
public abstract String getInfo(); public abstract String getInfo();
public Collection<Task> getDependTasks() { return null; } public Collection<Task> getDependTasks() {
public Collection<Task> getAfterTasks() { return null; } return null;
}
public Collection<Task> getAfterTasks() {
return null;
}
} }

View File

@@ -87,9 +87,8 @@ public class TaskList extends Thread {
static final Set<Task> taskPool = Collections.synchronizedSet(new HashSet<Task>()); static final Set<Task> taskPool = Collections.synchronizedSet(new HashSet<Task>());
private void processTasks(Collection<Task> c) { private void processTasks(Collection<Task> c) {
if (c == null) { if (c == null)
return; return;
}
this.totTask += c.size(); this.totTask += c.size();
Set<InvokeThread> runningThread = Collections.synchronizedSet(new HashSet<InvokeThread>()); Set<InvokeThread> runningThread = Collections.synchronizedSet(new HashSet<InvokeThread>());
for (Task t2 : c) { for (Task t2 : c) {
@@ -99,39 +98,34 @@ public class TaskList extends Thread {
runningThread.add(thread); runningThread.add(thread);
thread.start(); thread.start();
} }
while (!runningThread.isEmpty()) { while (!runningThread.isEmpty())
try { try {
if(this.isInterrupted()) return; if (this.isInterrupted()) return;
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
HMCLog.warn("Failed to sleep task thread", ex); HMCLog.warn("Failed to sleep task thread", ex);
} }
}
} }
private void executeTask(Task t) { private void executeTask(Task t) {
if (!shouldContinue || t == null) { if (!shouldContinue || t == null)
return; return;
}
processTasks(t.getDependTasks()); processTasks(t.getDependTasks());
HMCLog.log("Executing task: " + t.getInfo()); HMCLog.log("Executing task: " + t.getInfo());
for (DoingDoneListener<Task> d : taskListener) { for (DoingDoneListener<Task> d : taskListener)
d.onDoing(t); d.onDoing(t);
}
if (t.executeTask()) { if (t.executeTask()) {
HMCLog.log("Task finished: " + t.getInfo()); HMCLog.log("Task finished: " + t.getInfo());
for (DoingDoneListener<Task> d : taskListener) { for (DoingDoneListener<Task> d : taskListener)
d.onDone(t); d.onDone(t);
}
processTasks(t.getAfterTasks()); processTasks(t.getAfterTasks());
} else { } else {
HMCLog.err("Task failed: " + t.getInfo(), t.getFailReason()); HMCLog.err("Task failed: " + t.getInfo(), t.getFailReason());
for (DoingDoneListener<Task> d : taskListener) { for (DoingDoneListener<Task> d : taskListener)
d.onFailed(t); d.onFailed(t);
}
} }
} }
@@ -153,10 +147,10 @@ public class TaskList extends Thread {
public void abort() { public void abort() {
shouldContinue = false; shouldContinue = false;
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

@@ -21,7 +21,9 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public class TaskRunnable extends TaskInfo { public class TaskRunnable extends TaskInfo {
private final Runnable r; private final Runnable r;
public TaskRunnable(String info, Runnable r) { public TaskRunnable(String info, Runnable r) {
super(info); super(info);
this.r = r; this.r = r;
@@ -32,7 +34,7 @@ public class TaskRunnable extends TaskInfo {
try { try {
r.run(); r.run();
return true; return true;
} catch(Throwable t) { } catch (Throwable t) {
setFailReason(t); setFailReason(t);
return false; return false;
} }

View File

@@ -170,7 +170,7 @@ public class TaskWindow extends javax.swing.JDialog
}// </editor-fold>//GEN-END:initComponents }// </editor-fold>//GEN-END:initComponents
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
if(MessageBox.Show(C.i18n("operation.confirm_stop"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) if (MessageBox.Show(C.i18n("operation.confirm_stop"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
this.dispose(); this.dispose();
}//GEN-LAST:event_btnCancelActionPerformed }//GEN-LAST:event_btnCancelActionPerformed
@@ -230,7 +230,7 @@ public class TaskWindow extends javax.swing.JDialog
@Override @Override
public void onFailed(Task task) { public void onFailed(Task task) {
failReasons.add(task.getInfo() + ": " + (task.getFailReason() == null ? "No exception" : task.getFailReason().getLocalizedMessage())); failReasons.add(task.getInfo() + ": " + (null == task.getFailReason() ? "No exception" : task.getFailReason().getLocalizedMessage()));
pgsTotal.setMaximum(taskList.taskCount()); pgsTotal.setMaximum(taskList.taskCount());
pgsTotal.setValue(pgsTotal.getValue() + 1); pgsTotal.setValue(pgsTotal.getValue() + 1);
SwingUtils.replaceLast(lstDownload, task.getFailReason()); SwingUtils.replaceLast(lstDownload, task.getFailReason());

View File

@@ -21,7 +21,8 @@ package org.jackhuang.hellominecraft.tasks.communication;
* @author huangyuhui * @author huangyuhui
* @param <T> the type of result. * @param <T> the type of result.
*/ */
public class DefaultPreviousResult<T> implements PreviousResult<T>{ public class DefaultPreviousResult<T> implements PreviousResult<T> {
T a; T a;
public DefaultPreviousResult(T a) { public DefaultPreviousResult(T a) {

View File

@@ -27,89 +27,79 @@ import java.util.Map;
public class ArrayUtils { public class ArrayUtils {
public static <T> boolean isEmpty(T[] array) { public static <T> boolean isEmpty(T[] array) {
return array == null || array.length <= 0; return array == null || array.length <= 0;
} }
public static <T> boolean isNotEmpty(T[] array) { public static <T> boolean isNotEmpty(T[] array) {
return !isEmpty(array); return !isEmpty(array);
} }
public static <T> boolean contains(T[] array, T objectToFind) { public static <T> boolean contains(T[] array, T objectToFind) {
return indexOf(array, objectToFind) != -1; return indexOf(array, objectToFind) != -1;
} }
public static <T> int indexOf(T[] array, T valueToFind) { public static <T> int indexOf(T[] array, T valueToFind) {
return indexOf(array, valueToFind, 0); return indexOf(array, valueToFind, 0);
} }
public static <T> int indexOf(T[] array, T valueToFind, int startIndex) { public static <T> int indexOf(T[] array, T valueToFind, int startIndex) {
if (array == null) { if (array == null)
return -1; return -1;
} if (startIndex < 0)
if (startIndex < 0) { startIndex = 0;
startIndex = 0; for (int i = startIndex; i < array.length; i++)
} if (valueToFind.equals(array[i]))
for (int i = startIndex; i < array.length; i++) { return i;
if (valueToFind.equals(array[i])) { return -1;
return i;
}
}
return -1;
} }
public static <T> int lastIndexOf(T[] array, T valueToFind) { public static <T> int lastIndexOf(T[] array, T valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647); return lastIndexOf(array, valueToFind, 2147483647);
} }
public static <T> int lastIndexOf(T[] array, T valueToFind, int startIndex) { public static <T> int lastIndexOf(T[] array, T valueToFind, int startIndex) {
if (array == null) { if (array == null)
return -1; return -1;
} if (startIndex < 0)
if (startIndex < 0) { return -1;
return -1; if (startIndex >= array.length)
} startIndex = array.length - 1;
if (startIndex >= array.length) { for (int i = startIndex; i >= 0; i--)
startIndex = array.length - 1; if (valueToFind.equals(array[i]))
} return i;
for (int i = startIndex; i >= 0; i--) { return -1;
if (valueToFind.equals(array[i])) {
return i;
}
}
return -1;
} }
public static ArrayList merge(List a, List b) { public static ArrayList merge(List a, List b) {
ArrayList al = new ArrayList(a.size() + b.size()); ArrayList al = new ArrayList(a.size() + b.size());
al.addAll(a); al.addAll(b); al.addAll(a);
return al; al.addAll(b);
return al;
} }
public static <K> K getEnd(K[] k) { public static <K> K getEnd(K[] k) {
if(k == null) return null; if (k == null) return null;
else return k[k.length-1]; else return k[k.length - 1];
} }
public static List tryGetMapWithList(Map map, String key) { public static List tryGetMapWithList(Map map, String key) {
List l = (List)map.get(key); List l = (List) map.get(key);
if(l == null) if (l == null)
map.put(key, l = new ArrayList()); map.put(key, l = new ArrayList());
return l; return l;
} }
public static <T> int matchArray(T[] a, T[] b) { public static <T> int matchArray(T[] a, T[] b) {
for (int i = 0; i < a.length - b.length; i++) { for (int i = 0; i < a.length - b.length; i++) {
int j = 1; int j = 1;
for (int k = 0; k < b.length; k++) { for (int k = 0; k < b.length; k++) {
if (b[k].equals(a[(i + k)])) { if (b[k].equals(a[(i + k)]))
continue; continue;
}
j = 0; j = 0;
break; break;
} }
if (j != 0) { if (j != 0)
return i; return i;
}
} }
return -1; return -1;
} }
@@ -118,15 +108,13 @@ public class ArrayUtils {
for (int i = 0; i < a.length - b.length; i++) { for (int i = 0; i < a.length - b.length; i++) {
int j = 1; int j = 1;
for (int k = 0; k < b.length; k++) { for (int k = 0; k < b.length; k++) {
if (b[k] == a[(i + k)]) { if (b[k] == a[(i + k)])
continue; continue;
}
j = 0; j = 0;
break; break;
} }
if (j != 0) { if (j != 0)
return i; return i;
}
} }
return -1; return -1;
} }

View File

@@ -27,13 +27,16 @@ import java.util.Iterator;
* @author huangyuhui * @author huangyuhui
*/ */
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 -> { if(p.apply(t)) newColl.add(t); }); forEach(coll, t -> {
if (p.apply(t)) newColl.add(t);
});
return newColl; return newColl;
} }

View File

@@ -30,73 +30,60 @@ public class DoubleOutputStream extends OutputStream {
private boolean c = true; private boolean c = true;
public DoubleOutputStream(OutputStream paramOutputStream1, OutputStream paramOutputStream2) { public DoubleOutputStream(OutputStream paramOutputStream1, OutputStream paramOutputStream2) {
this(paramOutputStream1, paramOutputStream2, true); this(paramOutputStream1, paramOutputStream2, true);
} }
private DoubleOutputStream(OutputStream paramOutputStream1, OutputStream paramOutputStream2, boolean paramBoolean) { private DoubleOutputStream(OutputStream paramOutputStream1, OutputStream paramOutputStream2, boolean paramBoolean) {
this.a = paramOutputStream1; this.a = paramOutputStream1;
this.b = paramOutputStream2; this.b = paramOutputStream2;
this.c = true; this.c = true;
} }
@Override @Override
public final void write(byte[] arr, int off, int len) throws IOException { public final void write(byte[] arr, int off, int len) throws IOException {
if (this.a != null) { if (this.a != null)
this.a.write(arr, off, len); this.a.write(arr, off, len);
} if (this.b != null)
if (this.b != null) { this.b.write(arr, off, len);
this.b.write(arr, off, len); if (this.c)
} flush();
if (this.c) {
flush();
}
} }
@Override @Override
public final void write(byte[] paramArrayOfByte) throws IOException { public final void write(byte[] paramArrayOfByte) throws IOException {
if (this.a != null) { if (this.a != null)
this.a.write(paramArrayOfByte); this.a.write(paramArrayOfByte);
} if (this.b != null)
if (this.b != null) { this.b.write(paramArrayOfByte);
this.b.write(paramArrayOfByte); if (this.c)
} flush();
if (this.c) {
flush();
}
} }
@Override @Override
public final void write(int paramInt) throws IOException { public final void write(int paramInt) throws IOException {
if (this.a != null) { if (this.a != null)
this.a.write(paramInt); this.a.write(paramInt);
} if (this.b != null)
if (this.b != null) { this.b.write(paramInt);
this.b.write(paramInt); if (this.c)
} flush();
if (this.c) {
flush();
}
} }
@Override @Override
public final void close() throws IOException { public final void close() throws IOException {
flush(); flush();
if (this.a != null) { if (this.a != null)
this.a.close(); this.a.close();
} if (this.b != null)
if (this.b != null) { this.b.close();
this.b.close();
}
} }
@Override @Override
public final void flush() throws IOException { public final void flush() throws IOException {
if (this.a != null) { if (this.a != null)
this.a.flush(); this.a.flush();
} if (this.b != null)
if (this.b != null) { this.b.flush();
this.b.flush();
}
} }
} }

View File

@@ -22,5 +22,6 @@ package org.jackhuang.hellominecraft.utils;
* @param <T> EventArgs * @param <T> EventArgs
*/ */
public interface Event<T> { public interface Event<T> {
boolean call(Object sender, T t); boolean call(Object sender, T t);
} }

View File

@@ -24,6 +24,7 @@ import java.util.HashSet;
* @param <T> EventArgs * @param <T> EventArgs
*/ */
public class EventHandler<T> { public class EventHandler<T> {
HashSet<Event<T>> handlers; HashSet<Event<T>> handlers;
Object sender; Object sender;
@@ -42,8 +43,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

@@ -30,19 +30,18 @@ public class LauncherPrintStream extends PrintStream {
private final ArrayList<Consumer<String>> printListeners = new ArrayList<>(); private final ArrayList<Consumer<String>> printListeners = new ArrayList<>();
public LauncherPrintStream(OutputStream paramOutputStream) { public LauncherPrintStream(OutputStream paramOutputStream) {
super(paramOutputStream); super(paramOutputStream);
} }
@Override @Override
public final void println(String paramString) { public final void println(String paramString) {
super.println(paramString); super.println(paramString);
for (Consumer<String> a1 : printListeners) { for (Consumer<String> a1 : printListeners)
a1.accept(paramString); a1.accept(paramString);
}
} }
public final void addPrintListener(Consumer<String> paraml) { public final void addPrintListener(Consumer<String> paraml) {
this.printListeners.add(paraml); this.printListeners.add(paraml);
} }
} }

View File

@@ -44,8 +44,8 @@ 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")) return a * 1024;
else if(s.endsWith("k")) return a / 1024; else if (s.endsWith("k")) return a / 1024;
else return a; else return a;
} }
} }

View File

@@ -39,9 +39,8 @@ public final class NetUtils {
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
byte[] arrayOfByte1 = new byte[1024]; byte[] arrayOfByte1 = new byte[1024];
int i; int i;
while ((i = is.read(arrayOfByte1)) >= 0) { while ((i = is.read(arrayOfByte1)) >= 0)
localByteArrayOutputStream.write(arrayOfByte1, 0, i); localByteArrayOutputStream.write(arrayOfByte1, 0, i);
}
is.close(); is.close();
return localByteArrayOutputStream.toByteArray(); return localByteArrayOutputStream.toByteArray();
} }
@@ -51,17 +50,16 @@ public final class NetUtils {
} }
public static String getStreamContent(InputStream is, String encoding) public static String getStreamContent(InputStream is, String encoding)
throws IOException { throws IOException {
String result; String result;
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) {
result = ""; result = "";
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null)
result += line + "\n"; result += line + "\n";
}
} }
if(result.length() < 1) return ""; if (result.length() < 1) return "";
else return result.substring(0, result.length() - 1); else return result.substring(0, result.length() - 1);
} }
public static String doGet(String url, String encoding) throws IOException { public static String doGet(String url, String encoding) throws IOException {
@@ -85,16 +83,15 @@ public final class NetUtils {
public static String sendGetRequest(String endpoint, public static String sendGetRequest(String endpoint,
String requestParameters) { String requestParameters) {
String result = null; String result = null;
if (endpoint.startsWith("http://")) { if (endpoint.startsWith("http://"))
// Send a GET request to the servlet // Send a GET request to the servlet
try { try {
// Construct data // Construct data
StringBuilder data = new StringBuilder(); StringBuilder data = new StringBuilder();
// Send data // Send data
String urlStr = endpoint; String urlStr = endpoint;
if (requestParameters != null && requestParameters.length() > 0) { if (requestParameters != null && requestParameters.length() > 0)
urlStr += "?" + requestParameters; urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr); URL url = new URL(urlStr);
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
@@ -110,7 +107,6 @@ public final class NetUtils {
} catch (Exception e) { } catch (Exception e) {
HMCLog.warn("Failed to send get request.", e); HMCLog.warn("Failed to send get request.", e);
} }
}
return result; return result;
} }
@@ -175,13 +171,12 @@ public final class NetUtils {
} }
public static URL concatenateURL(URL url, String query) { public static URL concatenateURL(URL url, String query) {
try { try {
if ((url.getQuery() != null) && (url.getQuery().length() > 0)) { if ((url.getQuery() != null) && (url.getQuery().length() > 0))
return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("&").append(query).toString()); return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("&").append(query).toString());
} return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("?").append(query).toString());
return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("?").append(query).toString()); } catch (MalformedURLException ex) {
} catch (MalformedURLException ex) { throw new IllegalArgumentException("Could not concatenate given URL with GET arguments!", ex);
throw new IllegalArgumentException("Could not concatenate given URL with GET arguments!", ex); }
}
} }
} }

View File

@@ -25,6 +25,7 @@ import java.util.Map;
* @param <V> V Type * @param <V> V Type
*/ */
public class Pair<K, V> implements Map.Entry<K, V> { public class Pair<K, V> implements Map.Entry<K, V> {
public K key; public K key;
public V value; public V value;

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.
*/
package org.jackhuang.hellominecraft.utils;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author huangyuhui
*/
public class ReflectUtils {
public static Set<? extends Class<?>> getClasses(Class c) {
HashSet set = new HashSet();
set.addAll(Arrays.asList(c.getInterfaces()));
while(c != Object.class) {
set.add(c);
c = c.getSuperclass();
}
return set;
}
}

View File

@@ -32,6 +32,14 @@ import org.jackhuang.hellominecraft.HMCLog;
*/ */
public class SwingUtils { public class SwingUtils {
/**
* Make DefaultTableModel by overriding getColumnClass and isCellEditable of DefaultTableModel.
*
* @param titleA The title of each column.
* @param typesA The type of each column value.
* @param canEditA Is column editable?
* @return
*/
public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) { public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) {
return new javax.swing.table.DefaultTableModel( return new javax.swing.table.DefaultTableModel(
new Object[][]{}, new Object[][]{},
@@ -51,6 +59,10 @@ public class SwingUtils {
}; };
} }
/**
* Open URL by java.awt.Desktop
* @param link
*/
public static void openLink(URI link) { public static void openLink(URI link) {
try { try {
java.awt.Desktop.getDesktop().browse(link); java.awt.Desktop.getDesktop().browse(link);
@@ -59,38 +71,59 @@ public class SwingUtils {
} }
} }
/**
* Move the cursor to the end of TextArea.
* @param tf the TextArea
*/
public static void moveEnd(JTextArea tf) { public static void moveEnd(JTextArea tf) {
int position = tf.getText().length(); int position = tf.getText().length();
tf.setCaretPosition(position); tf.setCaretPosition(position);
} }
/**
* Move the cursor to the end of ScrollPane.
* @param pane the ScrollPane
*/
public static void moveEnd(JScrollPane pane) { public static void moveEnd(JScrollPane pane) {
JScrollBar bar = pane.getVerticalScrollBar(); JScrollBar bar = pane.getVerticalScrollBar();
bar.setValue(bar.getMaximum()); bar.setValue(bar.getMaximum());
} }
/**
* Get the DefaultListModel from JList.
* @param list
* @return Forcely Type casted to DefaultListModel
*/
public static DefaultListModel getDefaultListModel(JList list) { public static DefaultListModel getDefaultListModel(JList list) {
return (DefaultListModel)list.getModel(); return (DefaultListModel) list.getModel();
} }
/**
* Append new element to JList
* @param list the JList
* @param element the Element
*/
public static void appendLast(JList list, Object element) { public static void appendLast(JList list, Object element) {
getDefaultListModel(list).addElement(element); getDefaultListModel(list).addElement(element);
} }
public static void replaceLast(JList list, Object element) { public static void replaceLast(JList list, Object element) {
DefaultListModel model = getDefaultListModel(list); DefaultListModel model = getDefaultListModel(list);
model.set(model.getSize()-1, element); model.set(model.getSize() - 1, element);
} }
public static void clear(JList list) { public static void clear(JList list) {
list.setModel(new DefaultListModel()); list.setModel(new DefaultListModel());
} }
/**
* Clear the JTable
* @param table JTable with DefaultTableModel.
*/
public static void clearDefaultTable(JTable table) { public static void clearDefaultTable(JTable table) {
DefaultTableModel model = (DefaultTableModel)table.getModel(); DefaultTableModel model = (DefaultTableModel) table.getModel();
while(model.getRowCount() > 0) { while (model.getRowCount() > 0)
model.removeRow(0); model.removeRow(0);
}
table.updateUI(); table.updateUI();
} }

View File

@@ -26,6 +26,7 @@ import org.jackhuang.hellominecraft.HMCLog;
* @author huangyuhui * @author huangyuhui
*/ */
public final class UpdateChecker extends Thread { public final class UpdateChecker extends Thread {
public static boolean OUT_DATED = false; public static boolean OUT_DATED = false;
public VersionNumber base; public VersionNumber base;
public String type; public String type;
@@ -33,7 +34,7 @@ public final class UpdateChecker extends Thread {
public NonConsumer dl; public NonConsumer dl;
public UpdateChecker(VersionNumber base, String type, boolean continueUpdate, NonConsumer dl) { public UpdateChecker(VersionNumber base, String type, boolean continueUpdate, NonConsumer dl) {
super("UpdateChecker"); super("UpdateChecker");
this.base = base; this.base = base;
this.type = type; this.type = type;
this.continueUpdate = continueUpdate; this.continueUpdate = continueUpdate;
@@ -45,32 +46,29 @@ public final class UpdateChecker extends Thread {
@Override @Override
public void run() { public void run() {
String url = "http://huangyuhui.duapp.com/info.php?type=" + type, version; String url = "http://huangyuhui.duapp.com/info.php?type=" + type, version;
try { try {
version = NetUtils.doGet(url); version = NetUtils.doGet(url);
} catch (Exception e) { } catch (Exception e) {
HMCLog.warn("Failed to get update url.", e); HMCLog.warn("Failed to get update url.", e);
return; return;
} }
value = VersionNumber.check(version); value = VersionNumber.check(version);
if (!continueUpdate) { if (!continueUpdate)
return; return;
}
process(false); process(false);
} }
public void process(boolean showMessage) { public void process(boolean showMessage) {
if (value == null) { if (value == null) {
HMCLog.warn("Failed to check update..."); HMCLog.warn("Failed to check update...");
if(showMessage) { if (showMessage)
MessageBox.Show(C.i18n("update.failed")); MessageBox.Show(C.i18n("update.failed"));
} } else
} else { if (VersionNumber.isOlder(base, value)) {
if (VersionNumber.isOlder(base, value)) {
OUT_DATED = true; OUT_DATED = true;
dl.onDone(); dl.onDone();
} }
}
} }
public VersionNumber getNewVersion() { public VersionNumber getNewVersion() {

View File

@@ -46,6 +46,7 @@ import org.jackhuang.hellominecraft.HMCLog;
public final class Utils { public final class Utils {
private static final GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting(); private static final GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting();
public static GsonBuilder getDefaultGsonBuilder() { public static GsonBuilder getDefaultGsonBuilder() {
return gsonBuilder; return gsonBuilder;
} }
@@ -53,13 +54,12 @@ public final class Utils {
public static String[] getURL() { public static String[] getURL() {
URL[] urls = ((URLClassLoader) Utils.class.getClassLoader()).getURLs(); URL[] urls = ((URLClassLoader) Utils.class.getClassLoader()).getURLs();
String[] urlStrings = new String[urls.length]; String[] urlStrings = new String[urls.length];
for (int i = 0; i < urlStrings.length; i++) { for (int i = 0; i < urlStrings.length; i++)
try { try {
urlStrings[i] = URLDecoder.decode(urls[i].getPath(), "UTF-8"); urlStrings[i] = URLDecoder.decode(urls[i].getPath(), "UTF-8");
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
HMCLog.warn("Unsupported UTF-8 encoding", ex); HMCLog.warn("Unsupported UTF-8 encoding", ex);
} }
}
return urlStrings; return urlStrings;
} }
@@ -81,29 +81,29 @@ public final class Utils {
} }
public static int getSuggestedMemorySize() { public static int getSuggestedMemorySize() {
try { try {
OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
int memory = (int)(osmb.getTotalPhysicalMemorySize() / 1024 / 1024) / 4; int memory = (int) (osmb.getTotalPhysicalMemorySize() / 1024 / 1024) / 4;
memory = Math.round((float)memory/128.0f)*128; memory = Math.round((float) memory / 128.0f) * 128;
return memory; return memory;
} catch(Throwable t) { } catch (Throwable t) {
HMCLog.warn("Failed to get total memory size, use 1024MB.", t); HMCLog.warn("Failed to get total memory size, use 1024MB.", t);
return 1024; return 1024;
} }
} }
public static void setClipborad(String text) { public static void setClipborad(String text) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null);
} }
public static boolean openLink(String url) { public static boolean openLink(String url) {
try { try {
Desktop.getDesktop().browse(new URI(url)); Desktop.getDesktop().browse(new URI(url));
return true; return true;
} catch (URISyntaxException | IOException ex) { } catch (URISyntaxException | IOException ex) {
HMCLog.warn("Failed to open link:" + url, ex); HMCLog.warn("Failed to open link:" + url, ex);
return false; return false;
} }
} }
public static void openFolder(File f) { public static void openFolder(File f) {
@@ -112,7 +112,7 @@ public final class Utils {
java.awt.Desktop.getDesktop().open(f); java.awt.Desktop.getDesktop().open(f);
} catch (Exception ex) { } catch (Exception ex) {
MessageBox.Show(C.i18n("message.cannot_open_explorer") + ex.getMessage()); MessageBox.Show(C.i18n("message.cannot_open_explorer") + ex.getMessage());
HMCLog.warn("Failed to open folder:" + f, ex); HMCLog.warn("Failed to open folder:" + f, ex);
} }
} }
@@ -125,49 +125,49 @@ public final class Utils {
boolean loaded = false; boolean loaded = false;
// bgpath // bgpath
if (StrUtils.isNotBlank(bgpath) && !loaded) { if (StrUtils.isNotBlank(bgpath) && !loaded) {
String[] backgroundPath = bgpath.split(";"); String[] backgroundPath = bgpath.split(";");
if(backgroundPath.length > 0) { if (backgroundPath.length > 0) {
int index = r.nextInt(backgroundPath.length); int index = r.nextInt(backgroundPath.length);
background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundPath[index]).getScaledInstance(width, height, Image.SCALE_DEFAULT)); background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundPath[index]).getScaledInstance(width, height, Image.SCALE_DEFAULT));
HMCLog.log("Prepared background image in bgpath."); HMCLog.log("Prepared background image in bgpath.");
loaded = true; loaded = true;
} }
} }
// bgskin // bgskin
if (!loaded) { if (!loaded) {
File backgroundImageFile = new File("bg"); File backgroundImageFile = new File("bg");
if (backgroundImageFile.exists() && backgroundImageFile.isDirectory()) { if (backgroundImageFile.exists() && backgroundImageFile.isDirectory()) {
String[] backgroundPath = backgroundImageFile.list(); String[] backgroundPath = backgroundImageFile.list();
if(backgroundPath.length > 0) { if (backgroundPath.length > 0) {
int index = r.nextInt(backgroundPath.length); int index = r.nextInt(backgroundPath.length);
background = new ImageIcon(Toolkit.getDefaultToolkit().getImage("bg" + File.separator + backgroundPath[index]).getScaledInstance(width, height, Image.SCALE_DEFAULT)); background = new ImageIcon(Toolkit.getDefaultToolkit().getImage("bg" + File.separator + backgroundPath[index]).getScaledInstance(width, height, Image.SCALE_DEFAULT));
HMCLog.log("Prepared background image in bgskin folder."); HMCLog.log("Prepared background image in bgskin folder.");
loaded = true; loaded = true;
} }
} }
} }
// background.png // background.png
if (!loaded) { if (!loaded) {
File backgroundImageFile = new File("background.png"); File backgroundImageFile = new File("background.png");
if (backgroundImageFile.exists()) { if (backgroundImageFile.exists()) {
loaded = true; loaded = true;
background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundImageFile.getAbsolutePath()).getScaledInstance(width, height, Image.SCALE_DEFAULT)); background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundImageFile.getAbsolutePath()).getScaledInstance(width, height, Image.SCALE_DEFAULT));
HMCLog.log("Prepared background image in background.png."); HMCLog.log("Prepared background image in background.png.");
} }
} }
// background.jpg // background.jpg
if (!loaded) { if (!loaded) {
File backgroundImageFile = new File("background.jpg"); File backgroundImageFile = new File("background.jpg");
if (backgroundImageFile.exists()) { if (backgroundImageFile.exists()) {
loaded = true; //loaded = true;
background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundImageFile.getAbsolutePath()).getScaledInstance(width, height, Image.SCALE_DEFAULT)); background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundImageFile.getAbsolutePath()).getScaledInstance(width, height, Image.SCALE_DEFAULT));
HMCLog.log("Prepared background image in background.jpg."); HMCLog.log("Prepared background image in background.jpg.");
} }
} }
return background; return background;
} }
@@ -181,7 +181,7 @@ public final class Utils {
Method exit = z.getDeclaredMethod("exit", int.class); Method exit = z.getDeclaredMethod("exit", int.class);
exit.setAccessible(true); exit.setAccessible(true);
exit.invoke(z, 0); exit.invoke(z, 0);
} catch(ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
MessageBox.Show(C.i18n("launcher.exit_failed")); MessageBox.Show(C.i18n("launcher.exit_failed"));
e.printStackTrace(); e.printStackTrace();
} }

View File

@@ -27,16 +27,16 @@ public final class VersionNumber implements Comparable<VersionNumber> {
public byte firstVer, secondVer, thirdVer; public byte firstVer, secondVer, thirdVer;
public VersionNumber(byte a, byte b, byte c) { public VersionNumber(byte a, byte b, byte c) {
firstVer = a; secondVer = b; thirdVer = c; firstVer = a;
secondVer = b;
thirdVer = c;
} }
public static VersionNumber check(String data) { public static VersionNumber check(String data) {
while (!data.isEmpty() && ((data.charAt(0) < '0' || data.charAt(0) > '9') && data.charAt(0) != '.')) { while (!data.isEmpty() && ((data.charAt(0) < '0' || data.charAt(0) > '9') && data.charAt(0) != '.'))
data = data.substring(1); data = data.substring(1);
} if (data.isEmpty())
if (data.isEmpty()) {
return null; return null;
}
VersionNumber ur; VersionNumber ur;
String[] ver = data.split("\\."); String[] ver = data.split("\\.");
if (ver.length == 3) { if (ver.length == 3) {
@@ -55,24 +55,21 @@ public final class VersionNumber implements Comparable<VersionNumber> {
} }
public static boolean isOlder(VersionNumber a, VersionNumber b) { public static boolean isOlder(VersionNumber a, VersionNumber b) {
if (a.firstVer < b.firstVer) { if (a.firstVer < b.firstVer)
return true; return true;
} else if (a.firstVer == b.firstVer) { else if (a.firstVer == b.firstVer)
if (a.secondVer < b.secondVer) { if (a.secondVer < b.secondVer)
return true; return true;
} else if (a.secondVer == b.secondVer) { else if (a.secondVer == b.secondVer)
if (a.thirdVer < b.thirdVer) { if (a.thirdVer < b.thirdVer)
return true; return true;
}
}
}
return false; return false;
} }
@Override @Override
public int compareTo(VersionNumber o) { public int compareTo(VersionNumber o) {
if(isOlder(this, o)) return -1; if (isOlder(this, o)) return -1;
else if(isOlder(o, this)) return 1; else if (isOlder(o, this)) return 1;
else return 0; else return 0;
} }

View File

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.utils.code; package org.jackhuang.hellominecraft.utils.code;
import org.jackhuang.hellominecraft.utils.code.Hex;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.MessageDigest; import java.security.MessageDigest;

View File

@@ -20,5 +20,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface BiConsumer<V, V2> { public interface BiConsumer<V, V2> {
void onDone(V value, V2 value2); void onDone(V value, V2 value2);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface BiFunction<A, B, C> { public interface BiFunction<A, B, C> {
C apply(A a, B b); C apply(A a, B b);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface Consumer<T> { public interface Consumer<T> {
void accept(T t); void accept(T t);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface Function<T, R> { public interface Function<T, R> {
R apply(T t); R apply(T t);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface NonConsumer { public interface NonConsumer {
void onDone(); void onDone();
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface NonFunction<T> { public interface NonFunction<T> {
T onDone(); T onDone();
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface Predicate<T> { public interface Predicate<T> {
boolean apply(T t); boolean apply(T t);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface TriConsumer<V1, V2, V3> { public interface TriConsumer<V1, V2, V3> {
void onDone(V1 v1, V2 v2, V3 v3); void onDone(V1 v1, V2 v2, V3 v3);
} }

View File

@@ -52,11 +52,10 @@ public class Compressor {
BufferedOutputStream bos = new BufferedOutputStream(os); BufferedOutputStream bos = new BufferedOutputStream(os);
try (ZipOutputStream zos = new ZipOutputStream(bos)) { try (ZipOutputStream zos = new ZipOutputStream(bos)) {
String basePath; String basePath;
if (sourceDir.isDirectory()) { if (sourceDir.isDirectory())
basePath = sourceDir.getPath(); basePath = sourceDir.getPath();
} else {//直接压缩单个文件时,取父目录 else//直接压缩单个文件时,取父目录
basePath = sourceDir.getParent(); basePath = sourceDir.getParent();
}
zipFile(sourceDir, basePath, zos); zipFile(sourceDir, basePath, zos);
zos.closeEntry(); zos.closeEntry();
} }
@@ -72,22 +71,21 @@ public class Compressor {
private static void zipFile(File source, String basePath, private static void zipFile(File source, String basePath,
ZipOutputStream zos) throws IOException { ZipOutputStream zos) throws IOException {
File[] files; File[] files;
if (source.isDirectory()) { if (source.isDirectory())
files = source.listFiles(); files = source.listFiles();
} else { else {
files = new File[1]; files = new File[1];
files[0] = source; files[0] = source;
} }
String pathName;//存相对路径(相对于待压缩的根目录) String pathName;//存相对路径(相对于待压缩的根目录)
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int length; int length;
for (File file : files) { for (File file : files)
if (file.isDirectory()) { if (file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) pathName = file.getPath().substring(basePath.length() + 1)
+ "/"; + "/";
if (file.getName().toLowerCase().contains("meta-inf")) { if (file.getName().toLowerCase().contains("meta-inf"))
continue; continue;
}
zos.putNextEntry(new ZipEntry(pathName)); zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos); zipFile(file, basePath, zos);
} else { } else {
@@ -95,12 +93,10 @@ public class Compressor {
try (InputStream is = new FileInputStream(file)) { try (InputStream is = new FileInputStream(file)) {
BufferedInputStream bis = new BufferedInputStream(is); BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName)); zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) { while ((length = bis.read(buf)) > 0)
zos.write(buf, 0, length); zos.write(buf, 0, length);
}
} }
} }
}
} }
public static void unzip(String zipFileName, String extPlace) throws IOException { public static void unzip(String zipFileName, String extPlace) throws IOException {
@@ -129,7 +125,7 @@ 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);
@@ -142,15 +138,13 @@ public class Compressor {
strtemp = strPath + File.separator + gbkPath; strtemp = strPath + File.separator + gbkPath;
//建目录 //建目录
String strsubdir = gbkPath; String strsubdir = gbkPath;
for (int i = 0; i < strsubdir.length(); i++) { for (int i = 0; i < strsubdir.length(); i++)
if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) { if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
String temp = strPath + File.separator + strsubdir.substring(0, i); String temp = strPath + File.separator + strsubdir.substring(0, i);
File subdir = new File(temp); File subdir = new File(temp);
if (!subdir.exists()) { if (!subdir.exists())
subdir.mkdir(); subdir.mkdir();
}
} }
}
try (FileOutputStream fos = new FileOutputStream(strtemp); BufferedOutputStream bos = new BufferedOutputStream(fos)) { try (FileOutputStream fos = new FileOutputStream(strtemp); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
int c; int c;
while ((c = bis.read()) != -1) while ((c = bis.read()) != -1)

View File

@@ -36,27 +36,25 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
public class FileUtils { public class FileUtils {
public static void deleteDirectory(File directory) public static void deleteDirectory(File directory)
throws IOException { throws IOException {
if (!directory.exists()) { if (!directory.exists())
return; return;
}
if (!isSymlink(directory)) { if (!isSymlink(directory))
cleanDirectory(directory); cleanDirectory(directory);
}
if (!directory.delete()) { if (!directory.delete()) {
String message = "Unable to delete directory " + directory + "."; String message = "Unable to delete directory " + directory + ".";
throw new IOException(message); throw new IOException(message);
} }
} }
public static boolean deleteDirectoryQuietly(File directory) { public static boolean deleteDirectoryQuietly(File directory) {
try { try {
deleteDirectory(directory); deleteDirectory(directory);
return true; return true;
} catch(Exception e) { } catch (Exception e) {
HMCLog.err("Failed to delete directory " + directory, e); HMCLog.err("Failed to delete directory " + directory, e);
return false; return false;
} }
@@ -66,165 +64,147 @@ public class FileUtils {
try { try {
cleanDirectory(directory); cleanDirectory(directory);
return true; return true;
} catch(Exception e) { } catch (Exception e) {
HMCLog.err("Failed to clean directory " + directory, e); HMCLog.err("Failed to clean directory " + directory, e);
return false; return false;
} }
} }
public static void cleanDirectory(File directory) public static void cleanDirectory(File directory)
throws IOException { throws IOException {
if (!directory.exists()) { if (!directory.exists()) {
//String message = directory + " does not exist"; //String message = directory + " does not exist";
//throw new IllegalArgumentException(message); //throw new IllegalArgumentException(message);
directory.mkdirs(); directory.mkdirs();
return; return;
} }
if (!directory.isDirectory()) { if (!directory.isDirectory()) {
String message = directory + " is not a directory"; String message = directory + " is not a directory";
throw new IllegalArgumentException(message); throw new IllegalArgumentException(message);
} }
File[] files = directory.listFiles(); File[] files = directory.listFiles();
if (files == null) { if (files == null)
throw new IOException("Failed to list contents of " + directory); throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null; IOException exception = null;
for (File file : files) { for (File file : files)
try { try {
forceDelete(file); forceDelete(file);
} catch (IOException ioe) { } catch (IOException ioe) {
exception = ioe; exception = ioe;
} }
}
if (null != exception) { if (null != exception)
throw exception; throw exception;
}
} }
public static void forceDelete(File file) public static void forceDelete(File file)
throws IOException { throws IOException {
if (file.isDirectory()) { if (file.isDirectory())
deleteDirectory(file); deleteDirectory(file);
} else { else {
boolean filePresent = file.exists(); boolean filePresent = file.exists();
if (!file.delete()) { if (!file.delete()) {
if (!filePresent) { if (!filePresent)
throw new FileNotFoundException("File does not exist: " + file); throw new FileNotFoundException("File does not exist: " + file);
} String message = "Unable to delete file: " + file;
String message = "Unable to delete file: " + file;
throw new IOException(message); throw new IOException(message);
} }
} }
} }
public static boolean isSymlink(File file) public static boolean isSymlink(File file)
throws IOException { throws IOException {
if (file == null) { if (file == null)
throw new NullPointerException("File must not be null"); throw new NullPointerException("File must not be null");
} if (File.separatorChar == '\\')
if (File.separatorChar == '\\') { return false;
return false; File fileInCanonicalDir;
} if (file.getParent() == null)
File fileInCanonicalDir; fileInCanonicalDir = file;
if (file.getParent() == null) { else {
fileInCanonicalDir = file; File canonicalDir = file.getParentFile().getCanonicalFile();
} else { fileInCanonicalDir = new File(canonicalDir, file.getName());
File canonicalDir = file.getParentFile().getCanonicalFile(); }
fileInCanonicalDir = new File(canonicalDir, file.getName());
}
return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile()); return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
} }
public static void copyDirectory(File srcDir, File destDir) public static void copyDirectory(File srcDir, File destDir)
throws IOException { throws IOException {
copyDirectory(srcDir, destDir, true); copyDirectory(srcDir, destDir, true);
} }
public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate)
throws IOException { throws IOException {
copyDirectory(srcDir, destDir, null, preserveFileDate); copyDirectory(srcDir, destDir, null, preserveFileDate);
} }
public static void copyDirectory(File srcDir, File destDir, FileFilter filter) public static void copyDirectory(File srcDir, File destDir, FileFilter filter)
throws IOException { throws IOException {
copyDirectory(srcDir, destDir, filter, true); copyDirectory(srcDir, destDir, filter, true);
} }
public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)
throws IOException { throws IOException {
if (srcDir == null) { if (srcDir == null)
throw new NullPointerException("Source must not be null"); throw new NullPointerException("Source must not be null");
} if (destDir == null)
if (destDir == null) { throw new NullPointerException("Destination must not be null");
throw new NullPointerException("Destination must not be null"); if (!srcDir.exists())
} throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
if (!srcDir.exists()) { if (!srcDir.isDirectory())
throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); throw new IOException("Source '" + srcDir + "' exists but is not a directory");
} if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath()))
if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
throw new IOException("Source '" + srcDir + "' exists but is not a directory");
}
if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
}
List exclusionList = null; List exclusionList = null;
if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if ((srcFiles != null) && (srcFiles.length > 0)) { if ((srcFiles != null) && (srcFiles.length > 0)) {
exclusionList = new ArrayList(srcFiles.length); exclusionList = new ArrayList(srcFiles.length);
for (File srcFile : srcFiles) { for (File srcFile : srcFiles) {
File copiedFile = new File(destDir, srcFile.getName()); File copiedFile = new File(destDir, srcFile.getName());
exclusionList.add(copiedFile.getCanonicalPath()); exclusionList.add(copiedFile.getCanonicalPath());
} }
} }
} }
doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList); doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);
} }
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList) private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList)
throws IOException { throws IOException {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles == null) { if (srcFiles == null)
throw new IOException("Failed to list contents of " + srcDir); throw new IOException("Failed to list contents of " + srcDir);
} if (destDir.exists()) {
if (destDir.exists()) { if (!destDir.isDirectory())
if (!destDir.isDirectory()) { throw new IOException("Destination '" + destDir + "' exists but is not a directory");
throw new IOException("Destination '" + destDir + "' exists but is not a directory"); } else if ((!destDir.mkdirs()) && (!destDir.isDirectory()))
} throw new IOException("Destination '" + destDir + "' directory cannot be created");
} else if ((!destDir.mkdirs()) && (!destDir.isDirectory())) {
throw new IOException("Destination '" + destDir + "' directory cannot be created");
}
if (!destDir.canWrite()) { if (!destDir.canWrite())
throw new IOException("Destination '" + destDir + "' cannot be written to"); throw new IOException("Destination '" + destDir + "' cannot be written to");
} for (File srcFile : srcFiles) {
for (File srcFile : srcFiles) { File dstFile = new File(destDir, srcFile.getName());
File dstFile = new File(destDir, srcFile.getName()); if ((exclusionList == null) || (!exclusionList.contains(srcFile.getCanonicalPath())))
if ((exclusionList == null) || (!exclusionList.contains(srcFile.getCanonicalPath()))) { if (srcFile.isDirectory())
if (srcFile.isDirectory()) { doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList); else
} else { doCopyFile(srcFile, dstFile, preserveFileDate);
doCopyFile(srcFile, dstFile, preserveFileDate);
}
}
} }
if (preserveFileDate) { if (preserveFileDate)
destDir.setLastModified(srcDir.lastModified()); destDir.setLastModified(srcDir.lastModified());
}
} }
public static String readFileToString(File file) public static String readFileToString(File file)
throws IOException { throws IOException {
return NetUtils.getStreamContent(IOUtils.openInputStream(file)); return NetUtils.getStreamContent(IOUtils.openInputStream(file));
} }
public static String readFileToStringQuietly(File file) { public static String readFileToStringQuietly(File file) {
@@ -237,239 +217,216 @@ public class FileUtils {
} }
public static String readFileToString(File file, String charset) public static String readFileToString(File file, String charset)
throws IOException { throws IOException {
return NetUtils.getStreamContent(IOUtils.openInputStream(file), charset); return NetUtils.getStreamContent(IOUtils.openInputStream(file), charset);
} }
public static String readFileToStringIgnoreFileNotFound(File file) throws IOException { public static String readFileToStringIgnoreFileNotFound(File file) throws IOException {
try { try {
return NetUtils.getStreamContent(IOUtils.openInputStream(file)); return NetUtils.getStreamContent(IOUtils.openInputStream(file));
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
return ""; return "";
} }
} }
public static void copyFile(File srcFile, File destFile) public static void copyFile(File srcFile, File destFile)
throws IOException { throws IOException {
copyFile(srcFile, destFile, true); copyFile(srcFile, destFile, true);
} }
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) public static void copyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException { throws IOException {
if (srcFile == null) { if (srcFile == null)
throw new NullPointerException("Source must not be null"); throw new NullPointerException("Source must not be null");
} if (destFile == null)
if (destFile == null) { throw new NullPointerException("Destination must not be null");
throw new NullPointerException("Destination must not be null"); if (!srcFile.exists())
} throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
if (!srcFile.exists()) { if (srcFile.isDirectory())
throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); throw new IOException("Source '" + srcFile + "' exists but is a directory");
} if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath()))
if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
throw new IOException("Source '" + srcFile + "' exists but is a directory"); File parentFile = destFile.getParentFile();
} if ((parentFile != null)
if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) { && (!parentFile.mkdirs()) && (!parentFile.isDirectory()))
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); throw new IOException("Destination '" + parentFile + "' directory cannot be created");
}
File parentFile = destFile.getParentFile();
if ((parentFile != null)
&& (!parentFile.mkdirs()) && (!parentFile.isDirectory())) {
throw new IOException("Destination '" + parentFile + "' directory cannot be created");
}
if ((destFile.exists()) && (!destFile.canWrite())) { if ((destFile.exists()) && (!destFile.canWrite()))
throw new IOException("Destination '" + destFile + "' exists but is read-only"); throw new IOException("Destination '" + destFile + "' exists but is read-only");
} doCopyFile(srcFile, destFile, preserveFileDate);
doCopyFile(srcFile, destFile, preserveFileDate);
} }
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException { throws IOException {
if ((destFile.exists()) && (destFile.isDirectory())) { if ((destFile.exists()) && (destFile.isDirectory()))
throw new IOException("Destination '" + destFile + "' exists but is a directory"); throw new IOException("Destination '" + destFile + "' exists but is a directory");
}
FileInputStream fis = null; FileInputStream fis = null;
FileOutputStream fos = null; FileOutputStream fos = null;
FileChannel input = null; FileChannel input = null;
FileChannel output = null; FileChannel output = null;
try { try {
fis = new FileInputStream(srcFile); fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile); fos = new FileOutputStream(destFile);
input = fis.getChannel(); input = fis.getChannel();
output = fos.getChannel(); output = fos.getChannel();
long size = input.size(); long size = input.size();
long pos = 0L; long pos = 0L;
long count; long count;
while (pos < size) { while (pos < size) {
count = size - pos > 31457280L ? 31457280L : size - pos; count = size - pos > 31457280L ? 31457280L : size - pos;
pos += output.transferFrom(input, pos, count); pos += output.transferFrom(input, pos, count);
} }
} finally { } finally {
IOUtils.closeQuietly(output); IOUtils.closeQuietly(output);
IOUtils.closeQuietly(fos); IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(input); IOUtils.closeQuietly(input);
IOUtils.closeQuietly(fis); IOUtils.closeQuietly(fis);
} }
if (srcFile.length() != destFile.length()) { if (srcFile.length() != destFile.length())
throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
}
if (preserveFileDate) { if (preserveFileDate)
destFile.setLastModified(srcFile.lastModified()); destFile.setLastModified(srcFile.lastModified());
}
} }
public static int indexOfLastSeparator(String filename) { public static int indexOfLastSeparator(String filename) {
if (filename == null) { if (filename == null)
return -1; return -1;
} int lastUnixPos = filename.lastIndexOf(47);
int lastUnixPos = filename.lastIndexOf(47); int lastWindowsPos = filename.lastIndexOf(92);
int lastWindowsPos = filename.lastIndexOf(92); return Math.max(lastUnixPos, lastWindowsPos);
return Math.max(lastUnixPos, lastWindowsPos);
} }
public static int indexOfExtension(String filename) { public static int indexOfExtension(String filename) {
if (filename == null) { if (filename == null)
return -1; return -1;
} int extensionPos = filename.lastIndexOf(46);
int extensionPos = filename.lastIndexOf(46); int lastSeparator = indexOfLastSeparator(filename);
int lastSeparator = indexOfLastSeparator(filename); return lastSeparator > extensionPos ? -1 : extensionPos;
return lastSeparator > extensionPos ? -1 : extensionPos;
} }
public static String getName(String filename) { public static String getName(String filename) {
if (filename == null) { if (filename == null)
return null; return null;
} int index = indexOfLastSeparator(filename);
int index = indexOfLastSeparator(filename); return filename.substring(index + 1);
return filename.substring(index + 1);
} }
public static String getBaseName(String filename) { public static String getBaseName(String filename) {
return removeExtension(getName(filename)); return removeExtension(getName(filename));
} }
public static String getExtension(String filename) { public static String getExtension(String filename) {
if (filename == null) { if (filename == null)
return null; return null;
} int index = indexOfExtension(filename);
int index = indexOfExtension(filename); if (index == -1)
if (index == -1) { return "";
return ""; return filename.substring(index + 1);
}
return filename.substring(index + 1);
} }
public static String removeExtension(String filename) { public static String removeExtension(String filename) {
if (filename == null) { if (filename == null)
return null; return null;
} int index = indexOfExtension(filename);
int index = indexOfExtension(filename); if (index == -1)
if (index == -1) { return filename;
return filename; return filename.substring(0, index);
}
return filename.substring(0, index);
} }
public static void writeQuietly(File file, CharSequence data) { public static void writeQuietly(File file, CharSequence data) {
try { try {
write(file, data); write(file, data);
} catch(IOException e) { } catch (IOException e) {
HMCLog.warn("Failed to write data to file: " + file, e); HMCLog.warn("Failed to write data to file: " + file, e);
} }
} }
public static void write(File file, CharSequence data) public static void write(File file, CharSequence data)
throws IOException { throws IOException {
write(file, data, "UTF-8", false); write(file, data, "UTF-8", false);
} }
public static void write(File file, CharSequence data, boolean append) public static void write(File file, CharSequence data, boolean append)
throws IOException { throws IOException {
write(file, data, "UTF-8", append); write(file, data, "UTF-8", append);
} }
public static void write(File file, CharSequence data, String encoding) public static void write(File file, CharSequence data, String encoding)
throws IOException { throws IOException {
write(file, data, encoding, false); write(file, data, encoding, false);
} }
public static void write(File file, CharSequence data, String encoding, boolean append) public static void write(File file, CharSequence data, String encoding, boolean append)
throws IOException { throws IOException {
String str = data == null ? null : data.toString(); String str = data == null ? null : data.toString();
writeStringToFile(file, str, encoding, append); writeStringToFile(file, str, encoding, append);
} }
public static void writeStringToFile(File file, String data) public static void writeStringToFile(File file, String data)
throws IOException { throws IOException {
writeStringToFile(file, data, "UTF-8", false); writeStringToFile(file, data, "UTF-8", false);
} }
public static void writeStringToFile(File file, String data, String encoding) public static void writeStringToFile(File file, String data, String encoding)
throws IOException { throws IOException {
writeStringToFile(file, data, encoding, false); writeStringToFile(file, data, encoding, false);
} }
public static void writeStringToFile(File file, String data, String encoding, boolean append) public static void writeStringToFile(File file, String data, String encoding, boolean append)
throws IOException { throws IOException {
OutputStream out = null; OutputStream out = null;
try { try {
out = openOutputStream(file, append); out = openOutputStream(file, append);
IOUtils.write(data, out, encoding); IOUtils.write(data, out, encoding);
out.close(); out.close();
} finally { } finally {
IOUtils.closeQuietly(out); IOUtils.closeQuietly(out);
} }
} }
public static FileInputStream openInputStream(File file) public static FileInputStream openInputStream(File file)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) { if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
} if (!file.canRead())
if (!file.canRead()) { throw new IOException("File '" + file + "' cannot be read");
throw new IOException("File '" + file + "' cannot be read"); } else
} throw new FileNotFoundException("File '" + file + "' does not exist");
} else { return new FileInputStream(file);
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
} }
public static FileOutputStream openOutputStream(File file) public static FileOutputStream openOutputStream(File file)
throws IOException { throws IOException {
return openOutputStream(file, false); return openOutputStream(file, false);
} }
public static FileOutputStream openOutputStream(File file, boolean append) public static FileOutputStream openOutputStream(File file, boolean append)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) { if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
} if (!file.canWrite())
if (!file.canWrite()) { throw new IOException("File '" + file + "' cannot be written to");
throw new IOException("File '" + file + "' cannot be written to"); } else {
} File parent = file.getParentFile();
} else { if ((parent != null)
File parent = file.getParentFile(); && (!parent.mkdirs()) && (!parent.isDirectory()))
if ((parent != null) throw new IOException("Directory '" + parent + "' could not be created");
&& (!parent.mkdirs()) && (!parent.isDirectory())) {
throw new IOException("Directory '" + parent + "' could not be created");
}
file.createNewFile(); file.createNewFile();
} }
return new FileOutputStream(file, append); return new FileOutputStream(file, append);
} }
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();
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

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.utils.system; package org.jackhuang.hellominecraft.utils.system;
import org.jackhuang.hellominecraft.utils.system.OS;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.Closeable; import java.io.Closeable;
import java.io.File; import java.io.File;
@@ -43,14 +42,12 @@ import org.jackhuang.hellominecraft.HMCLog;
public class IOUtils { public class IOUtils {
public static String addSeparator(String path) { public static String addSeparator(String path) {
if (path == null || path.trim().length() == 0) { if (path == null || path.trim().length() == 0)
return ""; return "";
} if (isSeparator(path.charAt(path.length() - 1)))
if (isSeparator(path.charAt(path.length() - 1))) {
return path; return path;
} else { else
return path + File.separatorChar; return path + File.separatorChar;
}
} }
public static boolean isSeparator(char ch) { public static boolean isSeparator(char ch) {
@@ -60,21 +57,18 @@ public class IOUtils {
public static String removeLastSeparator(String dir) { public static String removeLastSeparator(String dir) {
String t = dir.trim(); String t = dir.trim();
char ch = t.charAt(t.length() - 1); char ch = t.charAt(t.length() - 1);
if (isSeparator(ch)) { if (isSeparator(ch))
return t.substring(0, t.length() - 1); return t.substring(0, t.length() - 1);
}
return t; return t;
} }
public static String extractLastDirectory(String dir) { public static String extractLastDirectory(String dir) {
String t = removeLastSeparator(dir); String t = removeLastSeparator(dir);
int i = t.length() - 1; int i = t.length() - 1;
while (i >= 0 && !isSeparator(dir.charAt(i))) { while (i >= 0 && !isSeparator(dir.charAt(i)))
i--; i--;
} if (i < 0)
if (i < 0) {
return t; return t;
}
return t.substring(i + 1, (t.length() - i) + (i + 1) - 1); return t.substring(i + 1, (t.length() - i) + (i + 1) - 1);
} }
@@ -83,11 +77,9 @@ public class IOUtils {
if (f.isDirectory()) { if (f.isDirectory()) {
File[] f1 = f.listFiles(); File[] f1 = f.listFiles();
int len = f1.length; int len = f1.length;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
if (f1[i].isFile()) { if (f1[i].isFile())
arr.add(f1[i].getName()); arr.add(f1[i].getName());
}
}
} }
return arr; return arr;
} }
@@ -97,11 +89,9 @@ public class IOUtils {
if (f.isDirectory()) { if (f.isDirectory()) {
File[] f1 = f.listFiles(); File[] f1 = f.listFiles();
int len = f1.length; int len = f1.length;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
if (f1[i].isFile()) { if (f1[i].isFile())
arr.add(addSeparator(f.getAbsolutePath()) + f1[i].getName()); arr.add(addSeparator(f.getAbsolutePath()) + f1[i].getName());
}
}
} }
return arr; return arr;
} }
@@ -111,11 +101,9 @@ public class IOUtils {
if (f.isDirectory()) { if (f.isDirectory()) {
File[] f1 = f.listFiles(); File[] f1 = f.listFiles();
int len = f1.length; int len = f1.length;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
if (f1[i].isDirectory()) { if (f1[i].isDirectory())
arr.add(f1[i].getName()); arr.add(f1[i].getName());
}
}
} }
return arr; return arr;
} }
@@ -152,9 +140,8 @@ public class IOUtils {
for (int i = 0; i < macs.length; i++) { for (int i = 0; i < macs.length; i++) {
mac = Integer.toHexString(macs[i] & 0xFF); mac = Integer.toHexString(macs[i] & 0xFF);
if (mac.length() == 1) { if (mac.length() == 1)
mac = '0' + mac; mac = '0' + mac;
}
sb.append(mac).append("-"); sb.append(mac).append("-");
} }
@@ -179,11 +166,10 @@ public class IOUtils {
public static String getJavaDir() { public static String getJavaDir() {
String path = System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar; String path = System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar;
path = addSeparator(path); path = addSeparator(path);
if (OS.os() == OS.WINDOWS && new File(path + "javaw.exe").isFile()) { if (OS.os() == OS.WINDOWS && new File(path + "javaw.exe").isFile())
return path + "javaw.exe"; return path + "javaw.exe";
} else { else
return path + "java"; return path + "java";
}
} }
public static byte[] readFully(InputStream stream) throws IOException { public static byte[] readFully(InputStream stream) throws IOException {
@@ -192,9 +178,8 @@ public class IOUtils {
int len; int len;
do { do {
len = stream.read(data); len = stream.read(data);
if (len <= 0) { if (len <= 0)
continue; continue;
}
entryBuffer.write(data, 0, len); entryBuffer.write(data, 0, len);
} while (len != -1); } while (len != -1);
@@ -219,39 +204,33 @@ public class IOUtils {
public static void closeQuietly(Closeable closeable) { public static void closeQuietly(Closeable closeable) {
try { try {
if (closeable != null) { if (closeable != null)
closeable.close(); closeable.close();
}
} catch (IOException ioe) { } catch (IOException ioe) {
} }
} }
public static void write(byte[] data, OutputStream output) public static void write(byte[] data, OutputStream output)
throws IOException { throws IOException {
if (data != null) { if (data != null)
output.write(data); output.write(data);
}
} }
public static void write(String data, OutputStream output, String encoding) public static void write(String data, OutputStream output, String encoding)
throws IOException { throws IOException {
if (data != null) { if (data != null)
output.write(data.getBytes(encoding)); output.write(data.getBytes(encoding));
}
} }
public static FileInputStream openInputStream(File file) public static FileInputStream openInputStream(File file)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) { if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
} if (!file.canRead())
if (!file.canRead()) {
throw new IOException("File '" + file + "' cannot be read"); throw new IOException("File '" + file + "' cannot be read");
} } else
} else {
throw new FileNotFoundException("File '" + file + "' does not exist"); throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file); return new FileInputStream(file);
} }

View File

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.utils.system; package org.jackhuang.hellominecraft.utils.system;
import org.jackhuang.hellominecraft.utils.system.ProcessManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -35,7 +34,7 @@ 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

@@ -111,16 +111,12 @@ 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.")) if (javaVersion.contains("1.9.")) a = JAVA_19;
a = JAVA_19; else if (javaVersion.contains("1.8.")) a = JAVA_18;
else if (javaVersion.contains("1.8.")) else if (javaVersion.contains("1.7.")) a = JAVA_17;
a = JAVA_18; else if (javaVersion.contains("1.6.")) a = JAVA_16;
else if (javaVersion.contains("1.7."))
a = JAVA_17;
else if (javaVersion.contains("1.6."))
a = JAVA_16;
return a; return a;
} }

View File

@@ -22,8 +22,8 @@ import org.jackhuang.hellominecraft.C;
/** /**
* @author huangyuhui * @author huangyuhui
*/ */
public class MessageBox public class MessageBox {
{
private static String Title = C.i18n("message.info"); private static String Title = C.i18n("message.info");
/** /**
* Buttons: OK * Buttons: OK
@@ -36,7 +36,7 @@ public class MessageBox
/** /**
* Buttons: Yes No Cancel * Buttons: Yes No Cancel
*/ */
public static final int YES_NO_CANCEL_OPTION =11; public static final int YES_NO_CANCEL_OPTION = 11;
/** /**
* Buttons: OK Cancel * Buttons: OK Cancel
*/ */
@@ -84,15 +84,14 @@ public class MessageBox
/** /**
* Show MsgBox with title and options * Show MsgBox with title and options
*
* @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) {
{ switch (Option) {
switch(Option)
{
case YES_NO_OPTION: case YES_NO_OPTION:
case YES_NO_CANCEL_OPTION: case YES_NO_CANCEL_OPTION:
case OK_CANCEL_OPTION: case OK_CANCEL_OPTION:
@@ -105,22 +104,22 @@ public class MessageBox
/** /**
* Show MsgBox with options * Show MsgBox with options
*
* @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) {
{
return Show(Msg, Title, Option); return Show(Msg, Title, Option);
} }
/** /**
* 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) {
{
return Show(Msg, Title, INFORMATION_MESSAGE); return Show(Msg, Title, INFORMATION_MESSAGE);
} }
} }

View File

@@ -39,24 +39,18 @@ public enum OS {
public static OS os() { public static OS os() {
String str; String str;
if ((str = System.getProperty("os.name").toLowerCase()) if ((str = System.getProperty("os.name").toLowerCase())
.contains("win")) { .contains("win"))
return OS.WINDOWS; return OS.WINDOWS;
} if (str.contains("mac"))
if (str.contains("mac")) {
return OS.OSX; return OS.OSX;
} if (str.contains("solaris"))
if (str.contains("solaris")) {
return OS.LINUX; return OS.LINUX;
} if (str.contains("sunos"))
if (str.contains("sunos")) {
return OS.LINUX; return OS.LINUX;
} if (str.contains("linux"))
if (str.contains("linux")) {
return OS.LINUX; return OS.LINUX;
} if (str.contains("unix"))
if (str.contains("unix")) {
return OS.LINUX; return OS.LINUX;
}
return OS.UNKOWN; return OS.UNKOWN;
} }
@@ -67,7 +61,7 @@ public enum OS {
try { try {
OperatingSystemMXBean o = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); OperatingSystemMXBean o = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
return o.getTotalPhysicalMemorySize(); return o.getTotalPhysicalMemorySize();
} catch(Throwable t) { } catch (Throwable t) {
HMCLog.warn("Failed to get total physical memory size"); HMCLog.warn("Failed to get total physical memory size");
return -1; return -1;
} }

View File

@@ -50,6 +50,6 @@ public enum Platform {
public abstract String getBit(); public abstract String getBit();
public static Platform getPlatform() { public static Platform getPlatform() {
return System.getProperty("os.arch").contains("64") ? BIT_64 : BIT_32; return System.getProperty("os.arch").contains("64") ? BIT_64 : BIT_32;
} }
} }

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