Clean up again

This commit is contained in:
huangyuhui 2017-01-27 22:41:34 +08:00
parent 809d7378e2
commit 972c4758b1
120 changed files with 353 additions and 1725 deletions

View File

@ -27,13 +27,6 @@ public class PluginManager {
private static IPlugin NOW_PLUGIN;
public static void getServerPlugin() {
try {
getPlugin(Thread.currentThread().getContextClassLoader().loadClass("org.jackhuang.hellominecraft.launcher.server.ServerPlugin"));
} catch (ClassNotFoundException ignore) {
}
}
public static void getPlugin(Class<?> cls) {
try {
IPlugin p = (IPlugin) cls.newInstance();

View File

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

View File

@ -26,11 +26,6 @@ public class AssetsObject {
private String hash;
private long size;
public AssetsObject(String hash, long size) {
this.hash = hash;
this.size = size;
}
public void setHash(String hash) {
this.hash = hash;
}

View File

@ -28,15 +28,6 @@ public class Contents {
public Contents() {
}
public Contents(String key, String eTag, String lastModified, String storageClass, long size) {
this();
this.key = key;
this.eTag = eTag;
this.lastModified = lastModified;
this.storageClass = storageClass;
this.size = size;
}
public String getKey() {
return key;
}

View File

@ -31,6 +31,7 @@ import org.jackhuang.hellominecraft.launcher.core.version.MinecraftVersion;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.tasks.download.FileDownloadTask;
import org.jackhuang.hellominecraft.util.code.DigestUtils;
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.system.IOUtils;
import org.jackhuang.hellominecraft.util.tasks.TaskInfo;
@ -113,8 +114,8 @@ public abstract class IAssetsHandler {
boolean need = true;
try {
if (location.exists()) {
FileInputStream fis = new FileInputStream(location);
String sha = DigestUtils.sha1Hex(IOUtils.readFully(fis).toByteArray());
FileInputStream fis = FileUtils.openInputStream(location);
String sha = DigestUtils.sha1Hex(IOUtils.toByteArray(fis));
IOUtils.closeQuietly(fis);
if (contents.get(i).geteTag().equals(sha)) {
++hasDownloaded;

View File

@ -57,7 +57,7 @@ public class MinecraftAssetService extends IMinecraftAssetService {
public Task downloadAssets(final MinecraftVersion mv) throws GameException {
if (mv == null)
return null;
return IAssetsHandler.ASSETS_HANDLER.getList(mv.resolve(service.version()), service.asset()).after(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(service.getDownloadType().getProvider()));
return IAssetsHandler.ASSETS_HANDLER.getList(mv.resolve(service.version()), service.asset()).with(IAssetsHandler.ASSETS_HANDLER.getDownloadTask(service.getDownloadType().getProvider()));
}
@Override
@ -155,7 +155,7 @@ public class MinecraftAssetService extends IMinecraftAssetService {
if (index == null)
return false;
for (Map.Entry entry : index.getFileMap().entrySet())
for (Map.Entry<String, AssetsObject> entry : index.getFileMap().entrySet())
if (!new File(getAssets(), "objects/" + ((AssetsObject) entry.getValue()).getHash().substring(0, 2) + "/" + ((AssetsObject) entry.getValue()).getHash()).exists())
return false;
return true;
@ -185,7 +185,7 @@ public class MinecraftAssetService extends IMinecraftAssetService {
int cnt = 0;
HMCLog.log("Reconstructing virtual assets folder at " + virtualRoot);
int tot = index.getFileMap().entrySet().size();
for (Map.Entry entry : index.getFileMap().entrySet()) {
for (Map.Entry<String, AssetsObject> entry : index.getFileMap().entrySet()) {
File target = new File(virtualRoot, (String) entry.getKey());
File original = new File(assetsDir, "objects/" + ((AssetsObject) entry.getValue()).getHash().substring(0, 2) + "/" + ((AssetsObject) entry.getValue()).getHash());
if (original.exists()) {

View File

@ -87,13 +87,13 @@ public abstract class IAuthenticator {
public abstract void logOut();
public Map onSaveSettings() {
public Map<?, ?> onSaveSettings() {
HashMap<String, String> m = new HashMap<>();
m.put("IAuthenticator_UserName", username);
return m;
}
public void onLoadSettings(Map m) {
public void onLoadSettings(Map<?, ?> m) {
if (m == null)
return;
Object o = m.get("IAuthenticator_UserName");

View File

@ -29,7 +29,7 @@ import org.jackhuang.hellominecraft.util.code.DigestUtils;
*/
public final class OfflineAuthenticator extends IAuthenticator {
Map<String, String> uuidMap = new HashMap<>();
Map uuidMap = new HashMap<>();
public OfflineAuthenticator(String clientToken) {
super(clientToken);
@ -42,7 +42,7 @@ public final class OfflineAuthenticator extends IAuthenticator {
return;
Object o = m.get("uuidMap");
if (o != null && o instanceof Map)
uuidMap = (Map<String, String>) o;
uuidMap = (Map<?, ?>) o;
}
@Override
@ -57,8 +57,8 @@ public final class OfflineAuthenticator extends IAuthenticator {
if (StrUtils.isBlank(info.username))
throw new AuthenticationException(C.i18n("login.no_Player007"));
String uuid = getUUIDFromUserName(info.username);
if (uuidMap != null && uuidMap.containsKey(uuid))
uuid = uuidMap.get(info.username);
if (uuidMap != null && uuidMap.containsKey(info.username) && uuidMap.get(info.username) instanceof String)
uuid = (String) uuidMap.get(info.username);
else {
if (uuidMap == null)
uuidMap = new HashMap<>();
@ -69,7 +69,8 @@ public final class OfflineAuthenticator extends IAuthenticator {
.setSession(uuid)
.setUserId(uuid)
.setAccessToken(uuid)
.setUserType("Legacy");
.setUserType("Legacy")
.setClientIdentifier(clientToken);
}
public static String getUUIDFromUserName(String str) {

View File

@ -86,7 +86,8 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.LegacySerializer()).create().toJson(ua.getUserProperties()))
.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()))
.setAccessToken(ua.getAuthenticatedToken())
.setSession(ua.getAuthenticatedToken());
.setSession(ua.getAuthenticatedToken())
.setClientIdentifier(clientToken);
}
@Override

View File

@ -25,11 +25,6 @@ public class User {
public User() {
}
public User(String id, PropertyMap properties) {
this.id = id;
this.properties = properties;
}
public String getId() {
return id;
}

View File

@ -17,12 +17,18 @@
*/
package org.jackhuang.hellominecraft.launcher.core.download;
import com.google.gson.annotations.SerializedName;
/**
*
* @author huangyuhui
*/
public class MinecraftRemoteLatestVersion {
public String snapshot, release;
@SerializedName("snapshot")
public String snapshot;
@SerializedName("release")
public String release;
}

View File

@ -17,13 +17,23 @@
*/
package org.jackhuang.hellominecraft.launcher.core.download;
import com.google.gson.annotations.SerializedName;
/**
*
* @author huangyuhui
*/
public class MinecraftRemoteVersion {
public String id, time, releaseTime, type;
@SerializedName("id")
public String id;
@SerializedName("time")
public String time;
@SerializedName("releaseTime")
public String releaseTime;
@SerializedName("type")
public String type;
@SerializedName("url")
private String url;
public String getUrl(DownloadType type) {

View File

@ -19,9 +19,12 @@ package org.jackhuang.hellominecraft.launcher.core.install;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.tasks.Task;
/**
@ -29,6 +32,9 @@ import org.jackhuang.hellominecraft.util.tasks.Task;
* @author huangyuhui
*/
public abstract class InstallerVersionList {
public Map<String, List<InstallerVersion>> versionMap;
public List<InstallerVersion> versions;
/**
* Refresh installer versions list from the downloaded content.
@ -53,7 +59,17 @@ public abstract class InstallerVersionList {
*
* @return cached result.
*/
protected abstract List<InstallerVersion> getVersionsImpl(String mcVersion);
public List<InstallerVersion> getVersionsImpl(String mcVersion) {
if (versions == null || versionMap == null)
return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List<InstallerVersion> c = versionMap.get(mcVersion);
if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c;
}
/**
* Get installers you want, please cache this method's result to save time.

View File

@ -62,8 +62,8 @@ public final class MinecraftInstallerService extends IMinecraftInstallerService
return null;
else
return new FileDownloadTask(service.getDownloadType().getProvider().getParsedDownloadURL(v.installer), filepath).setTag("forge")
.after(new ForgeInstaller(service, filepath))
.after(new DeleteFileTask(filepath));
.with(new ForgeInstaller(service, filepath))
.with(new DeleteFileTask(filepath));
}
@Override
@ -72,9 +72,9 @@ public final class MinecraftInstallerService extends IMinecraftInstallerService
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));
return task.with(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.with(new OptiFineInstaller(service, installId, v, filepath))
.with(new DeleteFileTask(filepath));
}
@Override
@ -83,7 +83,7 @@ public final class MinecraftInstallerService extends IMinecraftInstallerService
throw new Error("Download lite loader but the version is not ll's.");
File filepath = IOUtils.tryGetCanonicalFile("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));
return task.with(new LiteLoaderInstaller(service, installId, (LiteLoaderVersionList.LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.with(new DeleteFileTask(filepath));
}
}

View File

@ -1,50 +0,0 @@
/*
* 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.launcher.core.install;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.system.CompressingUtils;
import org.jackhuang.hellominecraft.util.system.FileUtils;
/**
*
* @author huangyuhui
*/
public class PackMinecraftInstaller {
File dest;
ArrayList<String> src;
public PackMinecraftInstaller(ArrayList<String> src, File dest) {
this.dest = dest;
this.src = src;
}
public void install() throws IOException {
File file = new File("HMCL-MERGE-TEMP");
if (!file.exists() && !file.mkdirs())
HMCLog.warn("Failed to make directories: " + file);
for (String src1 : src)
CompressingUtils.unzip(new File(src1), file);
CompressingUtils.zip(file.getAbsolutePath(), dest.getAbsolutePath());
FileUtils.deleteDirectory(file);
}
}

View File

@ -81,7 +81,7 @@ public class ForgeInstaller extends Task {
File file = new File(gameDir, "libraries/" + forge.getDownloadInfo().path);
if (file.getParentFile().mkdirs())
HMCLog.warn("Failed to make library directory " + file.getParent());
try (FileOutputStream fos = new FileOutputStream(file)) {
try (FileOutputStream fos = FileUtils.openOutputStream(file)) {
IOUtils.copyStream(is, fos);
}
mp.version().refreshVersions();

View File

@ -1,38 +0,0 @@
/*
* 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.launcher.core.install.forge;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.jackhuang.hellominecraft.launcher.core.install.PackMinecraftInstaller;
/**
*
* @author huangyuhui
*/
public class ForgeOldInstaller {
public static void install(String destMinecraftJar, String srcMinecraftJar, String forgeUniversal) throws IOException {
ArrayList<String> al = new ArrayList<>();
al.add(srcMinecraftJar);
al.add(forgeUniversal);
new PackMinecraftInstaller(al, new File(destMinecraftJar)).install();
}
}

View File

@ -47,19 +47,6 @@ public class Install {
public Install() {
}
public Install(String profileName, String target, String path, String version, String filePath, String welcome, String minecraft, String mirrorList, String logo) {
this();
this.profileName = profileName;
this.target = target;
this.path = path;
this.version = version;
this.filePath = filePath;
this.welcome = welcome;
this.minecraft = minecraft;
this.mirrorList = mirrorList;
this.logo = logo;
}
public String getProfileName() {
return profileName;
}

View File

@ -76,16 +76,4 @@ public class MinecraftForgeVersion {
this.modified = modified;
}
public MinecraftForgeVersion() {
}
public MinecraftForgeVersion(String branch, String mcversion, String jobver, String version, int build, double modified) {
this.branch = branch;
this.mcversion = mcversion;
this.jobver = jobver;
this.version = version;
this.build = build;
this.modified = modified;
}
}

View File

@ -22,7 +22,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.launcher.core.download.DownloadType;
@ -48,8 +47,6 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
}
public MinecraftForgeVersionRoot root;
public Map<String, List<InstallerVersion>> versionMap;
public List<InstallerVersion> versions;
@Override
public Task refresh(String[] needed) {
@ -116,19 +113,6 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
};
}
@Override
public List<InstallerVersion> getVersionsImpl(String mcVersion) {
if (versions == null || versionMap == null)
return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion);
if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c;
}
@Override
public String getName() {
return "Forge - MinecraftForge Offical Site";

View File

@ -63,7 +63,7 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrar
MinecraftVersion mv = (MinecraftVersion) service.version().getVersionById(installId).clone();
mv.inheritsFrom = mv.id;
mv.jar = mv.jar == null ? mv.id : mv.jar;
mv.libraries = new ArrayList(Arrays.asList(version.libraries));
mv.libraries = new ArrayList<>(Arrays.asList(version.libraries));
MinecraftLibrary ml = new MinecraftLibrary("com.mumfrey:liteloader:" + version.selfVersion);
//ml.url = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + version.mcVersion + "/liteloader-" + version.selfVersion + ".jar";
@ -92,7 +92,7 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrar
ArrayList<PreviousResult<File>> pre = new ArrayList<>();
@Override
public Task registerPreviousResult(PreviousResult pr) {
public Task registerPreviousResult(PreviousResult<File> pr) {
pre.add(pr);
return this;
}

View File

@ -22,13 +22,11 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jackhuang.hellominecraft.util.C;
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.StrUtils;
import org.jackhuang.hellominecraft.util.tasks.Task;
@ -50,8 +48,6 @@ public class LiteLoaderVersionList extends InstallerVersionList {
}
public LiteLoaderVersionsRoot root;
public Map<String, List<InstallerVersion>> versionMap;
public List<InstallerVersion> versions;
@Override
public Task refresh(String[] needed) {
@ -102,19 +98,6 @@ public class LiteLoaderVersionList extends InstallerVersionList {
};
}
@Override
public List<InstallerVersion> getVersionsImpl(String mcVersion) {
if (versions == null || versionMap == null)
return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion);
if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c;
}
@Override
public String getName() {
return "LiteLoader - LiteLoader Official Site(By: Mumfrey)";

View File

@ -35,13 +35,6 @@ public class LiteLoaderVersionsMeta {
public LiteLoaderVersionsMeta() {
}
public LiteLoaderVersionsMeta(String description, String authors, String url) {
this();
this.description = description;
this.authors = authors;
this.url = url;
}
public String getDescription() {
return description;
}

View File

@ -42,10 +42,6 @@ public class OptiFineInstaller extends Task implements PreviousResultRegistrar<F
public InstallerVersionList.InstallerVersion version;
public String installId;
public OptiFineInstaller(IMinecraftService service, String installId, InstallerVersionList.InstallerVersion version) {
this(service, installId, version, null);
}
public OptiFineInstaller(IMinecraftService service, String installId, InstallerVersionList.InstallerVersion version, File installer) {
this.service = service;
this.installId = installId;
@ -90,10 +86,10 @@ public class OptiFineInstaller extends Task implements PreviousResultRegistrar<F
return "OptiFine Installer";
}
ArrayList<PreviousResult<File>> pre = new ArrayList();
ArrayList<PreviousResult<File>> pre = new ArrayList<>();
@Override
public Task registerPreviousResult(PreviousResult pr) {
public Task registerPreviousResult(PreviousResult<File> pr) {
pre.add(pr);
return this;
}

View File

@ -25,7 +25,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jackhuang.hellominecraft.util.C;
@ -52,8 +51,6 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
}
public ArrayList<OptiFineVersion> root;
public Map<String, List<InstallerVersion>> versionMap;
public List<InstallerVersion> versions;
private static final Type TYPE = new TypeToken<ArrayList<OptiFineVersion>>() {
}.getType();
@ -101,19 +98,6 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
};
}
@Override
public List<InstallerVersion> getVersionsImpl(String mcVersion) {
if (versions == null || versionMap == null)
return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion);
if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c;
}
@Override
public String getName() {
return "OptiFine - BMCLAPI(By: bangbang93)";

View File

@ -25,7 +25,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
@ -59,9 +58,7 @@ public class OptiFineVersionList extends InstallerVersionList {
return instance;
}
public ArrayList<OptiFineVersion> root = new ArrayList();
public Map<String, List<InstallerVersion>> versionMap;
public List<InstallerVersion> versions;
public ArrayList<OptiFineVersion> root = new ArrayList<>();
@Override
public Task refresh(String[] sss) {
@ -138,18 +135,4 @@ public class OptiFineVersionList extends InstallerVersionList {
public String getName() {
return "OptiFine - OptiFine Official Site";
}
@Override
public List<InstallerVersion> getVersionsImpl(String mcVersion) {
if (versions == null || versionMap == null)
return null;
if (StrUtils.isBlank(mcVersion))
return versions;
List c = versionMap.get(mcVersion);
if (c == null)
return versions;
Collections.sort(c, InstallerVersionComparator.INSTANCE);
return c;
}
}

View File

@ -22,8 +22,6 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import org.jackhuang.hellominecraft.launcher.api.PluginManager;
import org.jackhuang.hellominecraft.launcher.core.GameException;
@ -38,6 +36,7 @@ import org.jackhuang.hellominecraft.launcher.core.version.DecompressLibraryJob;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.EventHandler;
import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.code.Charsets;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.system.IOUtils;
@ -153,7 +152,7 @@ public class GameLauncher {
*
* @throws java.io.IOException write contents failed.
*/
public File makeLauncher(String launcherName, List str) throws IOException {
public File makeLauncher(String launcherName, List<String> str) throws IOException {
HMCLog.log("Making shell launcher...");
service.version().onLaunch(options.getLaunchVersion());
boolean isWin = OS.os() == OS.WINDOWS;
@ -161,13 +160,8 @@ public class GameLauncher {
if (!f.exists() && !f.createNewFile())
HMCLog.warn("Failed to create " + f);
BufferedWriter writer;
try (FileOutputStream fos = new FileOutputStream(f)) {
try {
writer = new BufferedWriter(new OutputStreamWriter(fos, System.getProperty("sun.jnu.encoding", "UTF-8")));
} catch (UnsupportedEncodingException ex) {
HMCLog.warn("Failed to create writer, will try again.", ex);
writer = new BufferedWriter(new OutputStreamWriter(fos, Charset.defaultCharset()));
}
try (FileOutputStream fos = FileUtils.openOutputStream(f)) {
writer = new BufferedWriter(new OutputStreamWriter(fos, Charsets.toCharset()));
if (isWin) {
writer.write("@echo off");
writer.newLine();

View File

@ -18,7 +18,6 @@
package org.jackhuang.hellominecraft.launcher.core.mod;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@ -28,7 +27,6 @@ import java.util.Map;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftModService;
import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftService;
import org.jackhuang.hellominecraft.util.code.DigestUtils;
import org.jackhuang.hellominecraft.util.system.FileUtils;
/**
@ -113,11 +111,4 @@ public class MinecraftModService extends IMinecraftModService {
return flag;
}
public String[] checkMd5s(String id) throws IOException {
String[] res = new String[getMods(id).size()];
for (int i = 0; i < res.length; i++)
res[i] = DigestUtils.md5Hex(new FileInputStream(getMods(id).get(i).location));
return res;
}
}

View File

@ -93,15 +93,15 @@ public final class ModpackManager {
// Read modpack name and description from `modpack.json`
try (ZipFile zip = new ZipFile(input)) {
HashMap map = C.GSON.fromJson(new InputStreamReader(zip.getInputStream(zip.getEntry("modpack.json")), "UTF-8"), HashMap.class);
HashMap<String, String> map = C.GSON.fromJson(new InputStreamReader(zip.getInputStream(zip.getEntry("modpack.json")), "UTF-8"), HashMap.class);
if (map != null) {
if (id == null)
if (map.containsKey("name") && map.get("name") instanceof String)
id = (String) map.get("name");
id = map.get("name");
if (id != null)
description += id;
if (map.containsKey("description") && map.get("description") instanceof String)
description += "\n" + (String) map.get("description");
description += "\n" + map.get("description");
}
if (id == null)
throw new IllegalStateException("Illegal modpack id!");
@ -245,7 +245,7 @@ public final class ModpackManager {
*
* @throws IOException if create tmp directory failed
*/
public static void export(File output, IMinecraftProvider provider, String version, List<String> blacklist, Map modpackJson, CallbackIO<ZipEngine> callback) throws IOException, GameException {
public static void export(File output, IMinecraftProvider provider, String version, List<String> blacklist, Map<String, String> modpackPreferences, CallbackIO<ZipEngine> callback) throws IOException, GameException {
final ArrayList<String> b = new ArrayList<>(MODPACK_BLACK_LIST);
if (blacklist != null)
b.addAll(blacklist);
@ -272,7 +272,7 @@ public final class ModpackManager {
mv.jar = r.version;
mv.runDir = "version";
zip.putTextFile(C.GSON.toJson(mv), "minecraft/pack.json");
zip.putTextFile(C.GSON.toJson(modpackJson), "modpack.json");
zip.putTextFile(C.GSON.toJson(modpackPreferences), "modpack.json");
if (callback != null)
callback.call(zip);
} finally {

View File

@ -36,7 +36,6 @@ public class Extract implements Cloneable {
}
@Override
@SuppressWarnings("CloneDeclaresCloneNotSupported")
public Object clone() {
try {
return super.clone();

View File

@ -56,7 +56,6 @@ public abstract class IMinecraftLibrary implements Cloneable {
}
@Override
@SuppressWarnings("CloneDeclaresCloneNotSupported")
public Object clone() {
try {
return super.clone();

View File

@ -46,14 +46,6 @@ public class MinecraftLibrary extends IMinecraftLibrary {
super(name);
}
public MinecraftLibrary(ArrayList<Rules> rules, String url, Natives natives, String name, Extract extract, LibraryDownloadInfo downloads) {
super(name);
this.rules = rules == null ? null : (ArrayList<Rules>) rules.clone();
this.url = url;
this.natives = natives == null ? null : (Natives) natives.clone();
this.extract = extract == null ? null : (Extract) extract.clone();
}
/**
* is the library allowed to load.
*

View File

@ -31,7 +31,6 @@ import org.jackhuang.hellominecraft.launcher.core.GameException;
import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftProvider;
import org.jackhuang.hellominecraft.launcher.core.asset.AssetsIndex;
import org.jackhuang.hellominecraft.util.ArrayUtils;
import org.jackhuang.hellominecraft.util.Utils;
/**
*
@ -213,6 +212,6 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
}
public Set<IMinecraftLibrary> getLibraries() {
return libraries == null ? new HashSet() : new HashSet(libraries);
return libraries == null ? new HashSet<>() : new HashSet<>(libraries);
}
}

View File

@ -45,7 +45,7 @@ import org.jackhuang.hellominecraft.util.ui.SwingUtils;
*/
public class MinecraftVersionManager extends IMinecraftProvider {
final Map<String, MinecraftVersion> versions = new TreeMap();
final Map<String, MinecraftVersion> versions = new TreeMap<>();
/**
*

View File

@ -33,7 +33,6 @@ public class Natives implements Cloneable {
public String linux;
@Override
@SuppressWarnings("CloneDeclaresCloneNotSupported")
protected Object clone() {
try {
return super.clone();

View File

@ -33,12 +33,6 @@ public class Rules {
public Rules() {
}
public Rules(String action, OSRestriction os) {
this();
this.action = action;
this.os = os;
}
public String action() {
return os == null || os.isCurrentOS() ? action : null;
}

View File

@ -98,7 +98,6 @@ public final class Main implements Runnable {
return "HMCL" + ' ' + LAUNCHER_VERSION;
}
public static final Main INSTANCE = new Main();
private static HelloMinecraftLookAndFeel LOOK_AND_FEEL;
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());

View File

@ -126,18 +126,10 @@ public final class Settings {
return SETTINGS.getConfigurations();
}
public static void setProfile(Profile ver) {
getProfiles().put(ver.getName(), ver);
}
public static Collection<Profile> getProfilesFiltered() {
return CollectionUtils.filter(getProfiles().values(), t -> t != null && t.getName() != null);
}
public static Profile getOneProfile() {
return SETTINGS.getConfigurations().firstEntry().getValue();
}
public static boolean putProfile(Profile ver) {
if (ver == null || ver.getName() == null || getProfiles().containsKey(ver.getName()))
return false;
@ -163,8 +155,8 @@ public final class Settings {
return flag;
}
public static final EventHandler<Profile> profileChangedEvent = new EventHandler(null);
public static final EventHandler<Void> profileLoadingEvent = new EventHandler(null);
public static final EventHandler<Profile> profileChangedEvent = new EventHandler<>(null);
public static final EventHandler<Void> profileLoadingEvent = new EventHandler<>(null);
static void onProfileChanged() {
Profile p = getLastProfile();

View File

@ -93,27 +93,6 @@ public class VersionSetting {
javaDir = java = minecraftArgs = serverIp = precalledCommand = wrapper = "";
}
public VersionSetting(VersionSetting v) {
this();
if (v == null)
return;
maxMemory = v.maxMemory;
width = v.width;
height = v.height;
java = v.java;
fullscreen = v.fullscreen;
javaArgs = v.javaArgs;
javaDir = v.javaDir;
minecraftArgs = v.minecraftArgs;
permSize = v.permSize;
gameDirType = v.gameDirType;
noJVMArgs = v.noJVMArgs;
launcherVisibility = v.launcherVisibility;
precalledCommand = v.precalledCommand;
wrapper = v.wrapper;
serverIp = v.serverIp;
}
public String getJavaDir() {
Java j = getJava();
if (j.getHome() == null)
@ -173,10 +152,6 @@ public class VersionSetting {
propertyChanged.execute("javaArgs");
}
public boolean hasJavaArgs() {
return StrUtils.isNotBlank(getJavaArgs().trim());
}
public String getMaxMemory() {
if (StrUtils.isBlank(maxMemory))
return String.valueOf(OS.getSuggestedMemorySize());

View File

@ -1410,7 +1410,7 @@ public final class GameSettingsPanel extends RepaintPage implements DropTargetLi
private void loadProfiles() {
isLoading = true;
DefaultComboBoxModel model = new DefaultComboBoxModel();
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
for (Profile s : Settings.getProfilesFiltered())
model.addElement(s.getName());
cboProfiles.setModel(model);
@ -1423,7 +1423,7 @@ public final class GameSettingsPanel extends RepaintPage implements DropTargetLi
};
void loadVersions() {
DefaultComboBoxModel model = new DefaultComboBoxModel();
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
for (MinecraftVersion each : Settings.getLastProfile().service().version().getVersions()) {
if (each.hidden)
continue;
@ -1438,7 +1438,7 @@ public final class GameSettingsPanel extends RepaintPage implements DropTargetLi
public void versionChanged(String version) {
isLoading = true;
DefaultComboBoxModel model = (DefaultComboBoxModel) cboVersions.getModel();
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) cboVersions.getModel();
for (int i = 0; i < model.getSize(); ++i)
if (model.getElementAt(i).equals(version)) {
model.setSelectedItem(version);
@ -1462,7 +1462,7 @@ public final class GameSettingsPanel extends RepaintPage implements DropTargetLi
txtGameDir.setText(t.getGameDir());
isLoading = true;
DefaultComboBoxModel model = (DefaultComboBoxModel) cboProfiles.getModel();
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) cboProfiles.getModel();
for (int i = 0; i < model.getSize(); ++i)
if (model.getElementAt(i).equals(t.getName())) {
model.setSelectedItem(t.getName());

View File

@ -68,10 +68,6 @@ public class HeaderTab extends JLabel
return this.model.getActionListeners();
}
public void removeActionListener(ActionListener listener) {
this.model.removeActionListener(listener);
}
public void setActionCommand(String command) {
this.model.setActionCommand(command);
}

View File

@ -124,7 +124,7 @@ public class InstallerPanel extends Page {
Task refreshVersionsTask() {
Task t = list.refresh(new String[] { gsp.getMinecraftVersionFormatted() });
if (t != null)
return t.after(new TaskRunnable(this::loadVersions));
return t.with(new TaskRunnable(this::loadVersions));
else
return null;
}

View File

@ -49,12 +49,12 @@ public class LauncherSettingsPanel extends RepaintPage {
setBackground(GraphicsUtils.getWebColorWithAlpha("FFFFFF7F"));
setOpaque(true);
DefaultComboBoxModel d = new DefaultComboBoxModel();
DefaultComboBoxModel<String> d = new DefaultComboBoxModel<>();
for (DownloadType type : DownloadType.values())
d.addElement(type.getName());
cboDownloadSource.setModel(d);
d = new DefaultComboBoxModel();
d = new DefaultComboBoxModel<>();
int id = 0;
for (SupportedLocales type : SupportedLocales.values()) {
d.addElement(type.showString());

View File

@ -38,7 +38,7 @@ import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftService;
import org.jackhuang.hellominecraft.launcher.ui.modpack.ModpackWizard;
import org.jackhuang.hellominecraft.launcher.util.HMCLMinecraftService;
import org.jackhuang.hellominecraft.util.Event;
import org.jackhuang.hellominecraft.lookandfeel.comp.ConstomButton;
import org.jackhuang.hellominecraft.lookandfeel.ConstomButton;
import org.jackhuang.hellominecraft.util.func.Consumer;
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.tasks.TaskWindow;
@ -473,7 +473,7 @@ public class MainPagePanel extends GaussionPage {
final Runnable onLoadingProfiles = () -> {
isLoading = true;
DefaultComboBoxModel model = new DefaultComboBoxModel();
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
for (Profile s : Settings.getProfilesFiltered())
model.addElement(s.getName());
cboProfiles.setModel(model);
@ -516,7 +516,7 @@ public class MainPagePanel extends GaussionPage {
void versionChanged(String selectedVersion) {
isLoading = true;
DefaultComboBoxModel model = (DefaultComboBoxModel) cboVersions.getModel();
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) cboVersions.getModel();
for (int i = 0; i < model.getSize(); ++i)
if (model.getElementAt(i).equals(selectedVersion)) {
model.setSelectedItem(selectedVersion);
@ -532,7 +532,7 @@ public class MainPagePanel extends GaussionPage {
t.launcher().launchingStateChanged.register(launchingStateChanged);
isLoading = true;
DefaultComboBoxModel model = (DefaultComboBoxModel) cboProfiles.getModel();
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) cboProfiles.getModel();
for (int i = 0; i < model.getSize(); ++i)
if (model.getElementAt(i).equals(t.getName())) {
model.setSelectedItem(t.getName());

View File

@ -24,7 +24,7 @@ import javax.swing.JComboBox;
* Make the popup menu of combo boxes wider.
* @author huangyuhui
*/
public class WideComboBox extends JComboBox {
public class WideComboBox<E> extends JComboBox<E> {
public WideComboBox() {
}

View File

@ -38,12 +38,12 @@ public class ModpackInitializationPanel extends javax.swing.JPanel {
public static final String KEY_INCLUDING_LAUNCHER = "launcher";
private final transient WizardController controller;
private final Map wizardData;
private final Map<String, Object> wizardData;
/**
* Creates new form ModpackInitializationPanel
*/
public ModpackInitializationPanel(WizardController controller, Map wizardData, Vector<String> versions, String selVersion) {
public ModpackInitializationPanel(WizardController controller, Map<String, Object> wizardData, Vector<String> versions, String selVersion) {
initComponents();
this.controller = controller;

View File

@ -1,62 +0,0 @@
/*
* 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.launcher.util;
import java.io.File;
import java.util.ArrayList;
/**
*
* @author huangyuhui
*/
public class ModpackUpdater {
private ModpackInfo info;
public ModpackUpdater(File baseFolder, ModpackInfo info) {
this.info = info;
}
void update() {
}
public ModpackInfo getInfo() {
return info;
}
public void setInfo(ModpackInfo info) {
this.info = info;
}
public static class ModpackInfo {
ArrayList<ModpackFolder> folders;
ArrayList<ModpackFile> files;
public static class ModpackFolder {
String ext, name;
}
public static class ModpackFile {
String hash, loc;
}
}
}

View File

@ -18,8 +18,6 @@
package org.jackhuang.hellominecraft.launcher.util.upgrade;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@ -173,8 +171,8 @@ public class AppDataUpgrader extends IUpgrader {
if (!f.createNewFile())
HMCLog.warn("Failed to create new file: " + f);
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(f))) {
Pack200.newUnpacker().unpack(new GZIPInputStream(new FileInputStream(tempFile)), jos);
try (JarOutputStream jos = new JarOutputStream(FileUtils.openOutputStream(f))) {
Pack200.newUnpacker().unpack(new GZIPInputStream(FileUtils.openInputStream(tempFile)), jos);
}
json.put("ver", newestVersion);
json.put("loc", f.getAbsolutePath());

View File

@ -14,7 +14,7 @@
* You should have received a copy of the GNU General Public License
* along with this program.
*/
package org.jackhuang.hellominecraft.lookandfeel.comp;
package org.jackhuang.hellominecraft.lookandfeel;
import java.awt.Color;
import org.jackhuang.hellominecraft.util.ui.GraphicsUtils;
@ -28,7 +28,5 @@ public class ConstomButton extends javax.swing.JButton {
prelightFg = GraphicsUtils.getWebColorWithAlpha("FFFFFF7F"), prelightBg = GraphicsUtils.getWebColorWithAlpha("FFFFFF7F"),
activeFg = GraphicsUtils.getWebColorWithAlpha("EAEDF83F"), activeBg = GraphicsUtils.getWebColorWithAlpha("EAEDF83F");
public int drawPercent = 0;
public long lastDrawTime = 0;
public int radix = 0;
public boolean notDraw = false;
}

View File

@ -1,26 +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.lookandfeel.comp;
/**
*
* @author huangyuhui
*/
public interface IConstomable {
boolean constomBackground();
boolean constomForeground();
}

View File

@ -31,7 +31,7 @@ import javax.swing.plaf.synth.SynthConstants;
import javax.swing.plaf.synth.SynthContext;
import javax.swing.plaf.synth.SynthPainter;
import org.jackhuang.hellominecraft.util.ui.GraphicsUtils;
import org.jackhuang.hellominecraft.lookandfeel.comp.ConstomButton;
import org.jackhuang.hellominecraft.lookandfeel.ConstomButton;
/**
* ButtonPainter - handles painting Nimbus style buttons with Java2D

View File

@ -34,7 +34,7 @@ import java.awt.Component;
public class ListCellRender extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
setOpaque(true);
setBackground(Color.magenta);

View File

@ -20,10 +20,6 @@
*/
package org.jackhuang.hellominecraft.lookandfeel.ui;
import static javax.swing.SwingConstants.NORTH;
import static javax.swing.SwingConstants.SOUTH;
import javax.swing.SwingConstants;
import javax.swing.plaf.metal.MetalScrollButton;
import java.awt.Dimension;
import java.awt.Graphics;

View File

@ -18,8 +18,6 @@
package org.jackhuang.hellominecraft.svrmgr;
import java.awt.Font;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
@ -60,13 +58,7 @@ public class Main {
new MainWindow().setVisible(true);
} catch (Throwable t) {
HMCLog.err("There's something wrong when running server holder.", t);
LogWindow.INSTANCE.clean();
LogWindow.INSTANCE.warning("开服器崩溃了QAQ");
StringWriter trace = new StringWriter();
t.printStackTrace(new PrintWriter(trace));
LogWindow.INSTANCE.warning(trace.toString());
LogWindow.INSTANCE.setVisible(true);
LogWindow.INSTANCE.showAsCrashWindow(false);
System.exit(-1);
}

View File

@ -122,7 +122,7 @@ public class ForgeInstaller {
File packFile = new File(gameDir, "libraries" + File.separator + library.formatted + ".pack.xz");
if (packFile.exists() && packFile.isFile())
try {
unpackLibrary(lib.getParentFile(), IOUtils.readFully(FileUtils.openInputStream(packFile)).toByteArray());
unpackLibrary(lib.getParentFile(), IOUtils.toByteArray(FileUtils.openInputStream(packFile)));
if (!checksumValid(lib, Arrays.asList(library.checksums)))
badLibs.add(library.name);
} catch (IOException e) {
@ -139,7 +139,7 @@ public class ForgeInstaller {
if (output.exists())
output.delete();
byte[] decompressed = IOUtils.readFully(new XZInputStream(new ByteArrayInputStream(data))).toByteArray();
byte[] decompressed = IOUtils.toByteArray(new XZInputStream(new ByteArrayInputStream(data)));
String end = new String(decompressed, decompressed.length - 4, 4);
if (!end.equals("SIGN")) {
@ -165,7 +165,7 @@ public class ForgeInstaller {
private static boolean checksumValid(File libPath, List<String> checksums) {
try {
byte[] fileData = IOUtils.readFully(FileUtils.openInputStream(libPath)).toByteArray();
byte[] fileData = IOUtils.toByteArray(FileUtils.openInputStream(libPath));
boolean valid = (checksums == null) || (checksums.isEmpty()) || (checksums.contains(DigestUtils.sha1Hex(fileData)));
if ((!valid) && (libPath.getName().endsWith(".jar")))
valid = validateJar(libPath, fileData, checksums);
@ -184,7 +184,7 @@ public class ForgeInstaller {
try (JarInputStream jar = new JarInputStream(new ByteArrayInputStream(data))) {
JarEntry entry = jar.getNextJarEntry();
while (entry != null) {
byte[] eData = IOUtils.readFully(jar).toByteArray();
byte[] eData = IOUtils.toByteArray(jar);
if (entry.getName().equals("checksums.sha1"))
hashes = new String(eData, Charset.forName("UTF-8")).split("\n");

View File

@ -24,7 +24,6 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
@ -47,6 +46,7 @@ import org.jackhuang.hellominecraft.svrmgr.util.WaitForThread;
import org.jackhuang.hellominecraft.svrmgr.util.Utilities;
import org.jackhuang.hellominecraft.util.Event;
import org.jackhuang.hellominecraft.util.EventHandler;
import org.jackhuang.hellominecraft.util.code.Charsets;
import org.jackhuang.hellominecraft.util.func.Consumer;
/**
@ -54,7 +54,7 @@ import org.jackhuang.hellominecraft.util.func.Consumer;
* @author huangyuhui
*/
public class Server implements Event<Integer>, MonitorThread.MonitorThreadListener,
ActionListener {
ActionListener {
private static Server instance;
private static boolean disactived = false;
@ -125,17 +125,13 @@ public class Server implements Event<Integer>, MonitorThread.MonitorThreadListen
pb.directory(new File(SettingsManager.settings.mainjar).getParentFile());
try {
disactiveMods(SettingsManager.settings.inactiveExtMods,
SettingsManager.settings.inactiveCoreMods,
SettingsManager.settings.inactivePlugins);
SettingsManager.settings.inactiveCoreMods,
SettingsManager.settings.inactivePlugins);
server = pb.start();
registerThread(threadA, server.getInputStream());
registerThread(threadB, server.getErrorStream());
registerThreadC(server);
try {
bw = new BufferedWriter(new OutputStreamWriter(server.getOutputStream(), System.getProperty("sun.jnu.encoding", "utf-8")));
} catch (UnsupportedEncodingException ex) {
bw = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
}
bw = new BufferedWriter(new OutputStreamWriter(server.getOutputStream(), Charsets.toCharset()));
isRunning = true;
startedEvent.execute(null);
sendStatus("*** 启动服务端中 ***");
@ -244,7 +240,7 @@ public class Server implements Event<Integer>, MonitorThread.MonitorThreadListen
}
private static void disactiveMods(ArrayList<String> inactiveExtMods,
ArrayList<String> inactiveCoreMods, ArrayList<String> inactivePlugins) {
ArrayList<String> inactiveCoreMods, ArrayList<String> inactivePlugins) {
disactiveModsByType(inactiveExtMods, "mods");
disactiveModsByType(inactiveCoreMods, "coremods");
disactiveModsByType(inactivePlugins, "plugins");
@ -267,7 +263,7 @@ public class Server implements Event<Integer>, MonitorThread.MonitorThreadListen
String name = file.getName();
if ((!paramArrayOfString.contains(name))
|| ((!name.toLowerCase().endsWith(".zip")) && (!name.toLowerCase().endsWith(".jar"))))
|| ((!name.toLowerCase().endsWith(".zip")) && (!name.toLowerCase().endsWith(".jar"))))
continue;
String newName = name + "X";

View File

@ -90,7 +90,7 @@ public abstract class PlayerList<T extends BasePlayer> {
op = null;
if (txt.exists())
try {
initByText(FileUtils.readIgnoreFileNotFound(txt));
initByText(FileUtils.read(txt));
if (op != null)
player.addAll(op);
} catch (IOException e) {
@ -100,7 +100,7 @@ public abstract class PlayerList<T extends BasePlayer> {
}
public void saveAsText(File file) throws IOException {
FileUtils.write(file, StrUtils.parseParams("", op, System.getProperty("line.separator")));
FileUtils.write(file, StrUtils.parseParams("", op.toArray(), System.getProperty("line.separator")));
}
public void saveAsJson(File file) throws IOException {

View File

@ -26,6 +26,7 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.system.IOUtils;
/**
@ -58,7 +59,7 @@ public class ServerProperties {
public String getProperty(String key, String defaultValue) {
try {
is = new FileInputStream(new File(path, "server.properties"));
is = FileUtils.openInputStream(new File(path, "server.properties"));
p = new Properties();
p.load(is);
return p.getProperty(key, defaultValue);
@ -84,12 +85,12 @@ public class ServerProperties {
public void setProperty(String key, String value) {
try {
is = new FileInputStream(new File(path, "server.properties"));
is = FileUtils.openInputStream(new File(path, "server.properties"));
p = new Properties();
p.load(is);
p.setProperty(key, value);
SimpleDateFormat f = new SimpleDateFormat("E M d HH:mm:ss z y");
p.store(new FileOutputStream(new File(path, "server.properties")),
p.store(FileUtils.openOutputStream(new File(path, "server.properties")),
"Minecraft server properties\n" + f.format(new Date()));
} catch (IOException ex) {
HMCLog.warn("Failed to set property in server.properties", ex);

View File

@ -86,7 +86,7 @@ import org.jackhuang.hellominecraft.svrmgr.util.IPGet;
import org.jackhuang.hellominecraft.svrmgr.util.Utilities;
import org.jackhuang.hellominecraft.util.ui.SwingUtils;
import org.jackhuang.hellominecraft.svrmgr.util.version.MinecraftRemoteVersion;
import org.jackhuang.hellominecraft.lookandfeel.comp.ConstomButton;
import org.jackhuang.hellominecraft.lookandfeel.ConstomButton;
import org.jackhuang.hellominecraft.util.Event;
import org.jackhuang.hellominecraft.util.StrUtils;

View File

@ -21,8 +21,8 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.jackhuang.hellominecraft.util.code.Charsets;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
/**
@ -42,11 +42,7 @@ public class MonitorThread extends Thread {
public MonitorThread(InputStream is) {
this.listeners = new ArrayList<>(5);
try {
br = new BufferedReader(new InputStreamReader(is, System.getProperty("sun.jnu.encoding", "gbk")));
} catch (UnsupportedEncodingException ex) {
br = new BufferedReader(new InputStreamReader(is));
}
br = new BufferedReader(new InputStreamReader(is, Charsets.toCharset(System.getProperty("sun.jnu.encoding", "gbk"))));
}
public void addListener(MonitorThreadListener l) {

View File

@ -47,12 +47,12 @@ public abstract class AbstractSwingWorker<T> extends SwingWorker<Void, T> {
return null;
}
public AbstractSwingWorker reg(Consumer<T> c) {
public AbstractSwingWorker<T> reg(Consumer<T> c) {
processListeners.add(Objects.requireNonNull(c));
return this;
}
public AbstractSwingWorker regDone(Runnable c) {
public AbstractSwingWorker<T> regDone(Runnable c) {
doneListeners.add(Objects.requireNonNull(c));
return this;
}

View File

@ -18,6 +18,8 @@
package org.jackhuang.hellominecraft.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -57,10 +59,6 @@ public final class ArrayUtils {
return -1;
}
public static <T> int lastIndexOf(T[] array, T valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static <T> int lastIndexOf(T[] array, T valueToFind, int startIndex) {
if (array == null)
return -1;
@ -75,16 +73,16 @@ public final class ArrayUtils {
}
public static <T> ArrayList<T> merge(List<T> a, List<T> b) {
ArrayList al = new ArrayList(a.size() + b.size());
ArrayList<T> al = new ArrayList<>(a.size() + b.size());
al.addAll(a);
al.addAll(b);
return al;
}
public static List tryGetMapWithList(Map map, String key) {
List l = (List) map.get(key);
public static <T> List<T> tryGetMapWithList(Map<String, List<T>> map, String key) {
List<T> l = (List<T>) map.get(key);
if (l == null)
map.put(key, l = new ArrayList());
map.put(key, l = new ArrayList<>());
return l;
}
@ -102,4 +100,8 @@ public final class ArrayUtils {
}
return -1;
}
public static <T> boolean hasDuplicateElements(T[] t) {
return new HashSet<>(Arrays.asList(t)).size() < t.length;
}
}

View File

@ -35,10 +35,6 @@ public final class C {
public static final String URL_GITHUB = "https://github.com/huanghongxun/HMCL/issues";
public static final String URL_MINECRAFTFORUM = "http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-tools/1265720-hello-minecraft-launcher-1-9-3-mc-1-7-4-auto";
public static final String FILE_MINECRAFT_VERSIONS = "versions";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
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";

View File

@ -49,26 +49,14 @@ public class EventHandler<T> {
events.add(t);
}
public void unregister(Event<T> t) {
events.remove(t);
}
public void unregister(Consumer<T> t) {
events.remove(t);
}
public void unregister(Runnable t) {
events.remove(t);
}
public boolean execute(T x) {
boolean flag = true;
for (Object t : events)
if (t instanceof Event) {
if (!((Event) t).call(sender, x))
if (!((Event<T>) t).call(sender, x))
flag = false;
} else if (t instanceof Consumer)
((Consumer) t).accept(x);
((Consumer<T>) t).accept(x);
else if (t instanceof Runnable)
((Runnable) t).run();
return flag;

View File

@ -1,49 +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;
import org.jackhuang.hellominecraft.util.func.Consumer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
/**
*
* @author huangyuhui
*/
public class LauncherPrintStream extends PrintStream {
private final ArrayList<Consumer<String>> printListeners = new ArrayList<>();
public LauncherPrintStream(OutputStream paramOutputStream) {
super(paramOutputStream);
}
@Override
public final void println(String paramString) {
super.println(paramString);
for (Consumer<String> a1 : printListeners)
a1.accept(paramString);
}
public final LauncherPrintStream addPrintListener(Consumer<String> paraml) {
this.printListeners.add(paraml);
return this;
}
}

View File

@ -68,7 +68,7 @@ public class MinecraftVersionRequest implements Serializable {
private static MinecraftVersionRequest getVersionOfOldMinecraft(ZipFile file, ZipEntry entry) throws IOException {
MinecraftVersionRequest r = new MinecraftVersionRequest();
byte[] tmp = IOUtils.readFully(file.getInputStream(entry)).toByteArray();
byte[] tmp = IOUtils.toByteArray(file.getInputStream(entry));
byte[] bytes = "Minecraft Minecraft ".getBytes("ASCII");
int j = ArrayUtils.matchArray(tmp, bytes);
@ -92,7 +92,7 @@ public class MinecraftVersionRequest implements Serializable {
private static MinecraftVersionRequest getVersionOfNewMinecraft(ZipFile file, ZipEntry entry) throws IOException {
MinecraftVersionRequest r = new MinecraftVersionRequest();
byte[] tmp = IOUtils.readFully(file.getInputStream(entry)).toByteArray();
byte[] tmp = IOUtils.toByteArray(file.getInputStream(entry));
byte[] str = "-server.txt".getBytes("ASCII");
int j = ArrayUtils.matchArray(tmp, str);

View File

@ -55,10 +55,6 @@ public final class NetUtils {
return get(url, IOUtils.DEFAULT_CHARSET);
}
public static String get(URL url) throws IOException {
return get(url, Proxy.NO_PROXY);
}
public static String get(URL url, Proxy proxy) throws IOException {
return readData(createConnection(url, proxy));
}
@ -123,12 +119,4 @@ public final class NetUtils {
return null;
}
}
public static URL concatenateURL(URL url, String query) {
try {
return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + (url.getQuery() != null && url.getQuery().length() > 0 ? '&' : '?') + query);
} catch (MalformedURLException ex) {
throw new IllegalArgumentException("Could not concatenate given URL with GET arguments!", ex);
}
}
}

View File

@ -17,7 +17,6 @@
*/
package org.jackhuang.hellominecraft.util;
import java.awt.Dimension;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
@ -72,15 +71,6 @@ public final class StrUtils {
return base != null && base.startsWith(match);
}
public static boolean startsWithOne(String[] a, String match) {
if (a == null)
return false;
for (String b : a)
if (startsWith(match, b))
return true;
return false;
}
public static boolean startsWithOne(Collection<String> a, String match) {
if (a == null)
return false;
@ -97,21 +87,6 @@ public final class StrUtils {
return false;
}
public static boolean containsOne(String base, String... match) {
for (String s : match)
if (base.contains(s))
return true;
return false;
}
public static boolean containsOne(List<String> base, List<String> match) {
for (String a : base)
for (String b : match)
if (a.toLowerCase().contains(b.toLowerCase()))
return true;
return false;
}
public static boolean containsOne(List<String> base, List<String> match, Predicate<String> pred) {
for (String a : base)
for (String b : match)
@ -142,12 +117,12 @@ public final class StrUtils {
return ver;
}
public static String parseParams(String addBefore, Collection paramArrayOfObject, String paramString) {
return parseParams(addBefore, paramArrayOfObject.toArray(), paramString);
public static String parseParams(String addBefore, Collection<?> objects, String addAfter) {
return parseParams(addBefore, objects.toArray(), addAfter);
}
public static String parseParams(String addBefore, Object[] params, String addAfter) {
return parseParams(t -> addBefore, params, t -> addAfter);
public static String parseParams(String addBefore, Object[] objects, String addAfter) {
return parseParams(t -> addBefore, objects, t -> addAfter);
}
public static String parseParams(Function<Object, String> beforeFunc, Object[] params, Function<Object, String> afterFunc) {
@ -179,37 +154,19 @@ public final class StrUtils {
return sb.toString();
}
public static boolean equals(String base, String to) {
if (base == null)
return to == null;
else
return base.equals(to);
}
public static Dimension parseDimension(String str) {
String[] tokenized = tokenize(str, "x,");
if (tokenized.length != 2)
return null;
int i = MathUtils.parseInt(tokenized[0], -1);
int j = MathUtils.parseInt(tokenized[1], -1);
if ((i < 0) || (j < 0))
return null;
return new Dimension(i, j);
}
public static String[] tokenize(String paramString1) {
return tokenize(paramString1, " \t\n\r\f");
}
public static String[] tokenize(String paramString1, String paramString2) {
ArrayList localArrayList = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(paramString1, paramString2);
public static String[] tokenize(String str, String delim) {
ArrayList<String> al = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(str, delim);
while (tokenizer.hasMoreTokens()) {
paramString2 = tokenizer.nextToken();
localArrayList.add(paramString2);
delim = tokenizer.nextToken();
al.add(delim);
}
return (String[]) localArrayList.toArray(new String[localArrayList.size()]);
return al.toArray(new String[al.size()]);
}
public static boolean isBlank(String s) {
@ -226,14 +183,4 @@ public final class StrUtils {
t.printStackTrace(writer);
return trace.toString();
}
public static List<Integer> findAllPos(String t, String p) {
ArrayList<Integer> ret = new ArrayList<>();
int i = 0, index;
while ((index = t.indexOf(p, i)) != -1) {
ret.add(index);
i = index + p.length();
}
return ret;
}
}

View File

@ -47,7 +47,7 @@ public final class UpdateChecker implements IUpdateChecker {
@Override
public AbstractSwingWorker<VersionNumber> process(final boolean showMessage) {
return new AbstractSwingWorker() {
return new AbstractSwingWorker<VersionNumber>() {
@Override
protected void work() throws Exception {
if (value == null) {
@ -74,12 +74,12 @@ public final class UpdateChecker implements IUpdateChecker {
@Override
public synchronized AbstractSwingWorker<Map<String, String>> requestDownloadLink() {
return new AbstractSwingWorker() {
return new AbstractSwingWorker<Map<String, String>>() {
@Override
protected void work() throws Exception {
if (download_link == null)
try {
download_link = C.GSON.fromJson(NetUtils.get("http://huangyuhui.duapp.com/update_link.php?type=" + type), Map.class);
download_link = C.GSON.<Map<String, String>>fromJson(NetUtils.get("http://huangyuhui.duapp.com/update_link.php?type=" + type), Map.class);
} catch (JsonSyntaxException | IOException e) {
HMCLog.warn("Failed to get update link.", e);
}

View File

@ -52,7 +52,7 @@ public final class Utils {
*/
public static void shutdownForcely(int status) throws Exception {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
Class z = Class.forName("java.lang.Shutdown");
Class<?> z = Class.forName("java.lang.Shutdown");
Method exit = z.getDeclaredMethod("exit", int.class);
exit.setAccessible(true);
exit.invoke(z, status);

View File

@ -1,102 +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.code;
/**
*
* @author huangyuhui
*/
public final class Base64 {
private Base64() {
}
public static char[] encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false;
boolean trip = false;
int val = (0xFF & (int) data[i]);
val <<= 8;
if ((i + 1) < data.length) {
val |= (0xFF & (int) data[i + 1]);
trip = true;
}
val <<= 8;
if ((i + 2) < data.length) {
val |= (0xFF & (int) data[i + 2]);
quad = true;
}
out[index + 3] = ALPHABET[(quad ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 2] = ALPHABET[(trip ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 1] = ALPHABET[val & 0x3F];
val >>= 6;
out[index + 0] = ALPHABET[val & 0x3F];
}
return out;
}
public static char[] encode(String s) {
return encode(s.getBytes(Charsets.UTF_8));
}
public static byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 && data[data.length - 1] == '=')
--len;
if (data.length > 1 && data[data.length - 2] == '=')
--len;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = CODES[data[ix] & 0xFF];
if (value >= 0) {
accum <<= 6;
shift += 6;
accum |= value;
if (shift >= 8) {
shift -= 8;
out[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != out.length)
throw new Error("miscalculated data length!");
return out;
}
private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();
private static final byte[] CODES = new byte[256];
static {
for (int i = 0; i < 256; i++)
CODES[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
CODES[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
CODES[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
CODES[i] = (byte) (52 + i - '0');
CODES['+'] = 62;
CODES['/'] = 63;
}
}

View File

@ -18,13 +18,15 @@
package org.jackhuang.hellominecraft.util.code;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import org.jackhuang.hellominecraft.util.system.IOUtils;
public final class Charsets {
private Charsets() {
}
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
/*public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
public static final Charset US_ASCII = Charset.forName("US-ASCII");
@ -32,15 +34,22 @@ public final class Charsets {
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");*/
public static final Charset UTF_8 = Charset.forName("UTF-8");
public static Charset toCharset(Charset charset) {
return charset == null ? Charset.defaultCharset() : charset;
}
public static final Charset DEFAULT_CHARSET = UTF_8;
public static Charset toCharset(String charset) {
return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
if (charset == null) return Charset.defaultCharset();
try {
return Charset.forName(charset);
} catch(UnsupportedCharsetException ignored) {
return Charset.defaultCharset();
}
}
public static Charset toCharset() {
return toCharset(System.getProperty("sun.jnu.encoding", IOUtils.DEFAULT_CHARSET));
}
}

View File

@ -70,11 +70,6 @@ public final class DigestUtils {
return getDigest("SHA-512");
}
@Deprecated
public static MessageDigest getShaDigest() {
return getSha1Digest();
}
public static byte[] md2(byte[] data) {
return getMd2Digest().digest(data);
}
@ -127,22 +122,6 @@ public final class DigestUtils {
return Hex.encodeHexString(md5(data));
}
@Deprecated
public static byte[] sha(byte[] data) {
return sha1(data);
}
@Deprecated
public static byte[] sha(InputStream data)
throws IOException {
return sha1(data);
}
@Deprecated
public static byte[] sha(String data) {
return sha1(data);
}
public static byte[] sha1(byte[] data) {
return getSha1Digest().digest(data);
}
@ -247,22 +226,6 @@ public final class DigestUtils {
return Hex.encodeHexString(sha512(data));
}
@Deprecated
public static String shaHex(byte[] data) {
return sha1Hex(data);
}
@Deprecated
public static String shaHex(InputStream data)
throws IOException {
return sha1Hex(data);
}
@Deprecated
public static String shaHex(String data) {
return sha1Hex(data);
}
public static MessageDigest updateDigest(MessageDigest messageDigest, byte[] valueToDigest) {
messageDigest.update(valueToDigest);
return messageDigest;

View File

@ -21,8 +21,6 @@ import java.nio.charset.Charset;
public final class Hex {
public static final Charset DEFAULT_CHARSET = Charsets.UTF_8;
public static final String DEFAULT_CHARSET_NAME = "UTF-8";
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
@ -80,17 +78,13 @@ public final class Hex {
}
public Hex() {
this.charset = DEFAULT_CHARSET;
this(Charsets.DEFAULT_CHARSET);
}
public Hex(Charset charset) {
this.charset = charset;
}
public Hex(String charsetName) {
this(Charset.forName(charsetName));
}
public byte[] decode(byte[] array) throws Exception {
return decodeHex(new String(array, getCharset()).toCharArray());
}

View File

@ -1,26 +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.func;
/**
* @author huangyuhui
*/
public interface BiConsumer<V, V2> {
void call(V value, V2 value2);
}

View File

@ -1,27 +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.func;
/**
*
* @author huangyuhui
*/
public interface TriConsumer<V1, V2, V3> {
void onDone(V1 v1, V2 v2, V3 v3);
}

View File

@ -21,7 +21,7 @@ import org.jackhuang.hellominecraft.util.logging.appender.IAppender;
public class AppenderControl {
private final ThreadLocal<AppenderControl> recursive = new ThreadLocal();
private final ThreadLocal<AppenderControl> recursive = new ThreadLocal<>();
private final IAppender appender;
private final Level level;
private final int intLevel;

View File

@ -35,18 +35,10 @@ public class HMCLog {
LOGGER.warn(message);
}
public static void debug(String message) {
LOGGER.debug(message);
}
public static void warn(String msg, Throwable t) {
LOGGER.warn(msg, t);
}
public static void debug(String msg, Throwable t) {
LOGGER.debug(msg, t);
}
public static void err(String msg) {
LOGGER.error(msg);
}

View File

@ -27,7 +27,6 @@ import java.util.regex.Pattern;
*/
public enum Level {
OFF(0, Color.gray),
FATAL(1, Color.red),
ERROR(2, Color.red),
WARN(3, Color.orange),
@ -48,10 +47,6 @@ public enum Level {
return this.level <= level.level;
}
public boolean lessOrEqual(int level) {
return this.level <= level;
}
public static final Pattern MINECRAFT_LOGGER = Pattern.compile("\\[(?<timestamp>[0-9:]+)\\] \\[[^/]+/(?<level>[^\\]]+)\\]");
public static final String JAVA_SYMBOL = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$][a-zA-Z\\d_$]*";

View File

@ -28,7 +28,6 @@ public abstract class AbstractLogger
public static final Class<? extends IMessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS = ParameterizedMessageFactory.class;
private static final String FQCN = AbstractLogger.class.getName();
private static final String THROWING = "throwing";
private static final String CATCHING = "catching";
private final String name;
@ -68,50 +67,6 @@ public abstract class AbstractLogger
catching(Level.ERROR, t);
}
@Override
public void debug(IMessage msg) {
if (isEnabled(Level.DEBUG, msg, null))
log(Level.DEBUG, msg, null);
}
@Override
public void debug(IMessage msg, Throwable t) {
if (isEnabled(Level.DEBUG, msg, t))
log(Level.DEBUG, msg, t);
}
@Override
public void debug(Object message) {
if (isEnabled(Level.DEBUG, message, null))
log(Level.DEBUG, this.messageFactory.newMessage(message), null);
}
@Override
public void debug(Object message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t);
}
@Override
public void debug(String message) {
if (isEnabled(Level.DEBUG, message))
log(Level.DEBUG, this.messageFactory.newMessage(message), null);
}
@Override
public void debug(String message, Object[] params) {
if (isEnabled(Level.DEBUG, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.DEBUG, msg, msg.getThrowable());
}
}
@Override
public void debug(String message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t);
}
@Override
public void entry() {
entry(new Object[0]);
@ -395,50 +350,6 @@ public abstract class AbstractLogger
return this.name;
}
@Override
public void trace(IMessage msg) {
if (isEnabled(Level.TRACE, msg, null))
log(Level.TRACE, msg, null);
}
@Override
public void trace(IMessage msg, Throwable t) {
if (isEnabled(Level.TRACE, msg, t))
log(Level.TRACE, msg, t);
}
@Override
public void trace(Object message) {
if (isEnabled(Level.TRACE, message, null))
log(Level.TRACE, this.messageFactory.newMessage(message), null);
}
@Override
public void trace(Object message, Throwable t) {
if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t);
}
@Override
public void trace(String message) {
if (isEnabled(Level.TRACE, message))
log(Level.TRACE, this.messageFactory.newMessage(message), null);
}
@Override
public void trace(String message, Object[] params) {
if (isEnabled(Level.TRACE, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.TRACE, msg, msg.getThrowable());
}
}
@Override
public void trace(String message, Throwable t) {
if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t);
}
@Override
public void warn(IMessage msg) {
if (isEnabled(Level.WARN, msg, null))

View File

@ -30,20 +30,6 @@ public interface ILogger {
void catching(Throwable paramThrowable);
void debug(IMessage paramIMessage);
void debug(IMessage paramIMessage, Throwable paramThrowable);
void debug(Object paramObject);
void debug(Object paramObject, Throwable paramThrowable);
void debug(String paramString);
void debug(String paramString, Object[] paramArrayOfObject);
void debug(String paramString, Throwable paramThrowable);
void entry();
void entry(Object[] paramArrayOfObject);
@ -126,20 +112,6 @@ public interface ILogger {
<T extends Throwable> T throwing(T paramT);
void trace(IMessage paramIMessage);
void trace(IMessage paramIMessage, Throwable paramThrowable);
void trace(Object paramObject);
void trace(Object paramObject, Throwable paramThrowable);
void trace(String paramString);
void trace(String paramString, Object[] paramArrayOfObject);
void trace(String paramString, Throwable paramThrowable);
void warn(IMessage paramIMessage);
void warn(IMessage paramIMessage, Throwable paramThrowable);

View File

@ -31,7 +31,7 @@ import org.jackhuang.hellominecraft.util.logging.message.IMessageFactory;
public class Logger extends AbstractLogger {
protected volatile PrivateConfig config;
private final Map<String, AppenderControl> appenders = new ConcurrentHashMap();
private final Map<String, AppenderControl> appenders = new ConcurrentHashMap<>();
public Logger(String name) {
this(name, null, Level.INFO);
@ -109,8 +109,8 @@ public class Logger extends AbstractLogger {
}
public Map<String, IAppender> getAppenders() {
Map map = new HashMap();
for (Map.Entry entry : this.appenders.entrySet())
Map<String, IAppender> map = new HashMap<>();
for (Map.Entry<String, AppenderControl> entry : this.appenders.entrySet())
map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender());
return map;
}

View File

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

View File

@ -22,7 +22,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@ -230,7 +229,7 @@ public class ParameterizedMessage
if (o instanceof String)
return (String) o;
StringBuilder str = new StringBuilder();
Set dejaVu = new HashSet();
Set<String> dejaVu = new HashSet<>();
recursiveDeepToString(o, str, dejaVu);
return str.toString();
}
@ -244,7 +243,7 @@ public class ParameterizedMessage
str.append(o);
return;
}
Class oClass = o.getClass();
Class<?> oClass = o.getClass();
if (oClass.isArray())
if (oClass == byte[].class)
str.append(Arrays.toString((byte[]) (byte[]) o));
@ -265,7 +264,7 @@ public class ParameterizedMessage
else {
String id = identityToString(o);
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
str.append(RECURSION_PREFIX).append(id).append(RECURSION_SUFFIX);
else {
dejaVu.add(id);
Object[] oArray = (Object[]) (Object[]) o;
@ -276,7 +275,7 @@ public class ParameterizedMessage
first = false;
else
str.append(", ");
recursiveDeepToString(current, str, new HashSet(dejaVu));
recursiveDeepToString(current, str, new HashSet<>(dejaVu));
}
str.append("]");
}
@ -284,42 +283,40 @@ public class ParameterizedMessage
else if ((o instanceof Map)) {
String id = identityToString(o);
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
str.append(RECURSION_PREFIX).append(id).append(RECURSION_SUFFIX);
else {
dejaVu.add(id);
Map oMap = (Map) o;
Map<?, ?> oMap = (Map<?, ?>) o;
str.append("{");
boolean isFirst = true;
for (Object o1 : oMap.entrySet()) {
Map.Entry current = (Map.Entry) o1;
for (Map.Entry<?, ?> current : oMap.entrySet()) {
if (isFirst)
isFirst = false;
else
str.append(", ");
Object key = current.getKey();
Object value = current.getValue();
recursiveDeepToString(key, str, new HashSet(dejaVu));
recursiveDeepToString(key, str, new HashSet<>(dejaVu));
str.append("=");
recursiveDeepToString(value, str, new HashSet(dejaVu));
recursiveDeepToString(value, str, new HashSet<>(dejaVu));
}
str.append("}");
}
} else if ((o instanceof Collection)) {
String id = identityToString(o);
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
str.append(RECURSION_PREFIX).append(id).append(RECURSION_SUFFIX);
else {
dejaVu.add(id);
Collection oCol = (Collection) o;
Collection<?> oCol = (Collection<?>) o;
str.append("[");
boolean isFirst = true;
for (Iterator i$ = oCol.iterator(); i$.hasNext();) {
Object anOCol = i$.next();
for (Object anOCol : oCol) {
if (isFirst)
isFirst = false;
else
str.append(", ");
recursiveDeepToString(anOCol, str, new HashSet(dejaVu));
recursiveDeepToString(anOCol, str, new HashSet<>(dejaVu));
}
str.append("]");
}
@ -332,17 +329,17 @@ public class ParameterizedMessage
try {
str.append(o.toString());
} catch (Throwable t) {
str.append("[!!!");
str.append(ERROR_PREFIX);
str.append(identityToString(o));
str.append("=>");
str.append(ERROR_SEPARATOR);
String msg = t.getMessage();
String className = t.getClass().getName();
str.append(className);
if (!className.equals(msg)) {
str.append(":");
str.append(ERROR_MSG_SEPARATOR);
str.append(msg);
}
str.append("!!!]");
str.append(ERROR_SUFFIX);
}
}

View File

@ -23,8 +23,6 @@ package org.jackhuang.hellominecraft.util.logging.message;
*/
public final class ParameterizedMessageFactory extends AbstractMessageFactory {
public static final ParameterizedMessageFactory INSTANCE = new ParameterizedMessageFactory();
@Override
public IMessage newMessage(String message, Object[] params) {
return new ParameterizedMessage(message, params);

View File

@ -17,10 +17,7 @@
*/
package org.jackhuang.hellominecraft.util.system;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ -55,9 +52,7 @@ public final class CompressingUtils {
* @throws java.io.IOException 压缩失败或无法读取
*/
public static void zip(File sourceDir, File zipFile, BiFunction<String, Boolean, String> pathNameCallback) throws IOException {
FileOutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
try (ZipOutputStream zos = new ZipOutputStream(FileUtils.openOutputStream(zipFile))) {
String basePath;
if (sourceDir.isDirectory())
basePath = sourceDir.getPath();
@ -68,30 +63,6 @@ public final class CompressingUtils {
}
}
/**
* 功能 sourceDir 目录下的所有文件进行 zip 格式的压缩保存为指定 zip 文件
*
* @param sourceDir 源文件夹
* @param zipFile 压缩生成的zip文件路径
* @param pathNameCallback callback(pathName, isDirectory) returns your
* modified pathName
*
* @throws java.io.IOException 压缩失败或无法读取
*/
public static ZipOutputStream zipContinuing(File sourceDir, File zipFile, BiFunction<String, Boolean, String> pathNameCallback) throws IOException {
FileOutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
String basePath;
if (sourceDir.isDirectory())
basePath = sourceDir.getPath();
else//直接压缩单个文件时取父目录
basePath = sourceDir.getParent();
zipFile(sourceDir, basePath, zos, pathNameCallback);
return zos;
}
}
/**
* 将文件压缩成zip文件
*
@ -128,18 +99,13 @@ public final class CompressingUtils {
pathName = pathNameCallback.apply(pathName, true);
if (pathName == null)
continue;
try (InputStream is = new FileInputStream(file)) {
BufferedInputStream bis = new BufferedInputStream(is);
try (InputStream is = FileUtils.openInputStream(file)) {
zos.putNextEntry(new ZipEntry(pathName));
IOUtils.copyStream(bis, zos, buf);
IOUtils.copyStream(is, zos, buf);
}
}
}
public static void unzip(String zipFileName, String extPlace) throws IOException {
unzip(new File(zipFileName), new File(extPlace));
}
public static void unzip(File zipFileName, File extPlace) throws IOException {
unzip(zipFileName, extPlace, null, true);
}
@ -157,7 +123,7 @@ public final class CompressingUtils {
public static void unzip(File zipFileName, File extPlace, Predicate<String> callback, boolean ignoreExistsFile) throws IOException {
byte[] buf = new byte[1024];
extPlace.mkdirs();
try (ZipInputStream zipFile = new ZipInputStream(new FileInputStream(zipFileName))) {
try (ZipInputStream zipFile = new ZipInputStream(FileUtils.openInputStream(zipFileName))) {
if (zipFileName.exists()) {
String strPath, gbkPath, strtemp;
strPath = extPlace.getAbsolutePath();
@ -186,7 +152,7 @@ public final class CompressingUtils {
}
if (ignoreExistsFile && new File(strtemp).exists())
continue;
try (FileOutputStream fos = new FileOutputStream(strtemp)) {
try (FileOutputStream fos = FileUtils.openOutputStream(new File(strtemp))) {
IOUtils.copyStream(zipFile, fos, buf);
}
}

View File

@ -152,11 +152,11 @@ public final class FileUtils {
if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath()))
throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
List exclusionList = null;
List<String> exclusionList = null;
if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if ((srcFiles != null) && (srcFiles.length > 0)) {
exclusionList = new ArrayList(srcFiles.length);
exclusionList = new ArrayList<>(srcFiles.length);
for (File srcFile : srcFiles) {
File copiedFile = new File(destDir, srcFile.getName());
exclusionList.add(copiedFile.getCanonicalPath());
@ -193,12 +193,12 @@ public final class FileUtils {
public static String read(File file)
throws IOException {
return IOUtils.toString(IOUtils.openInputStream(file));
return IOUtils.toString(openInputStream(file));
}
public static String readQuietly(File file) {
try {
return IOUtils.toString(IOUtils.openInputStream(file));
return IOUtils.toString(openInputStream(file));
} catch (IOException ex) {
HMCLog.err("Failed to read file: " + file, ex);
return null;
@ -207,15 +207,7 @@ public final class FileUtils {
public static String read(File file, String charset)
throws IOException {
return IOUtils.toString(IOUtils.openInputStream(file), charset);
}
public static String readIgnoreFileNotFound(File file) throws IOException {
try {
return IOUtils.toString(IOUtils.openInputStream(file));
} catch (FileNotFoundException ex) {
return "";
}
return IOUtils.toString(openInputStream(file), charset);
}
public static void copyFileQuietly(File srcFile, File destFile) {
@ -371,7 +363,7 @@ public final class FileUtils {
}
public static File[] searchSuffix(File dir, String suffix) {
ArrayList<File> al = new ArrayList();
ArrayList<File> al = new ArrayList<>();
File[] files = dir.listFiles();
if (files == null)
return new File[0];

View File

@ -21,8 +21,6 @@ import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@ -81,16 +79,6 @@ public final class IOUtils {
return t;
}
public static String extractLastDirectory(String dir) {
String t = removeLastSeparator(dir);
int i = t.length() - 1;
while (i >= 0 && !isSeparator(dir.charAt(i)))
i--;
if (i < 0)
return t;
return t.substring(i + 1, (t.length() - i) + (i + 1) - 1);
}
public static void findAllFile(File f, Consumer<String> callback) {
if (f.isDirectory()) {
File[] f1 = f.listFiles();
@ -110,7 +98,7 @@ public final class IOUtils {
callback.accept(f1[i].getName());
}
}
public static String getRealPath() {
String realPath = IOUtils.class.getClassLoader().getResource("").getFile();
java.io.File file = new java.io.File(realPath);
@ -171,11 +159,6 @@ public final class IOUtils {
return mac;
}
public static String extractFileName(String fileName) {
File file = new File(fileName);
return file.getName();
}
public static String getJavaDir() {
return getJavaDir(System.getProperty("java.home"));
}
@ -246,18 +229,6 @@ public final class IOUtils {
output.write(data.getBytes(encoding));
}
public static FileInputStream openInputStream(File file)
throws IOException {
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory");
if (!file.canRead())
throw new IOException("File '" + file + "' cannot be read");
} else
throw new FileNotFoundException("File '" + file + "' does not exist");
return new FileInputStream(file);
}
public static String tryGetCanonicalFolderPath(File file) {
try {
return IOUtils.addSeparator(file.getCanonicalPath());

View File

@ -30,10 +30,12 @@ public class JavaProcess {
private final List<String> commands;
private final Process process;
private final ArrayList<String> stdOutLines = new ArrayList<>();
private final ProcessManager pm;
public JavaProcess(List<String> commands, Process process, ProcessManager pm) {
this.commands = commands;
this.process = process;
this.pm = pm;
if (pm != null)
pm.registerProcess(this);
}
@ -53,6 +55,10 @@ public class JavaProcess {
public String getStartupCommand() {
return this.process.toString();
}
public ProcessManager getProcessManager() {
return pm;
}
public ArrayList<String> getStdOutLines() {
return this.stdOutLines;

View File

@ -115,15 +115,6 @@ public final class JdkVersion implements Cloneable {
*/
public static final int JAVA_19 = 6;
private static final String JAVA_VER;
private static final int MAJOR_JAVA_VER;
static {
JAVA_VER = System.getProperty("java.version");
// version String should look like "1.4.2_10"
MAJOR_JAVA_VER = parseVersion(JAVA_VER);
}
private static int parseVersion(String javaVersion) {
if (StrUtils.isBlank(javaVersion))
return UNKOWN;
@ -139,42 +130,6 @@ public final class JdkVersion implements Cloneable {
return a;
}
/**
* Return the full Java version string, as returned by
* <code>System.getProperty("java.version")</code>.
*
* @return the full Java version string
*
* @see System#getProperty(String)
*/
public static String getJavaVersion() {
return JAVA_VER;
}
/**
* Get the major version code. This means we can do things like
* <code>if (getMajorJavaVersion() < JAVA_14)</code>. @retu
*
*
* rn a code comparable to the JAVA_XX codes in this class
*
* @return
*
* @see #JAVA_13
* @see #JAVA_14
* @see #JAVA_15
* @see #JAVA_16
* @see #JAVA_17
*/
public static int getMajorJavaVersion() {
return MAJOR_JAVA_VER;
}
public static boolean isJava64Bit() {
String jdkBit = System.getProperty("sun.arch.data.model");
return jdkBit.contains("64");
}
private static final Pattern p = Pattern.compile("java version \"[1-9]*\\.[1-9]*\\.[0-9]*(.*?)\"");
public static JdkVersion getJavaVersionFromExecutable(String file) throws IOException {
@ -197,11 +152,6 @@ public final class JdkVersion implements Cloneable {
return new JdkVersion(file, ver, platform);
}
public void write(File f) throws IOException {
if (ver != null && getPlatform() != Platform.UNKNOWN)
FileUtils.write(f, ver + "\n" + platform);
}
public boolean isEarlyAccess() {
return getVersion() != null && getVersion().endsWith("-ea");
}

View File

@ -20,7 +20,6 @@ package org.jackhuang.hellominecraft.util.system;
import com.sun.management.OperatingSystemMXBean;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
@ -92,7 +91,7 @@ public enum OS {
public static long[] memoryInfoForLinux() throws IOException {
File file = new File("/proc/meminfo");
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charsets.UTF_8))) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(FileUtils.openInputStream(file), Charsets.UTF_8))) {
long[] result = new long[4];
String str;
StringTokenizer token;

View File

@ -25,7 +25,7 @@ import java.util.HashSet;
*/
public class ProcessManager {
private static final HashSet<JavaProcess> GAME_PROCESSES = new HashSet();
private static final HashSet<JavaProcess> GAME_PROCESSES = new HashSet<>();
public void registerProcess(JavaProcess jp) {
GAME_PROCESSES.add(jp);

View File

@ -21,9 +21,9 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.EventHandler;
import org.jackhuang.hellominecraft.util.code.Charsets;
/**
*
@ -50,15 +50,9 @@ public class ProcessThread extends Thread {
BufferedReader br = null;
try {
InputStream in = p.getRawProcess().getInputStream();
try {
br = new BufferedReader(new InputStreamReader(in, System.getProperty("sun.jnu.encoding", "UTF-8")));
} catch (UnsupportedEncodingException ex) {
HMCLog.warn("Unsupported encoding: " + System.getProperty("sun.jnu.encoding", "UTF-8"), ex);
br = new BufferedReader(new InputStreamReader(in));
}
br = new BufferedReader(new InputStreamReader(in, Charsets.toCharset()));
int ch;
String line = "";
String line;
while (p.isRunning())
while ((line = br.readLine()) != null) {
printlnEvent.execute(line);
@ -70,6 +64,8 @@ public class ProcessThread extends Thread {
System.out.println("Minecraft: " + line);
p.getStdOutLines().add(line);
}
if (p.getProcessManager() != null)
p.getProcessManager().onProcessStopped(p);
stopEvent.execute(p);
} catch (IOException e) {
HMCLog.err("An error occured when reading process stdout/stderr.", e);

View File

@ -1,47 +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.system;
import org.jackhuang.hellominecraft.util.func.Consumer;
/**
*
* @author huangyuhui
*/
public class ThreadExecutor extends Thread {
public final Consumer<Throwable> c;
public final Runnable r;
public ThreadExecutor(Consumer<Throwable> c, Runnable r) {
super();
this.c = c;
this.r = r;
}
@Override
public void run() {
try {
r.run();
c.accept(null);
} catch (Throwable t) {
c.accept(t);
}
}
}

View File

@ -22,7 +22,6 @@ import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
@ -41,8 +40,7 @@ public class ZipEngine implements Closeable {
ZipOutputStream zos;
public ZipEngine(File f) throws IOException {
FileOutputStream os = new FileOutputStream(f);
zos = new ZipOutputStream(new BufferedOutputStream(os));
zos = new ZipOutputStream(new BufferedOutputStream(FileUtils.openOutputStream(f)));
}
@Override
@ -51,10 +49,6 @@ public class ZipEngine implements Closeable {
zos.close();
}
public void putDirectory(String sourceDir) throws IOException {
putDirectory(new File(sourceDir), null);
}
public void putDirectory(File sourceDir) throws IOException {
putDirectory(sourceDir, null);
}
@ -117,7 +111,7 @@ public class ZipEngine implements Closeable {
}
public void putFile(File file, String pathName) throws IOException {
try (FileInputStream fis = new FileInputStream(file)) {
try (FileInputStream fis = FileUtils.openInputStream(file)) {
putStream(fis, pathName);
}
}

View File

@ -1,46 +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.io.File;
import org.jackhuang.hellominecraft.util.system.CompressingUtils;
/**
*
* @author huangyuhui
*/
public class DecompressTask extends Task {
File src, dest;
public DecompressTask(File src, File dest) {
this.src = src;
this.dest = dest;
}
@Override
public void executeTask(boolean areDependTasksSucceeded) throws Throwable {
CompressingUtils.unzip(src, dest);
}
@Override
public String getInfo() {
return "Decompress: " + src.getAbsolutePath() + " to " + dest.getAbsolutePath();
}
}

View File

@ -22,6 +22,7 @@ package org.jackhuang.hellominecraft.util.tasks;
* @author huangyuhui
*/
public class NoShownTaskException extends RuntimeException {
private static final long serialVersionUID = 4893571368018439312L;
public NoShownTaskException(String msg) {
super(msg);

View File

@ -18,7 +18,6 @@
package org.jackhuang.hellominecraft.util.tasks;
import java.util.Collection;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
/**
*
@ -102,14 +101,10 @@ public abstract class Task {
return this;
}
public Task after(Task t) {
public Task with(Task t) {
return new DoubleTask(this, t);
}
public Task before(Task t) {
return new DoubleTask(t, this);
}
public void runWithException() throws Throwable {
Collection<Task> c = getDependTasks();
if (c != null)
@ -121,14 +116,4 @@ public abstract class Task {
for (Task t : c)
t.runWithException();
}
public boolean run() {
try {
runWithException();
return true;
} catch (Throwable t) {
HMCLog.err("Failed to execute task", t);
return false;
}
}
}

View File

@ -40,7 +40,7 @@ public class TaskList extends Thread {
List<Task> taskQueue = Collections.synchronizedList(new LinkedList<>());
public final EventHandler<Object> doneEvent = new EventHandler<>(this);
ArrayList<DoingDoneListener<Task>> taskListener = new ArrayList();
ArrayList<DoingDoneListener<Task>> taskListener = new ArrayList<>();
int totTask;
boolean shouldContinue = true;
@ -49,11 +49,6 @@ public class TaskList extends Thread {
setDaemon(true);
}
public void clean() {
shouldContinue = true;
taskQueue.clear();
}
public void addTaskListener(DoingDoneListener<Task> l) {
taskListener.add(l);
}

View File

@ -44,7 +44,7 @@ public class TaskWindow extends javax.swing.JDialog
boolean suc = false;
private transient TaskList taskList;
private final ArrayList<String> failReasons = new ArrayList();
private final ArrayList<String> failReasons = new ArrayList<>();
private String stackTrace = null, lastStackTrace = null;
/**
@ -299,7 +299,6 @@ public class TaskWindow extends javax.swing.JDialog
public static class TaskWindowFactory {
LinkedList<Task> ll = new LinkedList<>();
boolean flag;
public TaskWindowFactory append(Task ts) {
if (ts != null)

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