Compare commits

..
7 Commits
35 .. 41
Author SHA1 Message Date
huangyuhui 4a2ac63d25 Added removal of installers for Issue #55 2016-03-28 20:57:01 +08:00
huangyuhui 5437968c83 Fixed #56 2016-03-28 20:45:06 +08:00
huangyuhui 8022252452 Fixed task system 2016-03-27 14:13:59 +08:00
huangyuhui ea6571fdb6 Fix #53 2016-03-26 13:02:47 +08:00
huanghongxun 2f7f692b84 Merge pull request #51 from tsl0922/master
Fix cpu ratio for mac
2016-03-25 19:19:46 +08:00
Shuanglei Tao 721df1d17c Fix cpu ratio for mac 2016-03-24 21:29:48 +08:00
huangyuhui 7a2e43f949 Fixed #50 2016-03-19 19:55:42 +08:00
30 changed files with 433 additions and 363 deletions

No files matched your search

@@ -22,7 +22,6 @@ import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftAssetService;
@@ -30,7 +29,6 @@ import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftService;
import org.jackhuang.hellominecraft.launcher.core.version.AssetIndexDownloadInfo;
import org.jackhuang.hellominecraft.launcher.core.version.MinecraftVersion;
import org.jackhuang.hellominecraft.util.MessageBox;
import org.jackhuang.hellominecraft.util.Utils;
import org.jackhuang.hellominecraft.util.func.Function;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.tasks.Task;
@@ -58,23 +56,7 @@ public class MinecraftAssetService extends IMinecraftAssetService {
public Task downloadAssets(final MinecraftVersion mv) {
if (mv == null)
return null;
return new TaskInfo("Download Assets") {
Collection<Task> afters = new HashSet<>();
@Override
public Collection<Task> getDependTasks() {
return Arrays.asList(IAssetsHandler.ASSETS_HANDLER.getList(mv, service.asset()));
}
@Override
public void executeTask() {
}
@Override
public Collection<Task> getAfterTasks() {
return Arrays.asList(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(service.getDownloadType().getProvider()));
}
};
return IAssetsHandler.ASSETS_HANDLER.getList(mv, service.asset()).after(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(service.getDownloadType().getProvider()));
}
@Override
@@ -25,7 +25,7 @@ public class CurseDownloadProvider extends MojangDownloadProvider {
@Override
public String getParsedDownloadURL(String str) {
return str == null ? null : str.replace("http://files.minecraftforge.net/maven", "http://ftb.cursecdn.com/FTB2/maven/");
return str == null ? null : str.replace("http://files.minecraftforge.net/maven", "http://ftb.cursecdn.com/FTB2/maven");
}
}
@@ -29,6 +29,6 @@ public class MinecraftRemoteVersion {
public String getUrl(DownloadType type) {
if (url == null)
return type.getProvider().getVersionsDownloadURL() + id + "/" + id + ".json";
return url;
return type.getProvider().getParsedDownloadURL(url);
}
}
@@ -22,13 +22,13 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import org.jackhuang.hellominecraft.util.func.Consumer;
import org.jackhuang.hellominecraft.util.tasks.Task;
/**
*
* @author huangyuhui
*/
public abstract class InstallerVersionList implements Consumer<String[]> {
public abstract class InstallerVersionList {
/**
* Refresh installer versions list from the downloaded content.
@@ -37,7 +37,7 @@ public abstract class InstallerVersionList implements Consumer<String[]> {
*
* @throws java.lang.Exception including network exceptions, IO exceptions.
*/
public abstract void refreshList(String[] versions) throws Exception;
public abstract Task refresh(String[] versions);
/**
* Installer name.
@@ -117,13 +117,4 @@ public abstract class InstallerVersionList implements Consumer<String[]> {
return o2.compareTo(o1);
}
}
@Override
public void accept(String[] v) {
try {
refreshList(v);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
@@ -27,10 +27,9 @@ import org.jackhuang.hellominecraft.launcher.core.install.liteloader.LiteLoaderV
import org.jackhuang.hellominecraft.launcher.core.install.optifine.OptiFineInstaller;
import org.jackhuang.hellominecraft.launcher.core.install.optifine.vanilla.OptiFineDownloadFormatter;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.tasks.TaskInfo;
import org.jackhuang.hellominecraft.util.tasks.TaskWindow;
import org.jackhuang.hellominecraft.util.tasks.download.FileDownloadTask;
import org.jackhuang.hellominecraft.util.system.IOUtils;
import org.jackhuang.hellominecraft.util.tasks.DeleteFileTask;
/**
*
@@ -58,47 +57,31 @@ public final class MinecraftInstallerService extends IMinecraftInstallerService
@Override
public Task downloadForge(String installId, InstallerVersion v) {
return new TaskInfo("Forge Downloader") {
@Override
public void executeTask() {
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "forge-installer.jar");
if (v.installer != null)
TaskWindow.factory()
.append(new FileDownloadTask(service.getDownloadType().getProvider().getParsedDownloadURL(v.installer), filepath).setTag("forge"))
.append(new ForgeInstaller(service, filepath))
.create();
}
};
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "forge-installer.jar");
if (v.installer == null)
return null;
else
return new FileDownloadTask(service.getDownloadType().getProvider().getParsedDownloadURL(v.installer), filepath).setTag("forge")
.after(new ForgeInstaller(service, filepath))
.after(new DeleteFileTask(filepath));
}
@Override
public Task downloadOptiFine(String installId, InstallerVersion v) {
return new TaskInfo("OptiFine Downloader") {
@Override
public void executeTask() {
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "optifine-installer.jar");
if (v.installer != null) {
OptiFineDownloadFormatter task = new OptiFineDownloadFormatter(v.installer);
TaskWindow.factory().append(task)
.append(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.append(new OptiFineInstaller(service, installId, v, filepath))
.create();
}
}
};
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "optifine-installer.jar");
if (v.installer == null)
return null;
OptiFineDownloadFormatter task = new OptiFineDownloadFormatter(v.installer);
return task.after(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.after(new OptiFineInstaller(service, installId, v, filepath))
.after(new DeleteFileTask(filepath));
}
@Override
public Task downloadLiteLoader(String installId, InstallerVersion v) {
return new TaskInfo("LiteLoader Downloader") {
@Override
public void executeTask() {
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "liteloader-universal.jar");
FileDownloadTask task = (FileDownloadTask) new FileDownloadTask(v.universal, filepath).setTag("LiteLoader");
TaskWindow.factory()
.append(task).append(new LiteLoaderInstaller(service, installId, (LiteLoaderVersionList.LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.create();
}
};
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "liteloader-universal.jar");
FileDownloadTask task = (FileDownloadTask) new FileDownloadTask(v.universal, filepath).setTag("LiteLoader");
return task.after(new LiteLoaderInstaller(service, installId, (LiteLoaderVersionList.LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.after(new DeleteFileTask(filepath));
}
}
@@ -18,6 +18,8 @@
package org.jackhuang.hellominecraft.launcher.core.install.forge;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -27,7 +29,9 @@ import org.jackhuang.hellominecraft.launcher.core.download.DownloadType;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionNewerComparator;
import org.jackhuang.hellominecraft.util.NetUtils;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.tasks.TaskInfo;
import org.jackhuang.hellominecraft.util.tasks.download.HTTPGetTask;
/**
*
@@ -48,54 +52,68 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
public List<InstallerVersion> versions;
@Override
public void refreshList(String[] needed) throws Exception {
public Task refresh(String[] needed) {
if (root != null)
return;
String s = NetUtils.get(DownloadType.getSuggestedDownloadType().getProvider().getParsedDownloadURL(C.URL_FORGE_LIST));
return null;
return new TaskInfo(C.i18n("install.forge.get_list")) {
HTTPGetTask task = new HTTPGetTask(DownloadType.getSuggestedDownloadType().getProvider().getParsedDownloadURL(C.URL_FORGE_LIST));
root = C.GSON.fromJson(s, MinecraftForgeVersionRoot.class);
versionMap = new HashMap<>();
versions = new ArrayList<>();
for (Map.Entry<String, int[]> arr : root.mcversion.entrySet()) {
String mcver = StrUtils.formatVersion(arr.getKey());
ArrayList<InstallerVersion> al = new ArrayList<>();
for (int num : arr.getValue()) {
MinecraftForgeVersion v = root.number.get(num);
InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.mcversion));
for (String[] f : v.files) {
String ver = v.mcversion + "-" + v.version;
if (!StrUtils.isBlank(v.branch))
ver = ver + "-" + v.branch;
String filename = root.artifact + "-" + ver + "-" + f[1] + "." + f[0];
String url = DownloadType.getSuggestedDownloadType().getProvider().getParsedDownloadURL(root.webpath + ver + "/" + filename);
switch (f[1]) {
case "installer":
iv.installer = url;
break;
case "universal":
iv.universal = url;
break;
case "changelog":
iv.changelog = url;
break;
default:
break;
}
}
if (StrUtils.isBlank(iv.installer) || StrUtils.isBlank(iv.universal))
continue;
Collections.sort(al, new InstallerVersionNewerComparator());
al.add(iv);
versions.add(iv);
@Override
public Collection<Task> getDependTasks() {
return Arrays.asList(task);
}
versionMap.put(StrUtils.formatVersion(mcver), al);
}
@Override
public void executeTask() throws Throwable {
if (!areDependTasksSucceeded)
return;
String s = task.getResult();
Collections.sort(versions, new InstallerVersionComparator());
root = C.GSON.fromJson(s, MinecraftForgeVersionRoot.class);
versionMap = new HashMap<>();
versions = new ArrayList<>();
for (Map.Entry<String, int[]> arr : root.mcversion.entrySet()) {
String mcver = StrUtils.formatVersion(arr.getKey());
ArrayList<InstallerVersion> al = new ArrayList<>();
for (int num : arr.getValue()) {
MinecraftForgeVersion v = root.number.get(num);
InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.mcversion));
for (String[] f : v.files) {
String ver = v.mcversion + "-" + v.version;
if (!StrUtils.isBlank(v.branch))
ver = ver + "-" + v.branch;
String filename = root.artifact + "-" + ver + "-" + f[1] + "." + f[0];
String url = DownloadType.getSuggestedDownloadType().getProvider().getParsedDownloadURL(root.webpath + ver + "/" + filename);
switch (f[1]) {
case "installer":
iv.installer = url;
break;
case "universal":
iv.universal = url;
break;
case "changelog":
iv.changelog = url;
break;
default:
break;
}
}
if (StrUtils.isBlank(iv.installer) || StrUtils.isBlank(iv.universal))
continue;
Collections.sort(al, new InstallerVersionNewerComparator());
al.add(iv);
versions.add(iv);
}
versionMap.put(StrUtils.formatVersion(mcver), al);
}
Collections.sort(versions, new InstallerVersionComparator());
}
};
}
@Override
@@ -19,6 +19,7 @@ package org.jackhuang.hellominecraft.launcher.core.install.liteloader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -28,8 +29,10 @@ import org.jackhuang.hellominecraft.launcher.core.version.MinecraftLibrary;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList.InstallerVersion;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionNewerComparator;
import org.jackhuang.hellominecraft.util.NetUtils;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.tasks.TaskInfo;
import org.jackhuang.hellominecraft.util.tasks.download.HTTPGetTask;
/**
*
@@ -50,38 +53,52 @@ public class LiteLoaderVersionList extends InstallerVersionList {
public List<InstallerVersion> versions;
@Override
public void refreshList(String[] needed) throws Exception {
String s = NetUtils.get(C.URL_LITELOADER_LIST);
public Task refresh(String[] needed) {
if (root != null)
return;
return null;
return new TaskInfo(C.i18n("install.liteloader.get_list")) {
HTTPGetTask task = new HTTPGetTask(C.URL_LITELOADER_LIST);
root = C.GSON.fromJson(s, LiteLoaderVersionsRoot.class);
versionMap = new HashMap<>();
versions = new ArrayList<>();
for (Map.Entry<String, LiteLoaderMCVersions> arr : root.versions.entrySet()) {
ArrayList<InstallerVersion> al = new ArrayList<>();
LiteLoaderMCVersions mcv = arr.getValue();
if (mcv == null || mcv.artefacts == null || mcv.artefacts.get("com.mumfrey:liteloader") == null)
continue;
for (Map.Entry<String, LiteLoaderVersion> entry : mcv.artefacts.get("com.mumfrey:liteloader").entrySet()) {
if ("latest".equals(entry.getKey()))
continue;
LiteLoaderVersion v = entry.getValue();
LiteLoaderInstallerVersion iv = new LiteLoaderInstallerVersion(v.version, StrUtils.formatVersion(arr.getKey()));
iv.universal = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + arr.getKey() + "/" + v.file;
iv.tweakClass = v.tweakClass;
iv.libraries = Arrays.copyOf(v.libraries, v.libraries.length);
iv.installer = "http://dl.liteloader.com/redist/" + iv.mcVersion + "/liteloader-installer-" + iv.selfVersion.replace("_", "-") + ".jar";
al.add(iv);
versions.add(iv);
@Override
public Collection<Task> getDependTasks() {
return Arrays.asList(task);
}
Collections.sort(al, new InstallerVersionNewerComparator());
versionMap.put(StrUtils.formatVersion(arr.getKey()), al);
}
Collections.sort(versions, InstallerVersionComparator.INSTANCE);
@Override
public void executeTask() throws Throwable {
if (!areDependTasksSucceeded)
return;
String s = task.getResult();
root = C.GSON.fromJson(s, LiteLoaderVersionsRoot.class);
versionMap = new HashMap<>();
versions = new ArrayList<>();
for (Map.Entry<String, LiteLoaderMCVersions> arr : root.versions.entrySet()) {
ArrayList<InstallerVersion> al = new ArrayList<>();
LiteLoaderMCVersions mcv = arr.getValue();
if (mcv == null || mcv.artefacts == null || mcv.artefacts.get("com.mumfrey:liteloader") == null)
continue;
for (Map.Entry<String, LiteLoaderVersion> entry : mcv.artefacts.get("com.mumfrey:liteloader").entrySet()) {
if ("latest".equals(entry.getKey()))
continue;
LiteLoaderVersion v = entry.getValue();
LiteLoaderInstallerVersion iv = new LiteLoaderInstallerVersion(v.version, StrUtils.formatVersion(arr.getKey()));
iv.universal = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + arr.getKey() + "/" + v.file;
iv.tweakClass = v.tweakClass;
iv.libraries = Arrays.copyOf(v.libraries, v.libraries.length);
iv.installer = "http://dl.liteloader.com/redist/" + iv.mcVersion + "/liteloader-installer-" + iv.selfVersion.replace("_", "-") + ".jar";
al.add(iv);
versions.add(iv);
}
Collections.sort(al, new InstallerVersionNewerComparator());
versionMap.put(StrUtils.formatVersion(arr.getKey()), al);
}
Collections.sort(versions, InstallerVersionComparator.INSTANCE);
}
};
}
@Override
@@ -20,6 +20,8 @@ package org.jackhuang.hellominecraft.launcher.core.install.optifine.bmcl;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -30,8 +32,10 @@ import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.ArrayUtils;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList;
import org.jackhuang.hellominecraft.launcher.core.install.optifine.OptiFineVersion;
import org.jackhuang.hellominecraft.util.NetUtils;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.tasks.TaskInfo;
import org.jackhuang.hellominecraft.util.tasks.download.HTTPGetTask;
/**
*
@@ -55,34 +59,46 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
}.getType();
@Override
public void refreshList(String[] needed) throws Exception {
String s = NetUtils.get("http://bmclapi.bangbang93.com/optifine/versionlist");
public Task refresh(String[] needed) {
return new TaskInfo(C.i18n("install.optifine.get_list")) {
HTTPGetTask task = new HTTPGetTask("http://bmclapi.bangbang93.com/optifine/versionlist");
versionMap = new HashMap<>();
versions = new ArrayList<>();
if (s == null)
return;
root = C.GSON.fromJson(s, TYPE);
for (OptiFineVersion v : root) {
v.setMirror(v.getMirror().replace("http://optifine.net/http://optifine.net/", "http://optifine.net/"));
if (StrUtils.isBlank(v.getMCVersion())) {
Pattern p = Pattern.compile("OptiFine (.*) HD");
Matcher m = p.matcher(v.getVersion());
while (m.find())
v.setMCVersion(m.group(1));
@Override
public Collection<Task> getDependTasks() {
return Arrays.asList(task);
}
InstallerVersion iv = new InstallerVersion(v.getVersion(), StrUtils.formatVersion(v.getMCVersion()));
List<InstallerVersion> al = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.getMCVersion()));
//String url = "http://bmclapi.bangbang93.com/optifine/" + iv.selfVersion.replace(" ", "%20");
iv.installer = iv.universal = v.getMirror();
al.add(iv);
versions.add(iv);
}
@Override
public void executeTask() throws Throwable {
String s = task.getResult();
Collections.sort(versions, InstallerVersionComparator.INSTANCE);
versionMap = new HashMap<>();
versions = new ArrayList<>();
if (s == null)
return;
root = C.GSON.fromJson(s, TYPE);
for (OptiFineVersion v : root) {
v.setMirror(v.getMirror().replace("http://optifine.net/http://optifine.net/", "http://optifine.net/"));
if (StrUtils.isBlank(v.getMCVersion())) {
Pattern p = Pattern.compile("OptiFine (.*) HD");
Matcher m = p.matcher(v.getVersion());
while (m.find())
v.setMCVersion(m.group(1));
}
InstallerVersion iv = new InstallerVersion(v.getVersion(), StrUtils.formatVersion(v.getMCVersion()));
List<InstallerVersion> al = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.getMCVersion()));
//String url = "http://bmclapi.bangbang93.com/optifine/" + iv.selfVersion.replace(" ", "%20");
iv.installer = iv.universal = v.getMirror();
al.add(iv);
versions.add(iv);
}
Collections.sort(versions, InstallerVersionComparator.INSTANCE);
}
};
}
@Override
@@ -20,6 +20,8 @@ package org.jackhuang.hellominecraft.launcher.core.install.optifine.vanilla;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -32,8 +34,11 @@ import javax.xml.parsers.ParserConfigurationException;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList;
import org.jackhuang.hellominecraft.launcher.core.install.optifine.OptiFineVersion;
import org.jackhuang.hellominecraft.util.ArrayUtils;
import org.jackhuang.hellominecraft.util.NetUtils;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.tasks.TaskInfo;
import org.jackhuang.hellominecraft.util.tasks.download.HTTPGetTask;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -59,60 +64,74 @@ public class OptiFineVersionList extends InstallerVersionList {
public List<InstallerVersion> versions;
@Override
public void refreshList(String[] sss) throws Exception {
String content = NetUtils.get("http://optifine.net/downloads");
public Task refresh(String[] sss) {
if (versions != null)
return;
versionMap = new HashMap<>();
versions = new ArrayList<>();
return null;
return new TaskInfo(C.i18n("install.optifine.get_list")) {
HTTPGetTask task = new HTTPGetTask("http://optifine.net/downloads");
content = content.replace("&nbsp;", " ").replace("&gt;", ">").replace("&lt;", "<").replace("<br>", "<br />");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(content.getBytes("UTF-8")));
Element r = doc.getDocumentElement();
NodeList tables = r.getElementsByTagName("table");
for (int i = 0; i < tables.getLength(); i++) {
Element e = (Element) tables.item(i);
if ("downloadTable".equals(e.getAttribute("class"))) {
NodeList tr = e.getElementsByTagName("tr");
for (int k = 0; k < tr.getLength(); k++) {
NodeList downloadLine = ((Element) tr.item(k)).getElementsByTagName("td");
OptiFineVersion v = new OptiFineVersion();
for (int j = 0; j < downloadLine.getLength(); j++) {
Element td = (Element) downloadLine.item(j);
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineMirror"))
v.setMirror(((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"));
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDownload"))
v.setDownloadLink(((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"));
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDate"))
v.setDate(td.getTextContent());
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineFile"))
v.setVersion(td.getTextContent());
}
if (StrUtils.isBlank(v.getMCVersion())) {
Pattern p = Pattern.compile("OptiFine (.*?) ");
Matcher m = p.matcher(v.getVersion());
while (m.find())
v.setMCVersion(StrUtils.formatVersion(m.group(1)));
}
InstallerVersion iv = new InstallerVersion(v.getVersion(), StrUtils.formatVersion(v.getMCVersion()));
iv.installer = iv.universal = v.getMirror();
root.add(v);
versions.add(iv);
List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.getMCVersion()));
ivl.add(iv);
}
}
@Override
public Collection<Task> getDependTasks() {
return Arrays.asList(task);
}
} catch (ParserConfigurationException | SAXException | IOException | DOMException ex) {
throw new RuntimeException(ex);
}
Collections.sort(versions, InstallerVersionComparator.INSTANCE);
@Override
public void executeTask() throws Throwable {
if (!areDependTasksSucceeded)
return;
String content = task.getResult();
versionMap = new HashMap<>();
versions = new ArrayList<>();
content = content.replace("&nbsp;", " ").replace("&gt;", ">").replace("&lt;", "<").replace("<br>", "<br />");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(content.getBytes("UTF-8")));
Element r = doc.getDocumentElement();
NodeList tables = r.getElementsByTagName("table");
for (int i = 0; i < tables.getLength(); i++) {
Element e = (Element) tables.item(i);
if ("downloadTable".equals(e.getAttribute("class"))) {
NodeList tr = e.getElementsByTagName("tr");
for (int k = 0; k < tr.getLength(); k++) {
NodeList downloadLine = ((Element) tr.item(k)).getElementsByTagName("td");
OptiFineVersion v = new OptiFineVersion();
for (int j = 0; j < downloadLine.getLength(); j++) {
Element td = (Element) downloadLine.item(j);
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineMirror"))
v.setMirror(((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"));
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDownload"))
v.setDownloadLink(((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"));
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDate"))
v.setDate(td.getTextContent());
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineFile"))
v.setVersion(td.getTextContent());
}
if (StrUtils.isBlank(v.getMCVersion())) {
Pattern p = Pattern.compile("OptiFine (.*?) ");
Matcher m = p.matcher(v.getVersion());
while (m.find())
v.setMCVersion(StrUtils.formatVersion(m.group(1)));
}
InstallerVersion iv = new InstallerVersion(v.getVersion(), StrUtils.formatVersion(v.getMCVersion()));
iv.installer = iv.universal = v.getMirror();
root.add(v);
versions.add(iv);
List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.getMCVersion()));
ivl.add(iv);
}
}
}
} catch (ParserConfigurationException | SAXException | IOException | DOMException ex) {
throw new RuntimeException(ex);
}
Collections.sort(versions, InstallerVersionComparator.INSTANCE);
}
};
}
@Override
@@ -31,7 +31,7 @@ public class LibraryDownloadInfo extends GameDownloadInfo {
@Override
public String getUrl(DownloadType dt, boolean allowSelf) {
String myURL = (forgeURL == null ? dt.getProvider().getLibraryDownloadURL() : forgeURL) + "/";
String myURL = (forgeURL == null ? dt.getProvider().getLibraryDownloadURL() : forgeURL);
if (StrUtils.isNotBlank(url) && allowSelf)
myURL = url;
if (!myURL.endsWith(".jar"))
@@ -103,8 +103,10 @@ public final class GameSettingsPanel extends AnimatedPanel implements DropTarget
initExternalModsTable();
initTabs();
isLoading = true;
for (Java j : Java.JAVA)
cboJava.addItem(j.getLocalizedName());
isLoading = false;
Settings.profileLoadingEvent.register(onLoadingProfiles);
Settings.profileChangedEvent.register(onSelectedProfilesChanged);
@@ -25,9 +25,7 @@ import org.jackhuang.hellominecraft.launcher.setting.Settings;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerType;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList;
import org.jackhuang.hellominecraft.util.tasks.TaskRunnable;
import org.jackhuang.hellominecraft.util.tasks.TaskRunnableArg1;
import org.jackhuang.hellominecraft.util.tasks.TaskWindow;
import org.jackhuang.hellominecraft.util.tasks.communication.DefaultPreviousResult;
import org.jackhuang.hellominecraft.util.MessageBox;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.ui.SwingUtils;
@@ -123,9 +121,7 @@ public class InstallerPanel extends AnimatedPanel {
InstallerType id;
void refreshVersions() {
if (TaskWindow.factory().append(new TaskRunnableArg1<>(C.i18n("install." + id.id + ".get_list"), list)
.registerPreviousResult(new DefaultPreviousResult<>(new String[] { gsp.getMinecraftVersionFormatted() })))
.create())
if (TaskWindow.execute(list.refresh(new String[] { gsp.getMinecraftVersionFormatted() })))
loadVersions();
}
@@ -139,7 +135,8 @@ public class InstallerPanel extends AnimatedPanel {
MessageBox.Show(C.i18n("install.not_refreshed"));
return;
}
Settings.getLastProfile().service().install().download(Settings.getLastProfile().getSelectedVersion(), getVersion(idx), id).after(new TaskRunnable(this::refreshVersions)).run();
TaskWindow.execute(Settings.getLastProfile().service().install().download(Settings.getLastProfile().getSelectedVersion(), getVersion(idx), id),
new TaskRunnable(this::refreshVersions));
}
public void loadVersions() {
@@ -47,8 +47,8 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
{
put("MessageBox", "");
put("AWTError", "");
put("JFileChooser", "Has your operating system been installed completely or is a ghost system? ");
put("Jce", "Has your operating system been installed completely or is a ghost system? ");
put("JFileChooser", "Has your operating system been installed completely or is a ghost system?");
put("Jce", "Has your operating system been installed completely or is a ghost system?");
put("couldn't create component peer", "Fucking computer!");
put("sun.awt.shell.Win32ShellFolder2", "crash.user_fault");
put("UnsatisfiedLinkError", "crash.user_fault");
@@ -60,6 +60,7 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
put("java.lang.ClassFormatError", "crash.NoClassDefFound");
put("java.lang.OutOfMemoryError", "FUCKING MEMORY LIMIT!");
put("Trampoline", "ui.message.update_java");
put("NoSuchAlgorithmException", "Has your operating system been installed completely or is a ghost system?");
}
};
@@ -53,20 +53,16 @@ public class DefaultPlugin implements IPlugin {
OFFLINE_LOGIN.onLoadSettings(Settings.getInstance().getAuthenticatorConfig(OFFLINE_LOGIN.id()));
YGGDRASIL_LOGIN = new YggdrasilAuthenticator(clientToken);
YGGDRASIL_LOGIN.onLoadSettings(Settings.getInstance().getAuthenticatorConfig(YGGDRASIL_LOGIN.id()));
SKINME_LOGIN = new SkinmeAuthenticator(clientToken);
SKINME_LOGIN.onLoadSettings(Settings.getInstance().getAuthenticatorConfig(SKINME_LOGIN.id()));
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
Settings.getInstance().setAuthenticatorConfig(OFFLINE_LOGIN.id(), OFFLINE_LOGIN.onSaveSettings());
Settings.getInstance().setAuthenticatorConfig(YGGDRASIL_LOGIN.id(), YGGDRASIL_LOGIN.onSaveSettings());
Settings.getInstance().setAuthenticatorConfig(SKINME_LOGIN.id(), SKINME_LOGIN.onSaveSettings());
}
});
apply.accept(OFFLINE_LOGIN);
apply.accept(YGGDRASIL_LOGIN);
apply.accept(SKINME_LOGIN);
}
@Override
@@ -88,6 +88,8 @@ public class ZipEngine {
files = new File[1];
files[0] = source;
}
if (files == null)
return;
String pathName;//存相对路径(相对于待压缩的根目录)
for (File file : files)
if (file.isDirectory()) {
@@ -0,0 +1,44 @@
/*
* Hello Minecraft! Launcher.
* Copyright (C) 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 3 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. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.tasks;
import java.io.File;
/**
*
* @author huangyuhui
*/
public class DeleteFileTask extends Task {
File f;
public DeleteFileTask(File f) {
this.f = f;
}
@Override
public void executeTask() throws Throwable {
f.delete();
}
@Override
public String getInfo() {
return "Delete: " + f.getAbsolutePath();
}
}
@@ -17,28 +17,39 @@
*/
package org.jackhuang.hellominecraft.util.tasks;
import java.util.Arrays;
import java.util.Collection;
/**
*
* @author huangyuhui
*/
public class DoubleTask extends Task {
public class DoubleTask extends TaskInfo {
Task a, b;
public DoubleTask(Task a, Task b) {
this(a, b, "Double Task");
}
public DoubleTask(Task a, Task b, String info) {
super(info);
this.a = a;
this.b = b;
}
@Override
public void executeTask() throws Throwable {
a.executeTask();
b.executeTask();
public Collection<Task> getDependTasks() {
return Arrays.asList(a);
}
@Override
public String getInfo() {
return "Double Task";
public Collection<Task> getAfterTasks() {
return Arrays.asList(b);
}
@Override
public void executeTask() throws Throwable {
}
}
@@ -101,6 +101,8 @@ public class TaskList extends Thread {
AtomicBoolean bool = new AtomicBoolean(true);
CountDownLatch counter = new CountDownLatch(c.size());
for (Task t2 : c) {
if (t2 == null)
continue;
t2.setParallelExecuting(true);
Invoker thread = new Invoker(t2, counter, bool);
invokers.add(thread);
@@ -1,54 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 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 3 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. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.tasks;
import java.util.ArrayList;
import org.jackhuang.hellominecraft.util.tasks.communication.PreviousResult;
import org.jackhuang.hellominecraft.util.tasks.communication.PreviousResultRegistrar;
import org.jackhuang.hellominecraft.util.func.Consumer;
/**
*
* @author huangyuhui
* @param <T> Runnable&lt;T&gt;
*/
public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegistrar<T> {
private final Consumer<T> r;
public TaskRunnableArg1(String info, Consumer<T> r) {
super(info);
this.r = r;
}
@Override
public void executeTask() throws Exception {
if (al.size() != 1)
throw new IllegalStateException("the count of args is not one.");
r.accept(al.get(0).getResult());
}
ArrayList<PreviousResult<T>> al = new ArrayList();
@Override
public Task registerPreviousResult(PreviousResult<T> pr) {
al.add(pr);
return this;
}
}
@@ -216,8 +216,8 @@ public class TaskWindow extends javax.swing.JDialog
if (idx == -1)
return;
int pgs = progress * 100 / max;
if (progresses.contains(idx) && progresses.get(idx) != pgs && lstDownload.getRowCount() > idx) {
SwingUtils.setValueAt(lstDownload, pgs + "%", idx, 1);
if (progresses.size() > idx && progresses.get(idx) != pgs && lstDownload.getRowCount() > idx) {
SwingUtils.setValueAt(lstDownload, pgs < 0 ? "???" : pgs + "%", idx, 1);
progresses.set(idx, pgs);
}
});
@@ -242,7 +242,7 @@ public class TaskWindow extends javax.swing.JDialog
if (taskList == null)
return;
tasks.add(task);
progresses.add(0);
progresses.add(-1);
SwingUtils.appendLast(lstDownload, task.getInfo(), "0%");
SwingUtils.moveEnd(srlDownload);
});
@@ -130,6 +130,8 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
if (!shouldContinue)
break;
try {
if (ppl != null)
ppl.setProgress(this, -1, 1);
// Open connection to URL.
HttpURLConnection connection
@@ -57,15 +57,22 @@ public class HTTPGetTask extends TaskInfo implements PreviousResult<String> {
if (repeat > 0)
HMCLog.warn("Failed to download, repeat: " + repeat);
try {
if (ppl != null)
ppl.setProgress(this, -1, 1);
URLConnection conn = new URL(url).openConnection();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
int size = conn.getContentLength(), read = 0;
long lastTime = System.currentTimeMillis();
while ((i = is.read()) != -1) {
baos.write(i);
if (ppl != null)
ppl.setProgress(this, ++read, size);
++read;
long now = System.currentTimeMillis();
if (ppl != null && (now - lastTime) >= 1000) {
ppl.setProgress(this, read, size);
lastTime = now;
}
if (!shouldContinue)
return;
}
@@ -364,7 +364,7 @@ setupwindow.no_empty_name=名字不可为空
setupwindow.clean=清理游戏文件
update.no_browser=无法打开浏览器,网址已经复制到剪贴板了,您可以手动粘贴网址打开页面
update.should_open_link=是否前往发布页面更新?
update.should_open_link=是否更新?
update.newest_version=最新版本为:
update.failed=检查更新失败
update.found=(发现更新!)
@@ -364,7 +364,7 @@ setupwindow.no_empty_name=\u540d\u5b57\u4e0d\u53ef\u4e3a\u7a7a
setupwindow.clean=\u6e05\u7406\u6e38\u620f\u6587\u4ef6
update.no_browser=\u65e0\u6cd5\u6253\u5f00\u6d4f\u89c8\u5668\uff0c\u7f51\u5740\u5df2\u7ecf\u590d\u5236\u5230\u526a\u8d34\u677f\u4e86\uff0c\u60a8\u53ef\u4ee5\u624b\u52a8\u7c98\u8d34\u7f51\u5740\u6253\u5f00\u9875\u9762
update.should_open_link=\u662f\u5426\u524d\u5f80\u53d1\u5e03\u9875\u9762\u66f4\u65b0\uff1f
update.should_open_link=\u662f\u5426\u66f4\u65b0\uff1f
update.newest_version=\u6700\u65b0\u7248\u672c\u4e3a\uff1a
update.failed=\u68c0\u67e5\u66f4\u65b0\u5931\u8d25
update.found=(\u53d1\u73b0\u66f4\u65b0!)
@@ -364,7 +364,7 @@ setupwindow.no_empty_name=Version name cannot be empty.
setupwindow.clean=Clean game files
update.no_browser=Cannot open any browser. The link has been copied to the clipboard. You can paste it to the address bar.
update.should_open_link=Are you willing to open the update link?
update.should_open_link=Are you willing to upgrade this app?
update.newest_version=Newest version:
update.failed=Failed to check for updates.
update.found=(Found Update!)
@@ -364,7 +364,7 @@ setupwindow.no_empty_name=Version name cannot be empty.
setupwindow.clean=Clean game files
update.no_browser=Cannot open any browser. The link has been copied to the clipboard. You can paste it to the address bar.
update.should_open_link=Are you willing to open the update link?
update.should_open_link=Are you willing to upgrade this app?
update.newest_version=Newest version:
update.failed=Failed to check for updates.
update.found=(Found Update!)
@@ -364,7 +364,7 @@ setupwindow.no_empty_name=名字不可為空
setupwindow.clean=清理遊戲資料
update.no_browser=無法打開瀏覽器,網址已經復製到剪貼板了,您可以手動粘貼網址打開頁面
update.should_open_link=是否前往發布頁面更新?
update.should_open_link=是否更新?
update.newest_version=最新版本為:
update.failed=檢查更新失敗
update.found=(發現更新!)
@@ -364,7 +364,7 @@ setupwindow.no_empty_name=\u540d\u5b57\u4e0d\u53ef\u70ba\u7a7a
setupwindow.clean=\u6e05\u7406\u904a\u6232\u8cc7\u6599
update.no_browser=\u7121\u6cd5\u6253\u958b\u700f\u89bd\u5668\uff0c\u7db2\u5740\u5df2\u7d93\u5fa9\u88fd\u5230\u526a\u8cbc\u677f\u4e86\uff0c\u60a8\u53ef\u4ee5\u624b\u52d5\u7c98\u8cbc\u7db2\u5740\u6253\u958b\u9801\u9762
update.should_open_link=\u662f\u5426\u524d\u5f80\u767c\u5e03\u9801\u9762\u66f4\u65b0\uff1f
update.should_open_link=\u662f\u5426\u66f4\u65b0\uff1f
update.newest_version=\u6700\u65b0\u7248\u672c\u70ba\uff1a
update.failed=\u6aa2\u67e5\u66f4\u65b0\u5931\u6557
update.found=(\u767c\u73fe\u66f4\u65b0!)
@@ -242,9 +242,9 @@ public final class MainWindow extends javax.swing.JFrame
itm.addActionListener(new ActionListenerImpl("time set 0"));
ppmBasically.add(itm);
itm = new JMenuItem("广播");
itm.addActionListener(new ActionListenerImpl("say {}", JOptionPane.showInputDialog("广播讯息")));
itm.addActionListener(new ActionListenerImpl("say {}", "广播讯息"));
itm = new JMenuItem("红字广播");
itm.addActionListener(new ActionListenerImpl("me {}", JOptionPane.showInputDialog("广播讯息")));
itm.addActionListener(new ActionListenerImpl("me {}", "广播讯息"));
itm = new JMenuItem("私聊");
itm.addActionListener(e -> {
InputDialog id = new InputDialog(MainWindow.this, true, new String[] { "玩家", "讯息" });
@@ -253,16 +253,16 @@ public final class MainWindow extends javax.swing.JFrame
});
ppmBasically.add(itm);
itm = new JMenuItem("给予OP");
itm.addActionListener(new ActionListenerImpl("op {}", JOptionPane.showInputDialog("新OP的游戏名")));
itm.addActionListener(new ActionListenerImpl("op {}", "新OP的游戏名"));
ppmBasically.add(itm);
itm = new JMenuItem("卸除OP");
itm.addActionListener(new ActionListenerImpl("deop {}", JOptionPane.showInputDialog("要卸除OP的游戏名")));
itm.addActionListener(new ActionListenerImpl("deop {}", "要卸除OP的游戏名"));
ppmBasically.add(itm);
itm = new JMenuItem("给予玩家白名单");
itm.addActionListener(new ActionListenerImpl("whitelist add {}", JOptionPane.showInputDialog("要添入白名单的游戏名")));
itm.addActionListener(new ActionListenerImpl("whitelist add {}", "要添入白名单的游戏名"));
ppmBasically.add(itm);
itm = new JMenuItem("解除玩家白名单");
itm.addActionListener(new ActionListenerImpl("whitelist remove {}", JOptionPane.showInputDialog("要解除白名单的游戏名")));
itm.addActionListener(new ActionListenerImpl("whitelist remove {}", "要解除白名单的游戏名"));
ppmBasically.add(itm);
itm = new JMenuItem("启用白名单");
itm.addActionListener(new ActionListenerImpl("whitelist on"));
@@ -274,31 +274,31 @@ public final class MainWindow extends javax.swing.JFrame
itm.addActionListener(new ActionListenerImpl("whitelist list"));
ppmBasically.add(itm);
itm = new JMenuItem("封禁玩家");
itm.addActionListener(new ActionListenerImpl("ban {}", JOptionPane.showInputDialog("要封禁玩家的游戏名")));
itm.addActionListener(new ActionListenerImpl("ban {}", "要封禁玩家的游戏名"));
ppmBasically.add(itm);
itm = new JMenuItem("封禁玩家IP");
itm.addActionListener(new ActionListenerImpl("ban-ip {}", JOptionPane.showInputDialog("要封禁玩家IP的游戏名")));
itm.addActionListener(new ActionListenerImpl("ban-ip {}", "要封禁玩家IP的游戏名"));
itm = new JMenuItem("解封玩家");
itm.addActionListener(new ActionListenerImpl("pardon {}", JOptionPane.showInputDialog("要解封玩家的游戏名")));
itm.addActionListener(new ActionListenerImpl("pardon {}", "要解封玩家的游戏名"));
ppmBasically.add(itm);
itm = new JMenuItem("解封玩家IP");
itm.addActionListener(new ActionListenerImpl("pardon-ip {}", JOptionPane.showInputDialog("要解封玩家IP的游戏名")));
itm.addActionListener(new ActionListenerImpl("pardon-ip {}", "要解封玩家IP的游戏名"));
itm = new JMenuItem("封禁玩家");
itm.addActionListener(new ActionListenerImpl("ban {}", JOptionPane.showInputDialog("要封禁玩家的游戏名")));
itm.addActionListener(new ActionListenerImpl("ban {}", "要封禁玩家的游戏名"));
ppmBasically.add(itm);
itm = new JMenuItem("封禁玩家IP");
itm.addActionListener(new ActionListenerImpl("ban-ip {}", JOptionPane.showInputDialog("要封禁玩家IP的游戏名")));
itm.addActionListener(new ActionListenerImpl("ban-ip {}", "要封禁玩家IP的游戏名"));
itm = new JMenuItem("封禁玩家列表");
itm.addActionListener(new ActionListenerImpl("banlist"));
ppmBasically.add(itm);
itm = new JMenuItem("修改时间");
itm.addActionListener(new ActionListenerImpl("time set {}", JOptionPane.showInputDialog("要调整的时间值")));
itm.addActionListener(new ActionListenerImpl("time set {}", "要调整的时间值"));
ppmBasically.add(itm);
itm = new JMenuItem("往后调整时间");
itm.addActionListener(new ActionListenerImpl("time add {}", JOptionPane.showInputDialog("要往后调整的时间值")));
itm.addActionListener(new ActionListenerImpl("time add {}", "要往后调整的时间值"));
ppmBasically.add(itm);
itm = new JMenuItem("调整天气");
itm.addActionListener(new ActionListenerImpl("weather {}", JOptionPane.showInputDialog("要调整的天气(只能填:clear[意思是取消所有天气]或rain[意思是下雨]或thunder[意思是打雷]")));
itm.addActionListener(new ActionListenerImpl("weather {}", "要调整的天气(只能填:clear[意思是取消所有天气]或rain[意思是下雨]或thunder[意思是打雷]"));
ppmBasically.add(itm);
itm = new JMenuItem("调整一定时间的天气");
itm.addActionListener(e -> {
@@ -314,10 +314,10 @@ public final class MainWindow extends javax.swing.JFrame
});
ppmBasically.add(itm);
itm = new JMenuItem("清除背包");
itm.addActionListener(new ActionListenerImpl("clear {}", JOptionPane.showInputDialog("要被清除背包的玩家")));
itm.addActionListener(new ActionListenerImpl("clear {}", "要被清除背包的玩家"));
ppmBasically.add(itm);
itm = new JMenuItem("踢出玩家");
itm.addActionListener(new ActionListenerImpl("kick {}", JOptionPane.showInputDialog("要被踢出的玩家")));
itm.addActionListener(new ActionListenerImpl("kick {}", "要被踢出的玩家"));
ppmBasically.add(itm);
itm = new JMenuItem("在线玩家");
itm.addActionListener(new ActionListenerImpl("list"));
@@ -343,10 +343,10 @@ public final class MainWindow extends javax.swing.JFrame
itm.addActionListener(new ActionListenerImpl("save-off"));
ppmBasically.add(itm);
itm = new JMenuItem("难度");
itm.addActionListener(new ActionListenerImpl("difficulty {}", JOptionPane.showInputDialog("难度")));
itm.addActionListener(new ActionListenerImpl("difficulty {}", "难度"));
ppmBasically.add(itm);
itm = new JMenuItem("默认游戏模式");
itm.addActionListener(new ActionListenerImpl("defaultgamemode {}", JOptionPane.showInputDialog("默认游戏模式")));
itm.addActionListener(new ActionListenerImpl("defaultgamemode {}", "默认游戏模式"));
ppmBasically.add(itm);
itm = new JMenuItem("地图种子");
itm.addActionListener(new ActionListenerImpl("seed"));
@@ -22,9 +22,11 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.util.StringTokenizer;
import com.sun.management.OperatingSystemMXBean;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
/**
*
@@ -56,7 +58,7 @@ public class MonitorServiceImpl implements IMonitorService {
long freeMemory = Runtime.getRuntime().freeMemory() / kb;
// 最大可使用内存
long maxMemory = Runtime.getRuntime().maxMemory() / kb;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
// 操作系统
String osName = System.getProperty("os.name");
// 总的物理内存
@@ -72,8 +74,10 @@ public class MonitorServiceImpl implements IMonitorService {
double cpuRatio = 0;
if (osName.toLowerCase().startsWith("windows"))
cpuRatio = this.getCpuRatioForWindows();
else if (osName.toLowerCase().startsWith("mac"))
cpuRatio = this.getCpuRatioForMac();
else
cpuRatio = getCpuRateForLinux();
cpuRatio = this.getCpuRatioForLinux();
// 构造返回对象
MonitorInfoBean infoBean = new MonitorInfoBean();
infoBean.setFreeMemory(freeMemory);
@@ -88,56 +92,86 @@ public class MonitorServiceImpl implements IMonitorService {
return infoBean;
}
private static double getCpuRateForLinux() {
private static double getCpuRatioForLinux() {
float cpuUsage = 0;
Process pro1, pro2;
Runtime r = Runtime.getRuntime();
try {
String command = "cat /proc/stat";
long startTime = System.currentTimeMillis();
pro1 = r.exec(command);
BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream()));
String line = null;
long idleCpuTime1 = 0, totalCpuTime1 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
while ((line = in1.readLine()) != null)
if (line.startsWith("cpu")) {
line = line.trim();
String[] temp = line.split("\\s+");
idleCpuTime1 = Long.parseLong(temp[4]);
for (String s : temp)
if (!s.equals("cpu"))
totalCpuTime1 += Long.parseLong(s);
break;
}
in1.close();
pro1.destroy();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
HMCLog.err("Failed to catch sysout", e);
}
//第二次采集CPU时间
long endTime = System.currentTimeMillis();
pro2 = r.exec(command);
BufferedReader in2 = new BufferedReader(new InputStreamReader(pro2.getInputStream()));
long idleCpuTime2 = 0, totalCpuTime2 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
while ((line = in2.readLine()) != null)
if (line.startsWith("cpu")) {
line = line.trim();
String[] temp = line.split("\\s+");
idleCpuTime2 = Long.parseLong(temp[4]);
for (String s : temp)
if (!s.equals("cpu"))
totalCpuTime2 += Long.parseLong(s);
break;
}
if (idleCpuTime1 != 0 && totalCpuTime1 != 0 && idleCpuTime2 != 0 && totalCpuTime2 != 0)
cpuUsage = 1 - (float) (idleCpuTime2 - idleCpuTime1) / (float) (totalCpuTime2 - totalCpuTime1);
in2.close();
pro2.destroy();
} catch (IOException e) {
HMCLog.err("Failed to catch sysout", e);
}
return cpuUsage * 100;
}
private double getCpuRatioForMac() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat;
try {
Process process = Runtime.getRuntime().exec("top -b -n 1");
Process process = Runtime.getRuntime().exec("top -l 1");
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
if (linuxVersion == null || linuxVersion.equals("2.4")) {
brStat.readLine();
brStat.readLine();
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
String user = tokenStat.nextToken();
tokenStat.nextToken();
String system = tokenStat.nextToken();
tokenStat.nextToken();
String nice = tokenStat.nextToken();
System.out.println(user + " , " + system + " , " + nice);
user = user.substring(0, user.indexOf("%"));
system = system.substring(0, system.indexOf("%"));
nice = nice.substring(0, nice.indexOf("%"));
float userUsage = new Float(user);
float systemUsage = new Float(system);
float niceUsage = new Float(nice);
return (userUsage + systemUsage + niceUsage) / 100;
} else {
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuUsage = tokenStat.nextToken();
System.out.println("CPU idle : " + cpuUsage);
Float usage = new Float(cpuUsage.substring(0, cpuUsage.indexOf("%")));
return (1 - usage / 100);
}
brStat.readLine();
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
String user = tokenStat.nextToken();
tokenStat.nextToken();
String system = tokenStat.nextToken();
tokenStat.nextToken();
user = user.substring(0, user.indexOf("%"));
system = system.substring(0, system.indexOf("%"));
float userUsage = new Float(user);
float systemUsage = new Float(system);
return (userUsage + systemUsage) / 100;
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
freeResource(is, isr, brStat);
return 1;
} finally {
freeResource(is, isr, brStat);