optimize code.

This commit is contained in:
huanghongxun
2015-06-26 23:00:55 +08:00
parent db8e425b2b
commit 9220a818b3
9 changed files with 157 additions and 239 deletions

View File

@@ -1,34 +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.launcher.utils;
import java.io.File;
import java.io.IOException;
import org.jackhuang.hellominecraft.utils.FileUtils;
/**
*
* @author hyh
*/
public class BaseLauncherProfile {
public static String profile = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}";
public static void tryWriteProfile(File gameDir) throws IOException {
File file = new File(gameDir, "launcher_profiles.json");
if(!file.exists())
FileUtils.writeStringToFile(file, profile);
}
}

View File

@@ -59,25 +59,23 @@ public final class MCUtils {
}
private static int lessThan32(byte[] b, int x) {
for (; x < b.length; x++) {
if (b[x] < 32) {
for (; x < b.length; x++)
if (b[x] < 32)
return x;
}
}
return -1;
}
private static MinecraftVersionRequest getVersionOfOldMinecraft(ZipFile paramZipFile, ZipEntry paramZipEntry) throws IOException {
private static MinecraftVersionRequest getVersionOfOldMinecraft(ZipFile file, ZipEntry entry) throws IOException {
MinecraftVersionRequest r = new MinecraftVersionRequest();
byte[] tmp = NetUtils.getBytesFromStream(paramZipFile.getInputStream(paramZipEntry));
byte[] tmp = NetUtils.getBytesFromStream(file.getInputStream(entry));
byte[] arrayOfByte = "Minecraft Minecraft ".getBytes("ASCII");
byte[] bytes = "Minecraft Minecraft ".getBytes("ASCII");
int j;
if ((j = ArrayUtils.matchArray(tmp, arrayOfByte)) < 0) {
if ((j = ArrayUtils.matchArray(tmp, bytes)) < 0) {
r.type = MinecraftVersionRequest.Unkown;
return r;
}
int i = j + arrayOfByte.length;
int i = j + bytes.length;
if ((j = lessThan32(tmp, i)) < 0) {
r.type = MinecraftVersionRequest.Unkown;
@@ -86,11 +84,8 @@ public final class MCUtils {
String ver = new String(tmp, i, j - i, "ASCII");
r.version = ver;
if (paramZipFile.getEntry("META-INF/MANIFEST.MF") == null) {
r.type = MinecraftVersionRequest.Modified;
} else {
r.type = MinecraftVersionRequest.OK;
}
r.type = file.getEntry("META-INF/MANIFEST.MF") == null ?
MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r;
}
@@ -139,12 +134,8 @@ public final class MCUtils {
k++;
r.version = new String(tmp, k, i - k + 1);
}
if (file.getEntry("META-INF/MANIFEST.MF") == null) {
r.type = MinecraftVersionRequest.Modified;
} else {
r.type = MinecraftVersionRequest.OK;
}
r.type = file.getEntry("META-INF/MANIFEST.MF") == null ?
MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r;
}
@@ -167,14 +158,12 @@ public final class MCUtils {
localZipFile = new ZipFile(file);
ZipEntry minecraft = localZipFile
.getEntry("net/minecraft/client/Minecraft.class");
if (minecraft != null) {
if (minecraft != null)
return getVersionOfOldMinecraft(localZipFile, minecraft);
}
ZipEntry main = localZipFile.getEntry("net/minecraft/client/main/Main.class");
ZipEntry minecraftserver = localZipFile.getEntry("net/minecraft/server/MinecraftServer.class");
if ((main != null) && (minecraftserver != null)) {
if ((main != null) && (minecraftserver != null))
return getVersionOfNewMinecraft(localZipFile, minecraftserver);
}
r.type = MinecraftVersionRequest.Invaild;
return r;
} catch (IOException localException) {
@@ -182,7 +171,7 @@ public final class MCUtils {
r.type = MinecraftVersionRequest.InvaildJar;
return r;
} finally {
if (localZipFile != null) {
if (localZipFile != null)
try {
localZipFile.close();
} catch (IOException ex) {
@@ -190,26 +179,27 @@ public final class MCUtils {
}
}
}
}
public static File getLocation() {
String localObject = "minecraft";
String baseName = "minecraft";
String str1 = System.getProperty("user.home", ".");
File file;
OS os = OS.os();
if (os == OS.LINUX) {
file = new File(str1, '.' + (String) localObject + '/');
} else if (os == OS.WINDOWS) {
switch (OS.os()) {
case LINUX:
file = new File(str1, '.' + (String) baseName + '/');
break;
case WINDOWS:
String str2;
if ((str2 = System.getenv("APPDATA")) != null) {
file = new File(str2, "." + (String) localObject + '/');
} else {
file = new File(str1, '.' + (String) localObject + '/');
}
} else if (os == OS.OSX) {
file = new File(str1, "Library/Application Support/" + localObject);
} else {
file = new File(str1, localObject + '/');
if ((str2 = System.getenv("APPDATA")) != null)
file = new File(str2, "." + baseName + '/');
else
file = new File(str1, '.' + baseName + '/');
break;
case OSX:
file = new File(str1, "Library/Application Support/" + baseName);
break;
default:
file = new File(str1, baseName + '/');
}
return file;
}
@@ -220,10 +210,7 @@ public final class MCUtils {
}
public static String minecraft() {
String os = System.getProperty("os.name").trim().toLowerCase();
if (os.contains("mac")) {
return "minecraft";
}
if (OS.os() == OS.OSX) return "minecraft";
return ".minecraft";
}
@@ -253,8 +240,6 @@ public final class MCUtils {
.addTask(new FileDownloadTask(vurl + id + ".jar", IOUtils.tryGetCanonicalFile(mvj)).setTag(id + ".jar"))
.start()) {
MinecraftVersion mv = new Gson().fromJson(FileUtils.readFileToStringQuietly(mvt), MinecraftVersion.class);
//File apath = new File(gameDir, "assets/indexes");
//downloadMinecraftAssetsIndex(apath, mv.assets, sourceType);
return mv;
}
return null;
@@ -273,15 +258,13 @@ public final class MCUtils {
if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(vurl + id + ".json", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".json"))
.start()) {
if (moved != null) {
if (moved != null)
moved.delete();
}
return true;
} else {
mvt.delete();
if (moved != null) {
if (moved != null)
moved.renameTo(mvt);
}
return false;
}
}
@@ -299,14 +282,12 @@ public final class MCUtils {
if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(aurl + assetsId + ".json", IOUtils.tryGetCanonicalFile(assetsIndex)).setTag(assetsId + ".json"))
.start()) {
if (renamed != null) {
if (renamed != null)
renamed.delete();
}
return true;
}
if (renamed != null) {
if (renamed != null)
renamed.renameTo(assetsIndex);
}
return false;
}
@@ -314,4 +295,11 @@ public final class MCUtils {
String result = NetUtils.doGet(sourceType.getProvider().getVersionsListDownloadURL());
return MinecraftRemoteVersions.fromJson(result);
}
public static String profile = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}";
public static void tryWriteProfile(File gameDir) throws IOException {
File file = new File(gameDir, "launcher_profiles.json");
if(!file.exists())
FileUtils.writeStringToFile(file, profile);
}
}

