This commit is contained in:
huanghongxun
2015-11-22 16:07:39 +08:00
parent 159a992081
commit 2dede7dea1
33 changed files with 239 additions and 402 deletions

View File

@@ -18,6 +18,7 @@ package org.jackhuang.hellominecraft.launcher;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
@@ -128,11 +129,22 @@ public final class Launcher {
System.err.println(advice); System.err.println(advice);
System.err.println(trace); System.err.println(trace);
LogWindow.instance.setVisible(true); LogWindow.instance.setVisible(true);
flag = 1; flag = 1;
} }
println("*** Game Exited ***"); println("*** Game Exited ***");
System.exit(flag); System.exit(flag);
} }
static Object getShutdownHaltLock() {
try {
Class z = Class.forName("java.lang.Shutdown");
Field haltLock = z.getDeclaredField("haltLock");
haltLock.setAccessible(true);
return haltLock.get(null);
} catch (Throwable ex) {
ex.printStackTrace();
return new Object();
}
}
} }

View File

@@ -23,7 +23,9 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.Authenticator; import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication; import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
@@ -57,6 +59,7 @@ import org.jackhuang.hellominecraft.launcher.views.MainFrame;
import org.jackhuang.hellominecraft.lookandfeel.HelloMinecraftLookAndFeel; import org.jackhuang.hellominecraft.lookandfeel.HelloMinecraftLookAndFeel;
import org.jackhuang.hellominecraft.tasks.TaskWindow; import org.jackhuang.hellominecraft.tasks.TaskWindow;
import org.jackhuang.hellominecraft.utils.ArrayUtils; import org.jackhuang.hellominecraft.utils.ArrayUtils;
import org.jackhuang.hellominecraft.utils.MathUtils;
import org.jackhuang.hellominecraft.utils.system.MessageBox; import org.jackhuang.hellominecraft.utils.system.MessageBox;
import org.jackhuang.hellominecraft.utils.StrUtils; import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.utils.VersionNumber; import org.jackhuang.hellominecraft.utils.VersionNumber;
@@ -104,6 +107,7 @@ public final class Main implements Runnable {
public static String launcherName = "Hello Minecraft! Launcher"; public static String launcherName = "Hello Minecraft! Launcher";
public static byte firstVer = 2, secondVer = 3, thirdVer = 5, forthVer = 5; public static byte firstVer = 2, secondVer = 3, thirdVer = 5, forthVer = 5;
public static int minimumLauncherVersion = 16; public static int minimumLauncherVersion = 16;
public static Proxy PROXY;
/** /**
* Make the version of HMCL. * Make the version of HMCL.
@@ -125,6 +129,7 @@ public final class Main implements Runnable {
public static final Main INSTANCE = new Main(); public static final Main INSTANCE = new Main();
@SuppressWarnings( {"CallToPrintStackTrace", "UseSpecificCatch"})
public static void main(String[] args) { public static void main(String[] args) {
{ {
if (!ArrayUtils.contains(args, "nofound")) if (!ArrayUtils.contains(args, "nofound"))
@@ -183,7 +188,7 @@ public final class Main implements Runnable {
Settings.UPDATE_CHECKER.start(); Settings.UPDATE_CHECKER.start();
if (StrUtils.isNotBlank(Settings.getInstance().getProxyHost()) && StrUtils.isNotBlank(Settings.getInstance().getProxyPort())) { if (StrUtils.isNotBlank(Settings.getInstance().getProxyHost()) && StrUtils.isNotBlank(Settings.getInstance().getProxyPort()) && MathUtils.canParseInt(Settings.getInstance().getProxyPort())) {
System.setProperty("http.proxyHost", Settings.getInstance().getProxyHost()); System.setProperty("http.proxyHost", Settings.getInstance().getProxyHost());
System.setProperty("http.proxyPort", Settings.getInstance().getProxyPort()); System.setProperty("http.proxyPort", Settings.getInstance().getProxyPort());
if (StrUtils.isNotBlank(Settings.getInstance().getProxyUserName()) && StrUtils.isNotBlank(Settings.getInstance().getProxyPassword())) if (StrUtils.isNotBlank(Settings.getInstance().getProxyUserName()) && StrUtils.isNotBlank(Settings.getInstance().getProxyPassword()))
@@ -193,6 +198,9 @@ public final class Main implements Runnable {
return new PasswordAuthentication(Settings.getInstance().getProxyUserName(), Settings.getInstance().getProxyPassword().toCharArray()); return new PasswordAuthentication(Settings.getInstance().getProxyUserName(), Settings.getInstance().getProxyPassword().toCharArray());
} }
}); });
PROXY = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Settings.getInstance().getProxyHost(), Integer.parseInt(Settings.getInstance().getProxyPort())));
} else {
PROXY = Proxy.NO_PROXY;
} }
try { try {

View File

@@ -30,6 +30,7 @@ import org.jackhuang.hellominecraft.launcher.utils.auth.LoginInfo;
import org.jackhuang.hellominecraft.launcher.utils.auth.UserProfileProvider; import org.jackhuang.hellominecraft.launcher.utils.auth.UserProfileProvider;
import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType; import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
import org.jackhuang.hellominecraft.launcher.settings.Profile; import org.jackhuang.hellominecraft.launcher.settings.Profile;
import org.jackhuang.hellominecraft.launcher.utils.auth.AuthenticationException;
import org.jackhuang.hellominecraft.utils.system.FileUtils; import org.jackhuang.hellominecraft.utils.system.FileUtils;
import org.jackhuang.hellominecraft.utils.system.IOUtils; import org.jackhuang.hellominecraft.utils.system.IOUtils;
import org.jackhuang.hellominecraft.utils.system.JavaProcess; import org.jackhuang.hellominecraft.utils.system.JavaProcess;
@@ -77,20 +78,10 @@ public class GameLauncher {
result = login.login(info); result = login.login(info);
else else
result = login.loginBySettings(); result = login.loginBySettings();
} catch (Exception e) { if (result == null) throw new AuthenticationException("Result can not be null.");
HMCLog.err("An exception has thrown when logging in.", e); } catch (Throwable e) {
result = new UserProfileProvider(); String error = C.i18n("login.failed") + e.getMessage();
result.setSuccess(false); HMCLog.warn("Login failed by method: " + login.getName(), e);
result.setErrorReason(e.getLocalizedMessage());
}
if (result == null || result.isSuccessful() == false) {
String error;
if (result == null || result.getErrorReason() == null)
error = C.i18n("login.failed");
else {
error = C.i18n("login.failed") + result.getErrorReason();
HMCLog.warn("Login failed by method: " + login.getName() + ", state: " + result.isSuccessful() + ", error reason: " + result.getErrorReason());
}
failEvent.execute(error); failEvent.execute(error);
return null; return null;
} }

View File

@@ -130,7 +130,7 @@ public final class Settings {
} }
public static Collection<Profile> getProfilesFiltered() { public static Collection<Profile> getProfilesFiltered() {
return CollectionUtils.sortOut(getProfiles().values(), (t) -> t != null && t.getName() != null); return CollectionUtils.map(getProfiles().values(), (t) -> t != null && t.getName() != null);
} }
public static Profile getOneProfile() { public static Profile getOneProfile() {

View File

@@ -16,6 +16,7 @@
*/ */
package org.jackhuang.hellominecraft.launcher.utils; package org.jackhuang.hellominecraft.launcher.utils;
import java.io.IOException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
@@ -120,7 +121,12 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
new Thread(() -> { new Thread(() -> {
HashMap<String, String> map = new HashMap<>(); HashMap<String, String> map = new HashMap<>();
map.put("CrashReport", text); map.put("CrashReport", text);
try {
System.out.println(NetUtils.post(NetUtils.constantURL("http://huangyuhui.duapp.com/crash.php"), map)); System.out.println(NetUtils.post(NetUtils.constantURL("http://huangyuhui.duapp.com/crash.php"), map));
} catch (IOException ex) {
System.out.println("Failed to send post request to HMCL server.");
ex.printStackTrace();
}
}).start(); }).start();
} }

