Use global Gson object with pretty printing

This commit is contained in:
khanhduytran0 2020-11-17 18:01:20 +07:00
parent 0ca33e4517
commit 54341d7cfe
12 changed files with 88 additions and 220 deletions

View file

@ -12,25 +12,24 @@ public class LoginTask extends AsyncTask<String, Void, String[]>
//private String TAG = "MojangAuth-login"; //private String TAG = "MojangAuth-login";
private LoginListener listener; private LoginListener listener;
public LoginTask setLoginListener(LoginListener listener) public LoginTask setLoginListener(LoginListener listener) {
{
this.listener = listener; this.listener = listener;
return this; return this;
} }
private UUID getRandomUUID()
{ private UUID getRandomUUID() {
return UUID.randomUUID(); return UUID.randomUUID();
} }
@Override @Override
protected void onPreExecute() protected void onPreExecute() {
{
listener.onBeforeLogin(); listener.onBeforeLogin();
super.onPreExecute(); super.onPreExecute();
} }
@Override @Override
protected String[] doInBackground(String[] args) protected String[] doInBackground(String[] args) {
{
ArrayList<String> str = new ArrayList<String>(); ArrayList<String> str = new ArrayList<String>();
str.add("ERROR"); str.add("ERROR");
try{ try{
@ -38,12 +37,10 @@ public class LoginTask extends AsyncTask<String, Void, String[]>
AuthenticateResponse response = authenticator.authenticate(args[0], args[1], getRandomUUID()); AuthenticateResponse response = authenticator.authenticate(args[0], args[1], getRandomUUID());
if (response.selectedProfile == null) { if (response.selectedProfile == null) {
str.add("Can't login a demo account!\n"); str.add("Can't login a demo account!\n");
} } else {
else{
if (new File(Tools.mpProfiles + "/" + response.selectedProfile.name).exists()) { if (new File(Tools.mpProfiles + "/" + response.selectedProfile.name).exists()) {
str.add("This account already exist!\n"); str.add("This account already exist!\n");
} } else {
else{
str.add(response.accessToken); // Access token str.add(response.accessToken); // Access token
str.add(response.clientToken.toString()); // Client token str.add(response.clientToken.toString()); // Client token
str.add(response.selectedProfile.id); // Profile ID str.add(response.selectedProfile.id); // Profile ID
@ -62,9 +59,9 @@ public class LoginTask extends AsyncTask<String, Void, String[]>
} }
return str.toArray(new String[0]); return str.toArray(new String[0]);
} }
@Override @Override
protected void onPostExecute(String[] result) protected void onPostExecute(String[] result) {
{
listener.onLoginDone(result); listener.onLoginDone(result);
super.onPostExecute(result); super.onPostExecute(result);
} }

View file

@ -1,24 +1,23 @@
package com.kdt.mojangauth.yggdrasil; package com.kdt.mojangauth.yggdrasil;
import android.util.*; import android.util.*;
import com.google.gson.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.nio.charset.*; import java.nio.charset.*;
import java.util.*; import java.util.*;
import net.kdt.pojavlaunch.*;
public class YggdrasilAuthenticator { public class YggdrasilAuthenticator {
private static final String API_URL = "https://authserver.mojang.com/"; private static final String API_URL = "https://authserver.mojang.com/";
private String clientName = "Minecraft"; private String clientName = "Minecraft";
private int clientVersion = 1; private int clientVersion = 1;
private Gson gson = new Gson();
private <T> T makeRequest(String endpoint, Object inputObject, Class<T> responseClass) throws IOException, Throwable { private <T> T makeRequest(String endpoint, Object inputObject, Class<T> responseClass) throws IOException, Throwable {
Throwable th; Throwable th;
InputStream is = null; InputStream is = null;
byte[] buf = new byte[16384]; byte[] buf = new byte[16384];
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
String requestJson = this.gson.toJson(inputObject); String requestJson = Tools.GLOBAL_GSON.toJson(inputObject);
try { try {
URL url = new URL(API_URL + endpoint); URL url = new URL(API_URL + endpoint);
OutputStream os; OutputStream os;
@ -53,7 +52,7 @@ public class YggdrasilAuthenticator {
if (statusCode == 200){ if (statusCode == 200){
Log.i("Result", "Task " + endpoint + " successful"); Log.i("Result", "Task " + endpoint + " successful");
return this.gson.fromJson(outString, responseClass); return Tools.GLOBAL_GSON.fromJson(outString, responseClass);
} }
throw new RuntimeException("Invalid username or password, status code: " + statusCode); throw new RuntimeException("Invalid username or password, status code: " + statusCode);
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
@ -64,6 +63,7 @@ public class YggdrasilAuthenticator {
try { try {
is.close(); is.close();
} catch (Exception e2) { } catch (Exception e2) {
e2.addSuppressed(th2);
throw e2; throw e2;
} }
} }

View file

@ -92,7 +92,7 @@ public class CustomControlsActivity extends AppCompatActivity
private void setDefaultControlJson(String path) { private void setDefaultControlJson(String path) {
try { try {
// Load before save to make sure control is not error // Load before save to make sure control is not error
ctrlLayout.loadLayout(new Gson().fromJson(Tools.read(path), CustomControls.class)); ctrlLayout.loadLayout(Tools.GLOBAL_GSON.fromJson(Tools.read(path), CustomControls.class));
LauncherPreferences.DEFAULT_PREF.edit().putString("defaultCtrl", path).commit(); LauncherPreferences.DEFAULT_PREF.edit().putString("defaultCtrl", path).commit();
LauncherPreferences.PREF_DEFAULTCTRL_PATH = path; LauncherPreferences.PREF_DEFAULTCTRL_PATH = path;
} catch (Throwable th) { } catch (Throwable th) {

View file

@ -642,17 +642,13 @@ public class PojavLoginActivity extends AppCompatActivity
new LoginTask().setLoginListener(new LoginListener(){ new LoginTask().setLoginListener(new LoginListener(){
@Override @Override
public void onBeforeLogin() public void onBeforeLogin() {
{
// TODO: Implement this method
v.setEnabled(false); v.setEnabled(false);
prb.setVisibility(View.VISIBLE); prb.setVisibility(View.VISIBLE);
} }
@Override @Override
public void onLoginDone(String[] result) public void onLoginDone(String[] result) {
{
// TODO: Implement this method
if(result[0].equals("ERROR")){ if(result[0].equals("ERROR")){
Tools.dialogOnUiThread(PojavLoginActivity.this, getResources().getString(R.string.global_error), strArrToString(result)); Tools.dialogOnUiThread(PojavLoginActivity.this, getResources().getString(R.string.global_error), strArrToString(result));
} else{ } else{

View file

@ -22,17 +22,19 @@ import android.view.*;
public final class Tools public final class Tools
{ {
public static boolean enableDevFeatures = BuildConfig.DEBUG; public static final boolean enableDevFeatures = BuildConfig.DEBUG;
public static String APP_NAME = "null"; public static String APP_NAME = "null";
public static String MAIN_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/games/.minecraft"; public static final String MAIN_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/games/.minecraft";
public static String ASSETS_PATH = MAIN_PATH + "/assets"; public static final String ASSETS_PATH = MAIN_PATH + "/assets";
public static String CTRLMAP_PATH = MAIN_PATH + "/controlmap"; public static final String CTRLMAP_PATH = MAIN_PATH + "/controlmap";
public static String CTRLDEF_FILE = MAIN_PATH + "/controlmap/default.json"; public static final String CTRLDEF_FILE = MAIN_PATH + "/controlmap/default.json";
public static final Gson GLOBAL_GSON = new GsonBuilder().setPrettyPrinting().create();
public static final String mhomeUrl = "https://pojavlauncherteam.github.io/PojavLauncher";
public static int usingVerCode = 1; public static int usingVerCode = 1;
public static String usingVerName = "2.4.2"; public static String usingVerName = "3.2.0";
public static String mhomeUrl = "https://pojavlauncherteam.github.io/PojavLauncher"; // "http://kdtjavacraft.eu5.net";
public static String datapath = "/data/data/net.kdt.pojavlaunch"; public static String datapath = "/data/data/net.kdt.pojavlaunch";
public static String worksDir = datapath + "/app_working_dir"; public static String worksDir = datapath + "/app_working_dir";
public static String currentArch; public static String currentArch;
@ -42,14 +44,14 @@ public final class Tools
public static String homeJreLib = "lib"; public static String homeJreLib = "lib";
// New since 2.4.2 // New since 2.4.2
public static String versnDir = MAIN_PATH + "/versions"; public static final String versnDir = MAIN_PATH + "/versions";
public static String libraries = MAIN_PATH + "/libraries"; public static final String libraries = MAIN_PATH + "/libraries";
public static String optifineDir = MAIN_PATH + "/optifine"; public static final String optifineDir = MAIN_PATH + "/optifine";
public static final String crashPath = MAIN_PATH + "/crash-reports";
public static String mpProfiles = datapath + "/Users"; public static String mpProfiles = datapath + "/Users";
public static String crashPath = MAIN_PATH + "/crash-reports";
public static String optifineLib = "optifine:OptiFine"; public static final String optifineLib = "optifine:OptiFine";
private static int exitCode = 0; private static int exitCode = 0;
public static void launchMinecraft(final LoggableActivity ctx, MCProfile.Builder profile, JMinecraftVersionList.Version versionInfo) throws Throwable { public static void launchMinecraft(final LoggableActivity ctx, MCProfile.Builder profile, JMinecraftVersionList.Version versionInfo) throws Throwable {
@ -465,9 +467,7 @@ public final class Tools
ctx.runOnUiThread(new Runnable(){ ctx.runOnUiThread(new Runnable(){
@Override @Override
public void run() public void run() {
{
// TODO: Implement this method
new AlertDialog.Builder(ctx) new AlertDialog.Builder(ctx)
.setTitle(title) .setTitle(title)
.setMessage(message) .setMessage(message)
@ -508,31 +508,7 @@ public final class Tools
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
act.startActivity(browserIntent); act.startActivity(browserIntent);
} }
/*
public static void clearDuplicateFiles(File f) throws IOException {
List<File> list = Arrays.asList(f.listFiles());
for (File file : list) {
if (!file.exists()) {
// The file was deleted by duplicate
list.remove(file);
continue;
}
String md5 = Md5Crypt.md5Crypt(read(file));
list.remove(file);
clearDuplicateFilesByMD5(list.toArray(new File[0]), md5);
}
}
public static void clearDuplicateFilesByMD5(File[] list, String md5Find) throws IOException {
for (File file : list) {
String md5Other = DigestUtils.md5Hex(new FileInputStream(file));
if (md5Find.equals(md5Other)) {
file.delete();
}
}
}
*/
public static String[] generateLibClasspath(JMinecraftVersionList.Version info) { public static String[] generateLibClasspath(JMinecraftVersionList.Version info) {
List<String> libDir = new ArrayList<String>(); List<String> libDir = new ArrayList<String>();
@ -545,7 +521,7 @@ public final class Tools
public static JMinecraftVersionList.Version getVersionInfo(String versionName) { public static JMinecraftVersionList.Version getVersionInfo(String versionName) {
try { try {
JMinecraftVersionList.Version customVer = new Gson().fromJson(read(versnDir + "/" + versionName + "/" + versionName + ".json"), JMinecraftVersionList.Version.class); JMinecraftVersionList.Version customVer = Tools.GLOBAL_GSON.fromJson(read(versnDir + "/" + versionName + "/" + versionName + ".json"), JMinecraftVersionList.Version.class);
for (DependentLibrary lib : customVer.libraries) { for (DependentLibrary lib : customVer.libraries) {
if (lib.name.startsWith(optifineLib)) { if (lib.name.startsWith(optifineLib)) {
customVer.optifineLib = lib; customVer.optifineLib = lib;
@ -559,7 +535,7 @@ public final class Tools
if (customVer.inheritsFrom == null || customVer.inheritsFrom.isEmpty()) { if (customVer.inheritsFrom == null || customVer.inheritsFrom.isEmpty()) {
return customVer; return customVer;
} else { } else {
JMinecraftVersionList.Version inheritsVer = new Gson().fromJson(read(versnDir + "/" + customVer.inheritsFrom + "/" + customVer.inheritsFrom + ".json"), JMinecraftVersionList.Version.class); JMinecraftVersionList.Version inheritsVer = Tools.GLOBAL_GSON.fromJson(read(versnDir + "/" + customVer.inheritsFrom + "/" + customVer.inheritsFrom + ".json"), JMinecraftVersionList.Version.class);
inheritsVer.inheritsFrom = ""; inheritsVer.inheritsFrom = "";
insertSafety(inheritsVer, customVer, insertSafety(inheritsVer, customVer,

View file

@ -32,7 +32,7 @@ public class ControlLayout extends FrameLayout
public void loadLayout(String jsonPath) { public void loadLayout(String jsonPath) {
try { try {
loadLayout(new Gson().fromJson(Tools.read(jsonPath), CustomControls.class)); loadLayout(Tools.GLOBAL_GSON.fromJson(Tools.read(jsonPath), CustomControls.class));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

View file

@ -42,6 +42,6 @@ public class CustomControls
} }
public void save(String path) throws Exception { public void save(String path) throws Exception {
Tools.write(path, new Gson().toJson(this)); Tools.write(path, Tools.GLOBAL_GSON.toJson(this));
} }
} }

View file

@ -1,102 +0,0 @@
package net.kdt.pojavlaunch.customcontrolsv2;
import java.util.*;
import net.kdt.pojavlaunch.*;
import org.lwjgl.glfw.*;
public class V2ControlButton implements Cloneable {
/*
* The v2 custom controls support for these value format use ${value}:
* This will provive autoscale when import/export
* - dp=N : define N dp size
* - width_window: replace by width screen
* - height_window: replace by height screen
* - at_corner=(left/right)-(top/bottom)
* - at_target=(name)
*/
/*
public static final int SPECIALBTN_KEYBOARD = -1;
public static final int SPECIALBTN_TOGGLECTRL = -2;
public static final int SPECIALBTN_MOUSEPRI = -3;
public static final int SPECIALBTN_MOUSESEC = -4;
public static final int SPECIALBTN_VIRTUALMOUSE = -5;
private static V2ControlButton[] SPECIAL_BUTTONS;
private static String[] SPECIAL_BUTTON_NAME_ARRAY;
public static V2ControlButton[] getSpecialButtons(){
if (SPECIAL_BUTTONS == null) {
SPECIAL_BUTTONS = new V2ControlButton[]{
new V2ControlButton("Keyboard", SPECIALBTN_KEYBOARD, "${dp=2} * 3 + ${dp=80} * 2", "${dp=2}", false),
new V2ControlButton("GUI", SPECIALBTN_TOGGLECTRL, "${dp=2}", "${width_window} - ${dp=50} * 2 + ${dp=2} * 4"),
new V2ControlButton("PRI", SPECIALBTN_MOUSEPRI, "${dp=2}", "${width_window} - ${dp=50} * 4 + ${dp=2} * 2"),
new V2ControlButton("SEC", SPECIALBTN_MOUSESEC, "${dp=2} * 3 + ${dp=50} * 2", "${height_window} - ${dp=50} * 4 + ${dp=2} * 2"),
new V2ControlButton("Mouse", SPECIALBTN_VIRTUALMOUSE, "${width_window} - ${dp=80}", "${dp=2}", false)
};
}
return SPECIAL_BUTTONS;
}
public static String[] buildSpecialButtonArray() {
if (SPECIAL_BUTTON_NAME_ARRAY == null) {
List<String> nameList = new ArrayList<String>();
for (V2ControlButton btn : getSpecialButtons()) {
nameList.add(btn.name);
}
SPECIAL_BUTTON_NAME_ARRAY = nameList.toArray(new String[0]);
}
return SPECIAL_BUTTON_NAME_ARRAY;
}
public String name;
public float x;
public float y;
public String width = "${dp=50}";
public String height = "${dp=50}";
public int keycode;
public int keyindex;
public boolean hidden;
public int mods;
public Object specialButtonListener;
// public boolean hold
public V2ControlButton() {
this("", LWJGLGLFWKeycode.GLFW_KEY_UNKNOWN, 0, 0);
}
public V2ControlButton(String name, int keycode) {
this(name, keycode, 0, 0);
}
public V2ControlButton(String name, int keycode, String x, String y) {
this(name, keycode, x, y, "${dp=50}", "${dp=50}");
}
public V2ControlButton(android.content.Context ctx, int resId, int keycode, String x, String y, boolean isSquare) {
this(ctx.getResources().getString(resId), keycode, x, y, isSquare);
}
public V2ControlButton(String name, int keycode, String x, String y, boolean isSquare) {
this(name, keycode, x, y, isSquare ? "${dp=50}" : pixelOf80dp, isSquare ? ${dp=50} : pixelOf30dp);
}
public V2ControlButton(String name, int keycode, String x, String y, int width, int height) {
this.name = name;
this.keycode = keycode;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void execute(MainActivity act, boolean isDown) {
act.sendKeyPress(keycode, 0, isDown);
}
public V2ControlButton clone() {
return new V2ControlButton(name, keycode, x, y, width, height);
}
*/
}

View file

@ -266,7 +266,7 @@ public class MinecraftDownloaderTask extends AsyncTask<String, String, Throwable
DownloadUtils.downloadFile(verInfo.assetIndex != null ? verInfo.assetIndex.url : "http://s3.amazonaws.com/Minecraft.Download/indexes/" + versionName + ".json", output); DownloadUtils.downloadFile(verInfo.assetIndex != null ? verInfo.assetIndex.url : "http://s3.amazonaws.com/Minecraft.Download/indexes/" + versionName + ".json", output);
} }
return new Gson().fromJson(Tools.read(output.getAbsolutePath()), JAssets.class); return Tools.GLOBAL_GSON.fromJson(Tools.read(output.getAbsolutePath()), JAssets.class);
} }
public void downloadAsset(JAssetInfo asset, File objectsDir) throws IOException, Throwable { public void downloadAsset(JAssetInfo asset, File objectsDir) throws IOException, Throwable {

View file

@ -26,7 +26,7 @@ public class RefreshVersionListTask extends AsyncTask<Void, Void, ArrayList<Stri
protected ArrayList<String> doInBackground(Void[] p1) protected ArrayList<String> doInBackground(Void[] p1)
{ {
try { try {
mActivity.mVersionList = new Gson().fromJson(DownloadUtils.downloadString("https://launchermeta.mojang.com/mc/game/version_manifest.json"), JMinecraftVersionList.class); mActivity.mVersionList = Tools.GLOBAL_GSON.fromJson(DownloadUtils.downloadString("https://launchermeta.mojang.com/mc/game/version_manifest.json"), JMinecraftVersionList.class);
ArrayList<String> versionStringList = filter(mActivity.mVersionList.versions, new File(Tools.versnDir).listFiles()); ArrayList<String> versionStringList = filter(mActivity.mVersionList.versions, new File(Tools.versnDir).listFiles());
return versionStringList; return versionStringList;

View file

@ -11,7 +11,7 @@ public class LauncherProfiles
try { try {
if (mainProfileJson == null) { if (mainProfileJson == null) {
if (launcherProfilesFile.exists()) { if (launcherProfilesFile.exists()) {
mainProfileJson = new Gson().fromJson(Tools.read(launcherProfilesFile.getAbsolutePath()), MinecraftLauncherProfiles.class); mainProfileJson = Tools.GLOBAL_GSON.fromJson(Tools.read(launcherProfilesFile.getAbsolutePath()), MinecraftLauncherProfiles.class);
} else { } else {
mainProfileJson = new MinecraftLauncherProfiles(); mainProfileJson = new MinecraftLauncherProfiles();
} }

View file

@ -1,5 +1,6 @@
package net.kdt.pojavlaunch.value.launcherprofiles; package net.kdt.pojavlaunch.value.launcherprofiles;
import com.google.gson.*; import com.google.gson.*;
import net.kdt.pojavlaunch.*;
public class MinecraftLauncherProfiles public class MinecraftLauncherProfiles
{ {
@ -13,6 +14,6 @@ public class MinecraftLauncherProfiles
public MinecraftSelectedUser selectedUser; public MinecraftSelectedUser selectedUser;
public String toJson() { public String toJson() {
return new Gson().toJson(this); return Tools.GLOBAL_GSON.toJson(this);
} }
} }