View File

@@ -85,8 +85,8 @@ public class AssetsMojangLoader extends IAssetsHandler {
if (o != null && o.getFileMap() != null)
for (Map.Entry<String, AssetsObject> e : o.getFileMap().entrySet()) {
Contents c = new Contents();
c.key = e.getValue().getHash().substring(0, 2) + "/" + e.getValue().getHash();
c.eTag = e.getValue().getHash();
c.key = c.eTag.substring(0, 2) + "/" + e.getValue().getHash();
c.size = e.getValue().getSize();
contents.add(c);
assetsDownloadURLs.add(c.key);

View File

@@ -140,7 +140,7 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
UserProfileProvider info = new UserProfileProvider();
try {
ua.logIn();
if(!ua.isLoggedIn()) throw new Exception(C.i18n("WrongPassword"));
if(!ua.isLoggedIn()) throw new Exception(C.i18n("login.wrong_password"));
GameProfile profile = ua.getSelectedProfile();
info.setUserName(profile.getName());
info.setSuccess(true);

View File

@@ -60,7 +60,6 @@ public final class Settings {
static {
settings = initSettings();
isFirstLoad = StrUtils.isBlank(settings.getUsername());
if (!getVersions().containsKey("Default"))
getVersions().put("Default", new Profile());
@@ -70,7 +69,7 @@ public final class Settings {
private static Config initSettings() {
Config c = new Config();
if (settingsFile.exists())
if (settingsFile.exists()) {
try {
String str = FileUtils.readFileToString(settingsFile);
if (str == null || str.trim().equals(""))
@@ -87,7 +86,8 @@ public final class Settings {
System.exit(1);
}
}
else {
isFirstLoad = StrUtils.isBlank(settings.getUsername());
} else {
HMCLog.log("No settings file here, may be first loading.");
isFirstLoad = true;
}

View File

@@ -32,7 +32,6 @@ import org.jackhuang.hellominecraft.launcher.launch.GameLauncher.DownloadLibrary
import org.jackhuang.hellominecraft.launcher.launch.IMinecraftLoader;
import org.jackhuang.hellominecraft.launcher.launch.IMinecraftProvider;
import org.jackhuang.hellominecraft.launcher.launch.MinecraftLoader;
import org.jackhuang.hellominecraft.launcher.utils.BaseLauncherProfile;
import org.jackhuang.hellominecraft.utils.FileUtils;
import org.jackhuang.hellominecraft.launcher.utils.MCUtils;
import org.jackhuang.hellominecraft.launcher.utils.auth.UserProfileProvider;
@@ -83,7 +82,7 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
public void refreshVersions() {
baseFolder = profile.getCanonicalGameDirFile();
try {
BaseLauncherProfile.tryWriteProfile(baseFolder);
MCUtils.tryWriteProfile(baseFolder);
} catch (IOException ex) {
HMCLog.warn("Failed to create launcher_profiles.json, Forge/LiteLoader installer will not work.", ex);
}

View File

@@ -4,9 +4,9 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jackhuang.hellominecraft.logging.logger.Logger;
import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.utils.Validate;
import org.jackhuang.mojang.authlib.properties.Property;
import org.jackhuang.mojang.authlib.properties.PropertyMap;
import org.jackhuang.mojang.util.UUIDTypeAdapter;
@@ -30,7 +30,7 @@ public abstract class BaseUserAuthentication
private UserType userType;
protected BaseUserAuthentication(AuthenticationService authenticationService) {
Validate.notNull(authenticationService);
Objects.requireNonNull(authenticationService);
this.authenticationService = authenticationService;
}

View File

@@ -9,10 +9,10 @@ import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;
import org.jackhuang.hellominecraft.logging.logger.Logger;
import org.jackhuang.hellominecraft.utils.IOUtils;
import org.jackhuang.hellominecraft.utils.NetUtils;
import org.jackhuang.hellominecraft.utils.Validate;
public abstract class HttpAuthenticationService extends BaseAuthenticationService {
@@ -20,7 +20,7 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
private final Proxy proxy;
protected HttpAuthenticationService(Proxy proxy) {
Validate.notNull(proxy);
Objects.requireNonNull(proxy);
this.proxy = proxy;
}
@@ -29,8 +29,8 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
}
protected HttpURLConnection createUrlConnection(URL url) throws IOException {
Validate.notNull(url);
LOGGER.debug(new StringBuilder().append("Opening connection to ").append(url).toString());
Objects.requireNonNull(url);
LOGGER.debug("Opening connection to " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(this.proxy);
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
@@ -39,17 +39,17 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
}
public String performPostRequest(URL url, String post, String contentType) throws IOException {
Validate.notNull(url);
Validate.notNull(post);
Validate.notNull(contentType);
Objects.requireNonNull(url);
Objects.requireNonNull(post);
Objects.requireNonNull(contentType);
HttpURLConnection connection = createUrlConnection(url);
byte[] postAsBytes = post.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", new StringBuilder().append(contentType).append("; charset=utf-8").toString());
connection.setRequestProperty("Content-Length", new StringBuilder().append("").append(postAsBytes.length).toString());
connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
connection.setDoOutput(true);
LOGGER.debug(new StringBuilder().append("Writing POST data to ").append(url).append(": ").append(post).toString());
LOGGER.debug("Writing POST data to " + url + ": " + post);
OutputStream outputStream = null;
try {
@@ -59,14 +59,14 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
IOUtils.closeQuietly(outputStream);
}
LOGGER.debug(new StringBuilder().append("Reading data from ").append(url).toString());
LOGGER.debug("Reading data from " + url);
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug(new StringBuilder().append("Successful read, server response was ").append(connection.getResponseCode()).toString());
LOGGER.debug(new StringBuilder().append("Response: ").append(result).toString());
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str1 = result;
return str1;
} catch (IOException e) {
@@ -74,10 +74,10 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
inputStream = connection.getErrorStream();
if (inputStream != null) {
LOGGER.debug(new StringBuilder().append("Reading error page from ").append(url).toString());
LOGGER.debug("Reading error page from " + url);
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug(new StringBuilder().append("Successful read, server response was ").append(connection.getResponseCode()).toString());
LOGGER.debug(new StringBuilder().append("Response: ").append(result).toString());
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str2 = result;
return str2;
}
@@ -90,17 +90,17 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
public String performGetRequest(URL url)
throws IOException {
Validate.notNull(url);
Objects.requireNonNull(url);
HttpURLConnection connection = createUrlConnection(url);
LOGGER.debug(new StringBuilder().append("Reading data from ").append(url).toString());
LOGGER.debug("Reading data from " + url);
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug(new StringBuilder().append("Successful read, server response was ").append(connection.getResponseCode()).toString());
LOGGER.debug(new StringBuilder().append("Response: ").append(result).toString());
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str1 = result;
return str1;
} catch (IOException e) {
@@ -108,10 +108,10 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
inputStream = connection.getErrorStream();
if (inputStream != null) {
LOGGER.debug(new StringBuilder().append("Reading error page from ").append(url).toString());
LOGGER.debug("Reading error page from " + url);
String result = NetUtils.getStreamContent(inputStream, "UTF-8");
LOGGER.debug(new StringBuilder().append("Successful read, server response was ").append(connection.getResponseCode()).toString());
LOGGER.debug(new StringBuilder().append("Response: ").append(result).toString());
LOGGER.debug("Successful read, server response was " + connection.getResponseCode());
LOGGER.debug("Response: " + result);
String str2 = result;
return str2;
}
@@ -123,17 +123,14 @@ public abstract class HttpAuthenticationService extends BaseAuthenticationServic
}
public static String buildQuery(Map<String, Object> query) {
if (query == null) {
return "";
}
if (query == null) return "";
StringBuilder builder = new StringBuilder();
for (Map.Entry entry : query.entrySet()) {
if (builder.length() > 0) {
for (Map.Entry<String, Object> entry : query.entrySet()) {
if (builder.length() > 0)
builder.append('&');
}
try {
builder.append(URLEncoder.encode((String) entry.getKey(), "UTF-8"));
builder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("Unexpected exception building query", e);
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.
*/
package org.jackhuang.hellominecraft.utils;
/**
*
* @author hyh
*/
public final class Validate {
public static <T> T notNull(T o) {
if(o == null) {
throw new IllegalArgumentException("The validated object is null");
}
return o;
}
}