View File

@@ -329,7 +329,7 @@ public final class MCUtils {
} }
public static MinecraftRemoteVersions getRemoteMinecraftVersions(DownloadType sourceType) throws IOException { public static MinecraftRemoteVersions getRemoteMinecraftVersions(DownloadType sourceType) throws IOException {
String result = NetUtils.doGet(sourceType.getProvider().getVersionsListDownloadURL()); String result = NetUtils.get(sourceType.getProvider().getVersionsListDownloadURL());
return MinecraftRemoteVersions.fromJson(result); return MinecraftRemoteVersions.fromJson(result);
} }

View File

@@ -1,4 +1,4 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil; package org.jackhuang.hellominecraft.launcher.utils.auth;
public class AuthenticationException extends Exception { public class AuthenticationException extends Exception {

View File

@@ -16,6 +16,7 @@
*/ */
package org.jackhuang.hellominecraft.launcher.utils.auth; package org.jackhuang.hellominecraft.launcher.utils.auth;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.Socket; import java.net.Socket;
@@ -32,7 +33,7 @@ public final class BestLogin extends IAuthenticator {
} }
@Override @Override
public UserProfileProvider login(LoginInfo info) { public UserProfileProvider login(LoginInfo info) throws AuthenticationException {
try { try {
String request = "bl:l:" + info.username + ":" + DigestUtils.sha1Hex(info.password); String request = "bl:l:" + info.username + ":" + DigestUtils.sha1Hex(info.password);
@@ -42,34 +43,25 @@ public final class BestLogin extends IAuthenticator {
os.write(request.getBytes()); os.write(request.getBytes());
UserProfileProvider lr = new UserProfileProvider(); UserProfileProvider lr = new UserProfileProvider();
lr.setSuccess(false);
InputStream is = socket.getInputStream(); InputStream is = socket.getInputStream();
int code = is.read(); int code = is.read();
switch (code) { switch (code) {
case -1: case -1:
lr.setErrorReason("internet error."); throw new AuthenticationException("internet error.");
break;
case 200: case 200:
lr.setErrorReason("server restarting."); throw new AuthenticationException("server restarting.");
break;
case 255: case 255:
lr.setErrorReason("unknown error"); throw new AuthenticationException("unknown error");
break;
case 3: case 3:
lr.setErrorReason("unregistered."); throw new AuthenticationException("unregistered.");
break;
case 50: case 50:
lr.setErrorReason("please update your launcher and act your account."); throw new AuthenticationException("please update your launcher and act your account.");
break;
case 2: case 2:
lr.setErrorReason("wrong password."); throw new AuthenticationException("wrong password.");
break;
case 100: case 100:
lr.setErrorReason("server reloading."); throw new AuthenticationException("server reloading.");
break;
case 0: case 0:
lr.setSuccess(true);
byte[] b = new byte[64]; byte[] b = new byte[64];
is.read(b, 0, b.length); is.read(b, 0, b.length);
String[] ss = new String(b).split(":"); String[] ss = new String(b).split(":");
@@ -81,11 +73,8 @@ public final class BestLogin extends IAuthenticator {
} }
lr.setUserType("Legacy"); lr.setUserType("Legacy");
return lr; return lr;
} catch (Throwable t) { } catch (IOException t) {
UserProfileProvider lr = new UserProfileProvider(); throw new AuthenticationException(t);
lr.setSuccess(false);
lr.setErrorReason(t.getMessage());
return lr;
} }
} }

View File

@@ -58,8 +58,9 @@ public abstract class IAuthenticator {
* @param info username & password * @param info username & password
* *
* @return login result * @return login result
* @throws org.jackhuang.hellominecraft.launcher.utils.auth.AuthenticationException
*/ */
public abstract UserProfileProvider login(LoginInfo info); public abstract UserProfileProvider login(LoginInfo info) throws AuthenticationException;
/** /**
* *
@@ -84,7 +85,7 @@ public abstract class IAuthenticator {
} }
public abstract UserProfileProvider loginBySettings(); public abstract UserProfileProvider loginBySettings() throws AuthenticationException;
public abstract void logout(); public abstract void logout();
} }

View File

@@ -31,16 +31,16 @@ public final class OfflineAuthenticator extends IAuthenticator {
} }
@Override @Override
public UserProfileProvider login(LoginInfo info) { public UserProfileProvider login(LoginInfo info) throws AuthenticationException {
if(StrUtils.isBlank(info.username))
throw new AuthenticationException(C.i18n("login.no_Player007"));
UserProfileProvider result = new UserProfileProvider(); UserProfileProvider result = new UserProfileProvider();
result.setSuccess(StrUtils.isNotBlank(info.username));
result.setUserName(info.username); result.setUserName(info.username);
String uuid = getUUIDFromUserName(info.username); String uuid = getUUIDFromUserName(info.username);
result.setSession(uuid); result.setSession(uuid);
result.setUserId(uuid); result.setUserId(uuid);
result.setAccessToken(uuid); result.setAccessToken(uuid);
result.setUserType("Legacy"); result.setUserType("Legacy");
result.setErrorReason(C.i18n("login.no_Player007"));
return result; return result;
} }

View File

@@ -37,21 +37,15 @@ public final class SkinmeAuthenticator extends IAuthenticator {
} }
public String getCharacter(String user, String hash, String $char) throws Exception { public String getCharacter(String user, String hash, String $char) throws Exception {
if ($char == null) return NetUtils.get(
return NetUtils.doGet( "http://www.skinme.cc/api/login.php?user=" + user + "&hash=" + hash + (($char == null) ? "" : ("&char=" + $char)));
"http://www.skinme.cc/api/login.php?user=" + user + "&hash=" + hash);
else
return NetUtils.doGet(
"http://www.skinme.cc/api/login.php?user=" + user + "&hash=" + hash + "&char=" + $char);
} }
@Override @Override
public UserProfileProvider login(LoginInfo info) { public UserProfileProvider login(LoginInfo info) throws AuthenticationException {
UserProfileProvider req = new UserProfileProvider(); UserProfileProvider req = new UserProfileProvider();
if (info.username == null || !info.username.contains("@")) { if (info.username == null || !info.username.contains("@")) {
req.setSuccess(false); throw new AuthenticationException(C.i18n("login.not_email"));
req.setErrorReason(C.i18n("login.not_email"));
return req;
} }
try { try {
String usr = info.username.toLowerCase(); String usr = info.username.toLowerCase();
@@ -64,13 +58,10 @@ public final class SkinmeAuthenticator extends IAuthenticator {
if (null != sl[0]) if (null != sl[0])
switch (sl[0]) { switch (sl[0]) {
case "0": case "0":
req.setSuccess(false);
if (sl[1].contains("No Valid Character")) if (sl[1].contains("No Valid Character"))
sl[1] = C.i18n("login.no_valid_character"); sl[1] = C.i18n("login.no_valid_character");
req.setErrorReason(sl[1]); throw new AuthenticationException(sl[1]);
break;
case "1": { case "1": {
req.setSuccess(true);
String[] s = parseType1(sl[1]); String[] s = parseType1(sl[1]);
req.setUserName(s[0]); req.setUserName(s[0]);
req.setSession(s[1]); req.setSession(s[1]);
@@ -79,7 +70,6 @@ public final class SkinmeAuthenticator extends IAuthenticator {
break; break;
} }
case "2": { case "2": {
req.setSuccess(true);
String[] charators = sl[1].split(";"); String[] charators = sl[1].split(";");
int len = charators.length; int len = charators.length;
String[] $char = new String[len]; String[] $char = new String[len];
@@ -93,8 +83,7 @@ public final class SkinmeAuthenticator extends IAuthenticator {
Selector s = new Selector(null, user, C.i18n("login.choose_charactor")); Selector s = new Selector(null, user, C.i18n("login.choose_charactor"));
s.setVisible(true); s.setVisible(true);
if (s.sel == Selector.failedToSel) { if (s.sel == Selector.failedToSel) {
req.setSuccess(false); throw new AuthenticationException(C.i18n("message.cancelled"));
req.setErrorReason(C.i18n("message.cancelled"));
} else { } else {
int index = s.sel; int index = s.sel;
String character = $char[index]; String character = $char[index];
@@ -112,13 +101,7 @@ public final class SkinmeAuthenticator extends IAuthenticator {
req.setUserType("Legacy"); req.setUserType("Legacy");
return req; return req;
} catch (Exception e) { } catch (Exception e) {
HMCLog.warn("Failed to login skinme.", e); throw new AuthenticationException(e);
req.setUserName(info.username);
req.setSuccess(false);
req.setUserType("Legacy");
req.setErrorReason(e.getMessage());
return req;
} }
} }

View File

@@ -51,17 +51,10 @@ public final class UserProfileProvider {
} }
public void setAccessToken(String accessToken) { public void setAccessToken(String accessToken) {
if (accessToken == null) accessToken = "0";
this.accessToken = accessToken; this.accessToken = accessToken;
} }
public boolean isSuccessful() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getErrorReason() { public String getErrorReason() {
return error; return error;
} }
@@ -114,7 +107,6 @@ public final class UserProfileProvider {
private String userId = ""; private String userId = "";
private String session = ""; private String session = "";
private String accessToken = ""; private String accessToken = "";
private boolean success = false;
private String error = ""; private String error = "";
private String userProperties = "{}"; private String userProperties = "{}";
private String userPropertyMap = "{}"; private String userPropertyMap = "{}";

View File

@@ -17,11 +17,10 @@
package org.jackhuang.hellominecraft.launcher.utils.auth; package org.jackhuang.hellominecraft.launcher.utils.auth;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import java.net.Proxy;
import java.util.Map; import java.util.Map;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import org.jackhuang.hellominecraft.C; import org.jackhuang.hellominecraft.C;
import org.jackhuang.hellominecraft.HMCLog; import org.jackhuang.hellominecraft.launcher.Main;
import org.jackhuang.hellominecraft.utils.ArrayUtils; import org.jackhuang.hellominecraft.utils.ArrayUtils;
import org.jackhuang.hellominecraft.views.Selector; import org.jackhuang.hellominecraft.views.Selector;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile; import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile;
@@ -39,46 +38,34 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
public YggdrasilAuthenticator(String clientToken) { public YggdrasilAuthenticator(String clientToken) {
super(clientToken); super(clientToken);
ua = new YggdrasilAuthentication(Proxy.NO_PROXY, clientToken); ua = new YggdrasilAuthentication(Main.PROXY, clientToken);
} }
@Override @Override
public UserProfileProvider login(LoginInfo info) { public UserProfileProvider login(LoginInfo info) throws AuthenticationException {
if (ua.canPlayOnline()) {
UserProfileProvider result = new UserProfileProvider(); UserProfileProvider result = new UserProfileProvider();
result.setUserName(info.username);
result.setSuccess(true);
result.setUserId(UUIDTypeAdapter.fromUUID(ua.getSelectedProfile().id));
result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.LegacySerializer()).create().toJson(ua.getUserProperties()));
result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()));
result.setAccessToken(ua.getAuthenticatedToken());
result.setSession(ua.getAuthenticatedToken());
result.setUserType("mojang"); result.setUserType("mojang");
return result; if (ua.canPlayOnline()) {
} result.setUserName(info.username);
UserProfileProvider result = new UserProfileProvider(); result.setUserId(UUIDTypeAdapter.fromUUID(ua.getSelectedProfile().id));
} else {
String usr = info.username; String usr = info.username;
if (info.username == null || !info.username.contains("@")) { if (info.username == null || !info.username.contains("@"))
result.setSuccess(false); throw new AuthenticationException(C.i18n("login.not_email"));
result.setErrorReason(C.i18n("login.not_email"));
return result;
}
String pwd = info.password; String pwd = info.password;
if (!ua.isLoggedIn()) if (!ua.isLoggedIn())
ua.setPassword(pwd); ua.setPassword(pwd);
ua.setUsername(usr); ua.setUsername(usr);
try {
ua.logIn(); ua.logIn();
if (!ua.isLoggedIn()) if (!ua.isLoggedIn())
throw new Exception(C.i18n("login.wrong_password")); throw new AuthenticationException(C.i18n("login.wrong_password"));
GameProfile selectedProfile = ua.getSelectedProfile(); GameProfile selectedProfile = ua.getSelectedProfile();
GameProfile[] profiles = ua.getAvailableProfiles(); GameProfile[] profiles = ua.getAvailableProfiles();
String[] names;
String username; String username;
if (selectedProfile == null) if (selectedProfile == null)
if (ArrayUtils.isNotEmpty(profiles)) { if (ArrayUtils.isNotEmpty(profiles)) {
names = new String[profiles.length]; String[] names = new String[profiles.length];
for (int i = 0; i < profiles.length; i++) for (int i = 0; i < profiles.length; i++)
names[i] = profiles[i].name; names[i] = profiles[i].name;
Selector s = new Selector(null, names, C.i18n("login.choose_charactor")); Selector s = new Selector(null, names, C.i18n("login.choose_charactor"));
@@ -90,23 +77,12 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
else else
username = selectedProfile.name; username = selectedProfile.name;
result.setUserName(username); result.setUserName(username);
result.setSuccess(true);
result.setUserId(selectedProfile == null ? OfflineAuthenticator.getUUIDFromUserName(username) : UUIDTypeAdapter.fromUUID(selectedProfile.id)); result.setUserId(selectedProfile == null ? OfflineAuthenticator.getUUIDFromUserName(username) : UUIDTypeAdapter.fromUUID(selectedProfile.id));
}
result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.LegacySerializer()).create().toJson(ua.getUserProperties())); result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.LegacySerializer()).create().toJson(ua.getUserProperties()));
result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties())); result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()));
String authToken = ua.getAuthenticatedToken(); result.setAccessToken(ua.getAuthenticatedToken());
if (authToken == null) result.setSession(ua.getAuthenticatedToken());
authToken = "0";
result.setAccessToken(authToken);
result.setSession(authToken);
} catch (Exception ex) {
result.setErrorReason(ex.getMessage());
result.setSuccess(false);
result.setUserName(ua.getUserID());
HMCLog.err("Failed to login by yggdrasil authentication.", ex);
}
result.setUserType("mojang");
return result; return result;
} }
@@ -131,23 +107,19 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
} }
@Override @Override
public UserProfileProvider loginBySettings() { public UserProfileProvider loginBySettings() throws AuthenticationException {
UserProfileProvider info = new UserProfileProvider(); UserProfileProvider result = new UserProfileProvider();
try {
ua.logIn(); ua.logIn();
if (!ua.isLoggedIn()) if (!ua.isLoggedIn())
throw new Exception(C.i18n("login.wrong_password")); throw new AuthenticationException(C.i18n("login.wrong_password"));
GameProfile profile = ua.getSelectedProfile(); GameProfile profile = ua.getSelectedProfile();
info.setUserName(profile.name); result.setUserName(profile.name);
info.setSuccess(true); result.setUserId(profile.id.toString());
info.setUserId(profile.id.toString()); result.setUserProperties(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.LegacySerializer()).create().toJson(ua.getUserProperties()));
info.setAccessToken(ua.getAuthenticatedToken()); result.setUserPropertyMap(new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(ua.getUserProperties()));
} catch (Exception ex) { result.setAccessToken(ua.getAuthenticatedToken());
info.setErrorReason(ex.getMessage()); result.setSession(ua.getAuthenticatedToken());
info.setSuccess(false); return result;
info.setUserName(ua.getUserID());
}
return info;
} }
@Override @Override

View File

@@ -31,6 +31,7 @@ public class GameProfile {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
System.out.println("hello?");
if (this == o) if (this == o)
return true; return true;
if (o == null || getClass() != o.getClass()) if (o == null || getClass() != o.getClass())
@@ -43,13 +44,6 @@ public class GameProfile {
return name != null ? name.equals(that.name) : that.name == null; return name != null ? name.equals(that.name) : that.name == null;
} }
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
public static class GameProfileSerializer implements JsonSerializer<GameProfile>, JsonDeserializer<GameProfile> { public static class GameProfileSerializer implements JsonSerializer<GameProfile>, JsonDeserializer<GameProfile> {
@Override @Override

View File

@@ -1,7 +1,5 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil; package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
import org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil.GameProfile;
public class Response { public class Response {
public String accessToken, clientToken; public String accessToken, clientToken;

View File

@@ -1,5 +1,6 @@
package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil; package org.jackhuang.hellominecraft.launcher.utils.auth.yggdrasil;
import org.jackhuang.hellominecraft.launcher.utils.auth.AuthenticationException;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
@@ -62,65 +63,22 @@ public class YggdrasilAuthentication {
this.password = password; this.password = password;
} }
protected String getUsername() {
return this.username;
}
protected String getPassword() {
return this.password;
}
protected void setSelectedProfile(GameProfile selectedProfile) {
this.selectedProfile = selectedProfile;
}
public GameProfile getSelectedProfile() { public GameProfile getSelectedProfile() {
return this.selectedProfile; return this.selectedProfile;
} }
public String getUserID() { public String getUserId() {
return this.userid; return this.userid;
} }
public PropertyMap getUserProperties() { public PropertyMap getUserProperties() {
if (isLoggedIn()) { if (isLoggedIn())
PropertyMap result = new PropertyMap(); return (PropertyMap) userProperties.clone();
result.putAll(getModifiableUserProperties());
return result;
}
return new PropertyMap(); return new PropertyMap();
} }
protected PropertyMap getModifiableUserProperties() {
return this.userProperties;
}
protected void updateUserProperties(User user) {
if (user != null && user.properties != null)
getModifiableUserProperties().putAll(user.properties);
}
protected void setUserId(String userid) {
this.userid = userid;
}
public Proxy getProxy() {
return this.proxy;
}
public String getClientToken() {
return this.clientToken;
}
public GameProfile[] getAvailableProfiles() { public GameProfile[] getAvailableProfiles() {
return this.profiles; return profiles;
}
@Deprecated
public String getSessionToken() {
if (isLoggedIn() && getSelectedProfile() != null && canPlayOnline())
return String.format("token:%s:%s", new Object[] {getAuthenticatedToken(), getSelectedProfile().id});
return null;
} }
public String getAuthenticatedToken() { public String getAuthenticatedToken() {
@@ -134,7 +92,7 @@ public class YggdrasilAuthentication {
} }
public boolean canLogIn() { public boolean canLogIn() {
return !canPlayOnline() && StrUtils.isNotBlank(getUsername()) && (StrUtils.isNotBlank(getPassword()) || StrUtils.isNotBlank(getAuthenticatedToken())); return !canPlayOnline() && StrUtils.isNotBlank(username) && (StrUtils.isNotBlank(password) || StrUtils.isNotBlank(getAuthenticatedToken()));
} }
public boolean isLoggedIn() { public boolean isLoggedIn() {
@@ -142,69 +100,62 @@ public class YggdrasilAuthentication {
} }
public void logIn() throws AuthenticationException { public void logIn() throws AuthenticationException {
if (StrUtils.isBlank(getUsername())) if (StrUtils.isBlank(username))
throw new AuthenticationException(C.i18n("login.invalid_username")); throw new AuthenticationException(C.i18n("login.invalid_username"));
if (StrUtils.isNotBlank(getAuthenticatedToken())) if (StrUtils.isNotBlank(getAuthenticatedToken())) {
logInWithToken(); if (StrUtils.isBlank(getUserId()))
else if (StrUtils.isNotBlank(getPassword())) if (StrUtils.isNotBlank(username))
logInWithPassword(); userid = username;
else
throw new AuthenticationException(C.i18n("login.invalid_uuid_and_username"));
loggedIn(ROUTE_REFRESH, new RefreshRequest(getAuthenticatedToken(), clientToken));
} else if (StrUtils.isNotBlank(password))
loggedIn(ROUTE_AUTHENTICATE, new AuthenticationRequest(username, password, clientToken));
else else
throw new AuthenticationException(C.i18n("login.invalid_password")); throw new AuthenticationException(C.i18n("login.invalid_password"));
} }
private void logInWithPassword() throws AuthenticationException { private void loggedIn(URL url, Object input) throws AuthenticationException {
Response response = request(ROUTE_AUTHENTICATE, new AuthenticationRequest(getUsername(), getPassword(), clientToken)); try {
if (!response.clientToken.equals(clientToken)) String jsonResult = input == null ? NetUtils.get(url) : NetUtils.post(url, GSON.toJson(input), "application/json", proxy);
throw new AuthenticationException(C.i18n("login.changed_client_token")); Response response = (Response) GSON.fromJson(jsonResult, Response.class);
User user = response.user; if (StrUtils.isNotBlank(response.error))
setUserId(user != null && user.id != null ? user.id : getUsername()); throw new AuthenticationException("Request error: " + response.errorMessage);
this.isOnline = true;
this.accessToken = response.accessToken;
this.profiles = response.availableProfiles;
setSelectedProfile(response.selectedProfile);
getModifiableUserProperties().clear();
updateUserProperties(user);
}
protected void logInWithToken() throws AuthenticationException {
if (StrUtils.isBlank(getUserID()))
if (StrUtils.isBlank(getUsername()))
setUserId(getUsername());
else
throw new AuthenticationException(C.i18n("login.invalid_uuid_and_username"));
Response response = request(ROUTE_REFRESH, new RefreshRequest(getAuthenticatedToken(), getClientToken()));
if (!clientToken.equals(response.clientToken)) if (!clientToken.equals(response.clientToken))
throw new AuthenticationException(C.i18n("login.changed_client_token")); throw new AuthenticationException(C.i18n("login.changed_client_token"));
setUserId(response.user != null && response.user.id != null ? response.user.id : getUsername()); User user = response.user;
userid = user != null && user.id != null ? user.id : username;
this.isOnline = true; isOnline = true;
profiles = response.availableProfiles;
selectedProfile = response.selectedProfile;
userProperties.clear();
this.accessToken = response.accessToken; this.accessToken = response.accessToken;
this.profiles = response.availableProfiles;
setSelectedProfile(response.selectedProfile);
getModifiableUserProperties().clear();
updateUserProperties(response.user); if (user != null && user.properties != null)
userProperties.putAll(user.properties);
} catch (IOException | IllegalStateException | JsonParseException e) {
throw new AuthenticationException(C.i18n("login.failed.connect_authentication_server"), e);
}
} }
public void logOut() { public void logOut() {
this.password = null; password = null;
this.userid = null; userid = null;
setSelectedProfile(null); selectedProfile = null;
getModifiableUserProperties().clear(); userProperties.clear();
this.accessToken = null; accessToken = null;
this.profiles = null; profiles = null;
this.isOnline = false; isOnline = false;
} }
// </editor-fold>
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Settings Storage"> // <editor-fold defaultstate="collapsed" desc="Settings Storage">
public void loadFromStorage(Map<String, Object> credentials) { public void loadFromStorage(Map<String, Object> credentials) {
logOut(); logOut();
@@ -212,18 +163,18 @@ public class YggdrasilAuthentication {
setUsername((String) credentials.get(STORAGE_KEY_USER_NAME)); setUsername((String) credentials.get(STORAGE_KEY_USER_NAME));
if (credentials.containsKey(STORAGE_KEY_USER_ID)) if (credentials.containsKey(STORAGE_KEY_USER_ID))
this.userid = (String) credentials.get(STORAGE_KEY_USER_ID); userid = (String) credentials.get(STORAGE_KEY_USER_ID);
else else
this.userid = this.username; userid = username;
if (credentials.containsKey(STORAGE_KEY_USER_PROPERTIES)) if (credentials.containsKey(STORAGE_KEY_USER_PROPERTIES))
getModifiableUserProperties().fromList((List<Map<String, String>>) credentials.get(STORAGE_KEY_USER_PROPERTIES)); userProperties.fromList((List<Map<String, String>>) credentials.get(STORAGE_KEY_USER_PROPERTIES));
if ((credentials.containsKey(STORAGE_KEY_PROFILE_NAME)) && (credentials.containsKey(STORAGE_KEY_PROFILE_ID))) { if ((credentials.containsKey(STORAGE_KEY_PROFILE_NAME)) && (credentials.containsKey(STORAGE_KEY_PROFILE_ID))) {
GameProfile profile = new GameProfile(UUIDTypeAdapter.fromString((String) credentials.get(STORAGE_KEY_PROFILE_ID)), (String) credentials.get(STORAGE_KEY_PROFILE_NAME)); GameProfile profile = new GameProfile(UUIDTypeAdapter.fromString((String) credentials.get(STORAGE_KEY_PROFILE_ID)), (String) credentials.get(STORAGE_KEY_PROFILE_NAME));
if (credentials.containsKey(STORAGE_KEY_PROFILE_PROPERTIES)) if (credentials.containsKey(STORAGE_KEY_PROFILE_PROPERTIES))
profile.properties.fromList((List<Map<String, String>>) credentials.get(STORAGE_KEY_PROFILE_PROPERTIES)); profile.properties.fromList((List<Map<String, String>>) credentials.get(STORAGE_KEY_PROFILE_PROPERTIES));
setSelectedProfile(profile); selectedProfile = profile;
} }
this.accessToken = (String) credentials.get(STORAGE_KEY_ACCESS_TOKEN); this.accessToken = (String) credentials.get(STORAGE_KEY_ACCESS_TOKEN);
@@ -232,10 +183,10 @@ public class YggdrasilAuthentication {
public Map<String, Object> saveForStorage() { public Map<String, Object> saveForStorage() {
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
if (getUsername() != null) if (username != null)
result.put(STORAGE_KEY_USER_NAME, getUsername()); result.put(STORAGE_KEY_USER_NAME, username);
if (getUserID() != null) if (getUserId() != null)
result.put(STORAGE_KEY_USER_ID, getUserID()); result.put(STORAGE_KEY_USER_ID, getUserId());
if (!getUserProperties().isEmpty()) if (!getUserProperties().isEmpty())
result.put(STORAGE_KEY_USER_PROPERTIES, getUserProperties().list()); result.put(STORAGE_KEY_USER_PROPERTIES, getUserProperties().list());
@@ -255,20 +206,4 @@ public class YggdrasilAuthentication {
} }
// </editor-fold> // </editor-fold>
protected Response request(URL url, Object input) throws AuthenticationException {
try {
String jsonResult = input == null ? NetUtils.doGet(url) : NetUtils.post(url, GSON.toJson(input), "application/json", proxy);
Response result = (Response) GSON.fromJson(jsonResult, Response.class);
if (result == null)
return null;
if (StrUtils.isNotBlank(result.error))
throw new AuthenticationException("InvalidCredentials " + result.errorMessage);
return result;
} catch (IOException | IllegalStateException | JsonParseException e) {
throw new AuthenticationException(C.i18n("login.failed.connect_authentication_server"), e);
}
}
} }

View File

@@ -58,7 +58,7 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
for (String x : neededVersions) { for (String x : neededVersions) {
if (versionMap.containsKey(x)) if (versionMap.containsKey(x))
continue; continue;
String s = NetUtils.doGet("http://bmclapi2.bangbang93.com/forge/minecraft/" + x); String s = NetUtils.get("http://bmclapi2.bangbang93.com/forge/minecraft/" + x);
if (s == null) if (s == null)
continue; continue;

View File

@@ -48,7 +48,7 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] needed) throws Exception { public void refreshList(String[] needed) throws Exception {
String s = NetUtils.doGet(Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(C.URL_FORGE_LIST)); String s = NetUtils.get(Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(C.URL_FORGE_LIST));
if (root != null) if (root != null)
return; return;

View File

@@ -50,7 +50,7 @@ public class LiteLoaderVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] needed) throws Exception { public void refreshList(String[] needed) throws Exception {
String s = NetUtils.doGet(C.URL_LITELOADER_LIST); String s = NetUtils.get(C.URL_LITELOADER_LIST);
if (root != null) if (root != null)
return; return;

View File

@@ -51,7 +51,7 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] needed) throws Exception { public void refreshList(String[] needed) throws Exception {
String s = NetUtils.doGet("http://bmclapi.bangbang93.com/optifine/versionlist"); String s = NetUtils.get("http://bmclapi.bangbang93.com/optifine/versionlist");
versionMap = new HashMap<>(); versionMap = new HashMap<>();
versions = new ArrayList<>(); versions = new ArrayList<>();

View File

@@ -38,7 +38,7 @@ public class OptiFineDownloadFormatter extends Task implements PreviousResult<St
@Override @Override
public boolean executeTask() { public boolean executeTask() {
try { try {
String content = NetUtils.doGet(url); String content = NetUtils.get(url);
Pattern p = Pattern.compile("\"downloadx\\?f=OptiFine(.*)\""); Pattern p = Pattern.compile("\"downloadx\\?f=OptiFine(.*)\"");
Matcher m = p.matcher(content); Matcher m = p.matcher(content);
while (m.find()) while (m.find())

View File

@@ -59,7 +59,7 @@ public class OptiFineVersionList extends InstallerVersionList {
@Override @Override
public void refreshList(String[] sss) throws Exception { public void refreshList(String[] sss) throws Exception {
String content = NetUtils.doGet("http://optifine.net/downloads"); String content = NetUtils.get("http://optifine.net/downloads");
if (versions != null) if (versions != null)
return; return;
versionMap = new HashMap<>(); versionMap = new HashMap<>();

View File

@@ -373,7 +373,7 @@ public final class MainFrame extends DraggableFrame {
} }
public void invokeUpdate() { public void invokeUpdate() {
defaultTitle = defaultTitle + C.i18n("update.found"); defaultTitle = Main.makeTitle() + C.i18n("update.found");
if (!isShowedMessage) { if (!isShowedMessage) {
windowTitle.setText(defaultTitle); windowTitle.setText(defaultTitle);
windowTitle.setForeground(Color.red); windowTitle.setForeground(Color.red);

View File

@@ -33,7 +33,7 @@ public final class CollectionUtils {
p.accept(t); p.accept(t);
} }
public static <T> Collection<T> sortOut(Collection<T> coll, Predicate<T> p) { public static <T> ArrayList<T> map(Collection<T> coll, Predicate<T> p) {
ArrayList<T> newColl = new ArrayList<>(); ArrayList<T> newColl = new ArrayList<>();
forEach(coll, t -> { forEach(coll, t -> {
if (p.apply(t)) if (p.apply(t))

View File

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.utils; package org.jackhuang.hellominecraft.utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -26,7 +25,6 @@ import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.Proxy; import java.net.Proxy;
import java.net.URL; import java.net.URL;
import java.net.URLConnection;
import java.util.Map; import java.util.Map;
import org.jackhuang.hellominecraft.HMCLog; import org.jackhuang.hellominecraft.HMCLog;
import org.jackhuang.hellominecraft.utils.system.IOUtils; import org.jackhuang.hellominecraft.utils.system.IOUtils;
@@ -63,64 +61,23 @@ public final class NetUtils {
return sb.toString(); return sb.toString();
} }
public static String doGet(String url, String encoding) throws IOException { public static String get(String url, String encoding) throws IOException {
return getStreamContent(new URL(url).openConnection().getInputStream()); return getStreamContent(new URL(url).openConnection().getInputStream());
} }
public static String doGet(String url) throws IOException { public static String get(String url) throws IOException {
return doGet(url, DEFAULT_CHARSET); return get(url, DEFAULT_CHARSET);
} }
public static String doGet(URL url) throws IOException { public static String get(URL url) throws IOException {
return doGet(url, Proxy.NO_PROXY); return get(url, Proxy.NO_PROXY);
} }
public static String doGet(URL url, Proxy proxy) throws IOException { public static String get(URL url, Proxy proxy) throws IOException {
return getStreamContent(url.openConnection(proxy).getInputStream()); return getStreamContent(url.openConnection(proxy).getInputStream());
} }
/** public static String post(URL u, Map<String, String> params) throws IOException {
* Sends an HTTP GET request to a url
*
* @param endpoint - The URL of the server. (Example: "
* http://www.yahoo.com/search")
* @param requestParameters - all the request parameters (Example:
* "param1=val1&param2=val2"). Note: This method will add the question mark
* (?) to the request - DO NOT add it yourself
*
* @return - The response from the end point
*/
public static String sendGetRequest(String endpoint,
String requestParameters) {
String result = null;
if (endpoint.startsWith("http://"))
// Send a GET request to the servlet
try {
// Construct data
StringBuilder data = new StringBuilder();
// Send data
String urlStr = endpoint;
if (requestParameters != null && requestParameters.length() > 0)
urlStr += "?" + requestParameters;
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
// Get the response
InputStreamReader r = new InputStreamReader(conn.getInputStream());
StringBuffer sb;
BufferedReader rd = new BufferedReader(r);
sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null)
sb.append(line);
result = sb.toString();
} catch (Exception e) {
HMCLog.warn("Failed to send get request.", e);
}
return result;
}
public static String post(URL u, Map<String, String> params) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (params != null) { if (params != null) {
for (Map.Entry<String, String> e : params.entrySet()) { for (Map.Entry<String, String> e : params.entrySet()) {
@@ -134,18 +91,17 @@ public final class NetUtils {
return post(u, sb.toString()); return post(u, sb.toString());
} }
public static String post(URL u, String post) { public static String post(URL u, String post) throws IOException {
return post(u, post, "application/x-www-form-urlencoded"); return post(u, post, "application/x-www-form-urlencoded");
} }
public static String post(URL u, String post, String contentType) { public static String post(URL u, String post, String contentType) throws IOException {
return post(u, post, contentType, Proxy.NO_PROXY); return post(u, post, contentType, Proxy.NO_PROXY);
} }
public static String post(URL u, String post, String contentType, Proxy proxy) { public static String post(URL u, String post, String contentType, Proxy proxy) throws IOException {
try {
HttpURLConnection con = (HttpURLConnection) u.openConnection(proxy); HttpURLConnection con = (HttpURLConnection) u.openConnection(proxy);
con.setRequestMethod(METHOD_POST); con.setRequestMethod("POST");
con.setDoOutput(true); con.setDoOutput(true);
con.setDoInput(true); con.setDoInput(true);
con.setUseCaches(false); con.setUseCaches(false);
@@ -162,7 +118,7 @@ public final class NetUtils {
IOUtils.closeQuietly(os); IOUtils.closeQuietly(os);
} }
String result = null; String result;
InputStream is = null; InputStream is = null;
try { try {
is = con.getInputStream(); is = con.getInputStream();
@@ -176,12 +132,8 @@ public final class NetUtils {
con.disconnect(); con.disconnect();
return result; return result;
} catch (Exception e) {
HMCLog.warn("Failed to post.", e);
return null;
} }
}
private static final String METHOD_POST = "POST";
private static final String DEFAULT_CHARSET = "UTF-8"; private static final String DEFAULT_CHARSET = "UTF-8";
public static URL constantURL(String url) { public static URL constantURL(String url) {

View File

@@ -47,7 +47,7 @@ public final class UpdateChecker extends Thread {
public void run() { public void run() {
try { try {
versionString = NetUtils.doGet("http://huangyuhui.duapp.com/info.php?type=" + type); versionString = NetUtils.get("http://huangyuhui.duapp.com/info.php?type=" + type);
} catch (Exception e) { } catch (Exception e) {
HMCLog.warn("Failed to get update url.", e); HMCLog.warn("Failed to get update url.", e);
return; return;
@@ -75,7 +75,7 @@ public final class UpdateChecker extends Thread {
new Thread(() -> { new Thread(() -> {
if (download_link == null) if (download_link == null)
try { try {
download_link = C.gson.fromJson(NetUtils.doGet("http://huangyuhui.duapp.com/update_link.php?type=" + type), Map.class); download_link = C.gson.fromJson(NetUtils.get("http://huangyuhui.duapp.com/update_link.php?type=" + type), Map.class);
} catch (Exception e) { } catch (Exception e) {
HMCLog.warn("Failed to get update link.", e); HMCLog.warn("Failed to get update link.", e);
} }

View File

@@ -69,7 +69,7 @@ public class JavaProcessMonitor {
void processThreadStopped(ProcessThread t, boolean forceTermintate) { void processThreadStopped(ProcessThread t, boolean forceTermintate) {
al.remove(t); al.remove(t);
al.removeAll(CollectionUtils.sortOut(al, t1 -> !t1.isAlive())); al.removeAll(CollectionUtils.map(al, t1 -> !t1.isAlive()));
if (al.isEmpty() || forceTermintate) { if (al.isEmpty() || forceTermintate) {
for (Thread a : al) for (Thread a : al)
a.interrupt(); a.interrupt();

View File

@@ -4,7 +4,7 @@
<Properties> <Properties>
<Property name="defaultCloseOperation" type="int" value="2"/> <Property name="defaultCloseOperation" type="int" value="2"/>
<Property name="title" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor"> <Property name="title" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="logwindow.title" replaceFormat="C.I18N.getString(&quot;{key}&quot;)"/> <ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="logwindow.title" replaceFormat="C.i18n(&quot;{key}&quot;)"/>
</Property> </Property>
</Properties> </Properties>
<SyntheticProperties> <SyntheticProperties>
@@ -83,7 +83,7 @@
<Component class="javax.swing.JButton" name="btnClear"> <Component class="javax.swing.JButton" name="btnClear">
<Properties> <Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor"> <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="ui.button.clear" replaceFormat="C.I18N.getString(&quot;{key}&quot;)"/> <ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="ui.button.clear" replaceFormat="C.i18n(&quot;{key}&quot;)"/>
</Property> </Property>
</Properties> </Properties>
<Events> <Events>
@@ -93,7 +93,7 @@
<Component class="javax.swing.JButton" name="btnClose"> <Component class="javax.swing.JButton" name="btnClose">
<Properties> <Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor"> <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="ui.button.close" replaceFormat="C.I18N.getString(&quot;{key}&quot;)"/> <ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="ui.button.close" replaceFormat="C.i18n(&quot;{key}&quot;)"/>
</Property> </Property>
</Properties> </Properties>
<Events> <Events>
@@ -103,7 +103,7 @@
<Component class="javax.swing.JButton" name="btnCopy"> <Component class="javax.swing.JButton" name="btnCopy">
<Properties> <Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor"> <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="ui.button.copy" replaceFormat="C.I18N.getString(&quot;{key}&quot;)"/> <ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="ui.button.copy" replaceFormat="C.i18n(&quot;{key}&quot;)"/>
</Property> </Property>
</Properties> </Properties>
<Events> <Events>
@@ -128,7 +128,7 @@
<Component class="javax.swing.JButton" name="btnTieBa"> <Component class="javax.swing.JButton" name="btnTieBa">
<Properties> <Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor"> <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="logwindow.tieba" replaceFormat="C.I18N.getString(&quot;{key}&quot;)"/> <ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="logwindow.tieba" replaceFormat="C.i18n(&quot;{key}&quot;)"/>
</Property> </Property>
</Properties> </Properties>
<Events> <Events>
@@ -146,7 +146,7 @@
<Component class="javax.swing.JButton" name="btnTerminateGame"> <Component class="javax.swing.JButton" name="btnTerminateGame">
<Properties> <Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor"> <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="logwindow.terminate_game" replaceFormat="C.I18N.getString(&quot;{key}&quot;)"/> <ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="logwindow.terminate_game" replaceFormat="C.i18n(&quot;{key}&quot;)"/>
</Property> </Property>
</Properties> </Properties>
<Events> <Events>

View File

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.views; package org.jackhuang.hellominecraft.views;
import java.awt.Color;
import javax.swing.text.BadLocationException; import javax.swing.text.BadLocationException;
import javax.swing.text.Document; import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet; import javax.swing.text.SimpleAttributeSet;
@@ -80,28 +79,28 @@ public class LogWindow extends javax.swing.JFrame {
txtLog = new javax.swing.JTextPane(); txtLog = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(C.I18N.getString("logwindow.title")); // NOI18N setTitle(C.i18n("logwindow.title")); // NOI18N
addWindowListener(new java.awt.event.WindowAdapter() { addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) { public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt); formWindowClosed(evt);
} }
}); });
btnClear.setText(C.I18N.getString("ui.button.clear")); // NOI18N btnClear.setText(C.i18n("ui.button.clear")); // NOI18N
btnClear.addActionListener(new java.awt.event.ActionListener() { btnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
btnClearActionPerformed(evt); btnClearActionPerformed(evt);
} }
}); });
btnClose.setText(C.I18N.getString("ui.button.close")); // NOI18N btnClose.setText(C.i18n("ui.button.close")); // NOI18N
btnClose.addActionListener(new java.awt.event.ActionListener() { btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt); btnCloseActionPerformed(evt);
} }
}); });
btnCopy.setText(C.I18N.getString("ui.button.copy")); // NOI18N btnCopy.setText(C.i18n("ui.button.copy")); // NOI18N
btnCopy.addActionListener(new java.awt.event.ActionListener() { btnCopy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCopyActionPerformed(evt); btnCopyActionPerformed(evt);
@@ -117,7 +116,7 @@ public class LogWindow extends javax.swing.JFrame {
} }
}); });
btnTieBa.setText(C.I18N.getString("logwindow.tieba")); // NOI18N btnTieBa.setText(C.i18n("logwindow.tieba")); // NOI18N
btnTieBa.addActionListener(new java.awt.event.ActionListener() { btnTieBa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTieBaActionPerformed(evt); btnTieBaActionPerformed(evt);
@@ -131,7 +130,7 @@ public class LogWindow extends javax.swing.JFrame {
} }
}); });
btnTerminateGame.setText(C.I18N.getString("logwindow.terminate_game")); // NOI18N btnTerminateGame.setText(C.i18n("logwindow.terminate_game")); // NOI18N
btnTerminateGame.addActionListener(new java.awt.event.ActionListener() { btnTerminateGame.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTerminateGameActionPerformed(evt); btnTerminateGameActionPerformed(evt);

View File

@@ -40,7 +40,7 @@
<EmptySpace pref="212" max="32767" attributes="0"/> <EmptySpace pref="212" max="32767" attributes="0"/>
<Component id="btnCancel" min="-2" max="-2" attributes="0"/> <Component id="btnCancel" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
<Component id="jButton1" min="-2" max="-2" attributes="0"/> <Component id="btnOK" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
</Group> </Group>
</Group> </Group>
@@ -54,7 +54,7 @@
<Component id="jComboBox1" min="-2" max="-2" attributes="0"/> <Component id="jComboBox1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/> <EmptySpace max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0"> <Group type="103" groupAlignment="3" attributes="0">
<Component id="jButton1" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="btnOK" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnCancel" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="btnCancel" alignment="3" min="-2" max="-2" attributes="0"/>
</Group> </Group>
<EmptySpace max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
@@ -77,14 +77,14 @@
</Property> </Property>
</Properties> </Properties>
</Component> </Component>
<Component class="javax.swing.JButton" name="jButton1"> <Component class="javax.swing.JButton" name="btnOK">
<Properties> <Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor"> <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
<ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="button.ok" replaceFormat="java.util.ResourceBundle.getBundle(&quot;{bundleNameSlashes}&quot;).getString(&quot;{key}&quot;)"/> <ResourceString bundle="org/jackhuang/hellominecraft/launcher/I18N.properties" key="button.ok" replaceFormat="java.util.ResourceBundle.getBundle(&quot;{bundleNameSlashes}&quot;).getString(&quot;{key}&quot;)"/>
</Property> </Property>
</Properties> </Properties>
<Events> <Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnOKActionPerformed"/>
</Events> </Events>
</Component> </Component>
<Component class="javax.swing.JButton" name="btnCancel"> <Component class="javax.swing.JButton" name="btnCancel">

View File

@@ -50,6 +50,11 @@ public class Selector extends javax.swing.JDialog {
jComboBox1.addItem(s); jComboBox1.addItem(s);
} }
public int getChoice() {
setVisible(true);
return sel;
}
/** /**
* This method is called from within the constructor to initialize the form. * This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always * WARNING: Do NOT modify this code. The content of this method is always
@@ -61,7 +66,7 @@ public class Selector extends javax.swing.JDialog {
jLabel1 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox(); jComboBox1 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton(); btnOK = new javax.swing.JButton();
btnCancel = new javax.swing.JButton(); btnCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
@@ -69,10 +74,10 @@ public class Selector extends javax.swing.JDialog {
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N"); // NOI18N java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N"); // NOI18N
jLabel1.setText(bundle.getString("selector.choose")); // NOI18N jLabel1.setText(bundle.getString("selector.choose")); // NOI18N
jButton1.setText(bundle.getString("button.ok")); // NOI18N btnOK.setText(bundle.getString("button.ok")); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() { btnOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt); btnOKActionPerformed(evt);
} }
}); });
@@ -100,7 +105,7 @@ public class Selector extends javax.swing.JDialog {
.addContainerGap(212, Short.MAX_VALUE) .addContainerGap(212, Short.MAX_VALUE)
.addComponent(btnCancel) .addComponent(btnCancel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1) .addComponent(btnOK)
.addContainerGap()) .addContainerGap())
); );
layout.setVerticalGroup( layout.setVerticalGroup(
@@ -112,7 +117,7 @@ public class Selector extends javax.swing.JDialog {
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1) .addComponent(btnOK)
.addComponent(btnCancel)) .addComponent(btnCancel))
.addContainerGap()) .addContainerGap())
); );
@@ -125,14 +130,14 @@ public class Selector extends javax.swing.JDialog {
this.dispose(); this.dispose();
}//GEN-LAST:event_btnCancelActionPerformed }//GEN-LAST:event_btnCancelActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
sel = jComboBox1.getSelectedIndex(); sel = jComboBox1.getSelectedIndex();
this.dispose(); this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed }//GEN-LAST:event_btnOKActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables // Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel; private javax.swing.JButton btnCancel;
private javax.swing.JButton jButton1; private javax.swing.JButton btnOK;
private javax.swing.JComboBox jComboBox1; private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables // End of variables declaration//GEN-END:variables

View File

@@ -48,7 +48,7 @@ public class PluginManager {
} }
public static List<BukkitPlugin> getPlugins() throws Exception { public static List<BukkitPlugin> getPlugins() throws Exception {
String result = NetUtils.doGet("http://api.bukget.org/3//plugins?fields=slug,plugin_name,description,versions.version,versions.game_versions"); String result = NetUtils.get("http://api.bukget.org/3//plugins?fields=slug,plugin_name,description,versions.version,versions.game_versions");
Gson gson = new Gson(); Gson gson = new Gson();
List<BukkitPlugin> list = gson.fromJson(result, new TypeToken<List<BukkitPlugin>>() { List<BukkitPlugin> list = gson.fromJson(result, new TypeToken<List<BukkitPlugin>>() {
}.getType()); }.getType());
@@ -61,7 +61,7 @@ public class PluginManager {
CATEGORY_GENERAL = "General", CATEGORY_GENERAL = "General",
CATEGORY_ANTI_GRIEFING_TOOLS = "Anti Griefing Tools", CATEGORY_ANTI_GRIEFING_TOOLS = "Anti Griefing Tools",
CATEGORY_MECHAICS = "Mechanics", CATEGORY_MECHAICS = "Mechanics",
CATEGORY_Fixes = "Fixes", CATEGORY_FIXES = "Fixes",
CATEGORY_ROLE_PLAYING = "Role Playing", CATEGORY_ROLE_PLAYING = "Role Playing",
CATEGORY_WORLD_EDITING_AND_MANAGEMENT = "World Editing and Management", CATEGORY_WORLD_EDITING_AND_MANAGEMENT = "World Editing and Management",
CATEGORY_TELEPORTATION = "Teleportation", CATEGORY_TELEPORTATION = "Teleportation",
@@ -73,7 +73,7 @@ public class PluginManager {
CATEGORY_WEBSITE_ADMINISTRATION = "Website Administration"; CATEGORY_WEBSITE_ADMINISTRATION = "Website Administration";
public static List<BukkitPlugin> getPluginsByCategory(String category) throws Exception { public static List<BukkitPlugin> getPluginsByCategory(String category) throws Exception {
String result = NetUtils.doGet("http://api.bukget.org/3//categories/" + category + "?fields=slug,plugin_name,description,versions.version,versions.game_versions"); String result = NetUtils.get("http://api.bukget.org/3//categories/" + category + "?fields=slug,plugin_name,description,versions.version,versions.game_versions");
Gson gson = new Gson(); Gson gson = new Gson();
List<BukkitPlugin> list = gson.fromJson(result, new TypeToken<List<BukkitPlugin>>() { List<BukkitPlugin> list = gson.fromJson(result, new TypeToken<List<BukkitPlugin>>() {
}.getType()); }.getType());
@@ -81,7 +81,7 @@ public class PluginManager {
} }
public static List<Category> getCategories() throws Exception { public static List<Category> getCategories() throws Exception {
String result = NetUtils.doGet("http://api.bukget.org/3//categories/"); String result = NetUtils.get("http://api.bukget.org/3//categories/");
Gson gson = new Gson(); Gson gson = new Gson();
List<Category> list = gson.fromJson(result, new TypeToken<List<Category>>() { List<Category> list = gson.fromJson(result, new TypeToken<List<Category>>() {
}.getType()); }.getType());
@@ -90,7 +90,7 @@ public class PluginManager {
public static PluginInfo getPluginInfo(String slug) throws Exception { public static PluginInfo getPluginInfo(String slug) throws Exception {
if (StrUtils.isNotBlank(slug)) { if (StrUtils.isNotBlank(slug)) {
String result = NetUtils.doGet("http://api.bukget.org/3//plugins/bukkit/" + slug.toLowerCase()); String result = NetUtils.get("http://api.bukget.org/3//plugins/bukkit/" + slug.toLowerCase());
if (StrUtils.isNotBlank(result)) if (StrUtils.isNotBlank(result))
if (!result.equals("null")) { if (!result.equals("null")) {
PluginInfo info = new Gson().fromJson(result, PluginInfo.class); PluginInfo info = new Gson().fromJson(result, PluginInfo.class);

View File

@@ -40,7 +40,7 @@ public class IPGet extends Thread {
Elements iframe = d.getElementsByTag("iframe"); Elements iframe = d.getElementsByTag("iframe");
if (iframe.size() > 0) { if (iframe.size() > 0) {
String url = iframe.get(0).attr("src"); String url = iframe.get(0).attr("src");
String s = NetUtils.doGet(url, "GBK"); String s = NetUtils.get(url, "GBK");
Pattern p = Pattern.compile("\\[(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}\\]"); Pattern p = Pattern.compile("\\[(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}\\]");
Matcher m = p.matcher(s); Matcher m = p.matcher(s);
s = ""; s = "";