android code cleanup

This commit is contained in:
Geoffrey Goh
2016-03-15 01:41:22 -07:00
parent e0b9266057
commit f406ecd626
10 changed files with 124 additions and 151 deletions

View File

@@ -91,9 +91,8 @@ public class CodePush {
this.isDebugMode = isDebugMode;
this.mainActivity = mainActivity;
PackageInfo pInfo = null;
try {
pInfo = applicationContext.getPackageManager().getPackageInfo(applicationContext.getPackageName(), 0);
PackageInfo pInfo = applicationContext.getPackageManager().getPackageInfo(applicationContext.getPackageName(), 0);
appVersion = pInfo.versionName;
buildVersion = pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
@@ -110,11 +109,10 @@ public class CodePush {
}
}
public long getBinaryResourcesModifiedTime() {
ApplicationInfo ai = null;
private long getBinaryResourcesModifiedTime() {
ZipFile applicationFile = null;
try {
ai = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), 0);
ApplicationInfo ai = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), 0);
applicationFile = new ZipFile(ai.sourceDir);
ZipEntry classesDexEntry = applicationFile.getEntry(RESOURCES_BUNDLE);
return classesDexEntry.getTime();
@@ -155,7 +153,7 @@ public class CodePush {
String packageAppVersion = CodePushUtils.tryGetString(packageMetadata, "appVersion");
if (binaryModifiedDateDuringPackageInstall != null &&
binaryModifiedDateDuringPackageInstall == binaryResourcesModifiedTime &&
(this.isUsingTestConfiguration() || this.appVersion.equals(packageAppVersion))) {
(isUsingTestConfiguration() || this.appVersion.equals(packageAppVersion))) {
CodePushUtils.logBundleUrl(packageFilePath);
isRunningBinaryVersion = false;
return packageFilePath;
@@ -183,8 +181,7 @@ public class CodePush {
}
try {
JSONArray failedUpdates = new JSONArray(failedUpdatesString);
return failedUpdates;
return new JSONArray(failedUpdatesString);
} catch (JSONException e) {
// Unrecognized data format, clear and replace with expected format.
JSONArray emptyArray = new JSONArray();
@@ -201,8 +198,7 @@ public class CodePush {
}
try {
JSONObject pendingUpdate = new JSONObject(pendingUpdateString);
return pendingUpdate;
return new JSONObject(pendingUpdateString);
} catch (JSONException e) {
// Should not happen.
CodePushUtils.log("Unable to parse pending update metadata " + pendingUpdateString +
@@ -251,9 +247,8 @@ public class CodePush {
JSONArray failedUpdates = getFailedUpdates();
if (packageHash != null) {
for (int i = 0; i < failedUpdates.length(); i++) {
JSONObject failedPackage = null;
try {
failedPackage = failedUpdates.getJSONObject(i);
JSONObject failedPackage = failedUpdates.getJSONObject(i);
String failedPackageHash = failedPackage.getString(PACKAGE_HASH_KEY);
if (packageHash.equals(failedPackageHash)) {
return true;
@@ -271,10 +266,9 @@ public class CodePush {
JSONObject pendingUpdate = getPendingUpdate();
try {
boolean updateIsPending = pendingUpdate != null &&
pendingUpdate.getBoolean(PENDING_UPDATE_IS_LOADING_KEY) == false &&
(packageHash == null || pendingUpdate.getString(PENDING_UPDATE_HASH_KEY).equals(packageHash));
return updateIsPending;
return pendingUpdate != null &&
!pendingUpdate.getBoolean(PENDING_UPDATE_IS_LOADING_KEY) &&
(packageHash == null || pendingUpdate.getString(PENDING_UPDATE_HASH_KEY).equals(packageHash));
}
catch (JSONException e) {
throw new CodePushUnknownException("Unable to read pending update metadata in isPendingUpdate.", e);
@@ -359,13 +353,13 @@ public class CodePush {
@ReactMethod
public void downloadUpdate(final ReadableMap updatePackage, final Promise promise) {
AsyncTask asyncTask = new AsyncTask() {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Object... params) {
protected Void doInBackground(Void... params) {
try {
WritableMap mutableUpdatePackage = CodePushUtils.convertReadableMapToWritableMap(updatePackage);
mutableUpdatePackage.putString(BINARY_MODIFIED_TIME_KEY, "" + getBinaryResourcesModifiedTime());
codePushPackage.downloadPackage(applicationContext, mutableUpdatePackage, CodePush.this.assetsBundleFileName, new DownloadProgressCallback() {
codePushPackage.downloadPackage(mutableUpdatePackage, CodePush.this.assetsBundleFileName, new DownloadProgressCallback() {
@Override
public void call(DownloadProgress downloadProgress) {
getReactApplicationContext()
@@ -374,15 +368,15 @@ public class CodePush {
}
});
WritableMap newPackage = codePushPackage.getPackage(CodePushUtils.tryGetString(updatePackage, codePushPackage.PACKAGE_HASH_KEY));
WritableMap newPackage = codePushPackage.getPackage(CodePushUtils.tryGetString(updatePackage, PACKAGE_HASH_KEY));
promise.resolve(newPackage);
} catch (IOException e) {
e.printStackTrace();
promise.reject(e.getMessage());
promise.reject(e);
} catch (CodePushInvalidUpdateException e) {
e.printStackTrace();
saveFailedUpdate(updatePackage);
promise.reject(e.getMessage());
promise.reject(e);
}
return null;
@@ -414,9 +408,9 @@ public class CodePush {
@ReactMethod
public void getCurrentPackage(final Promise promise) {
AsyncTask asyncTask = new AsyncTask() {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Object... params) {
protected Void doInBackground(Void... params) {
WritableMap currentPackage = codePushPackage.getCurrentPackage();
if (currentPackage == null) {
promise.resolve("");
@@ -429,8 +423,8 @@ public class CodePush {
Boolean isPendingUpdate = false;
if (currentPackage.hasKey(codePushPackage.PACKAGE_HASH_KEY)) {
String currentHash = currentPackage.getString(codePushPackage.PACKAGE_HASH_KEY);
if (currentPackage.hasKey(PACKAGE_HASH_KEY)) {
String currentHash = currentPackage.getString(PACKAGE_HASH_KEY);
isPendingUpdate = CodePush.this.isPendingUpdate(currentHash);
}
@@ -446,16 +440,16 @@ public class CodePush {
@ReactMethod
public void getNewStatusReport(final Promise promise) {
AsyncTask asyncTask = new AsyncTask() {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Object... params) {
protected Void doInBackground(Void... params) {
if (needToReportRollback) {
needToReportRollback = false;
JSONArray failedUpdates = getFailedUpdates();
if (failedUpdates != null && failedUpdates.length() > 0) {
try {
JSONObject lastFailedPackageJSON = failedUpdates.getJSONObject(failedUpdates.length() - 1);
WritableMap lastFailedPackage = CodePushUtils.convertJsonObjectToWriteable(lastFailedPackageJSON);
WritableMap lastFailedPackage = CodePushUtils.convertJsonObjectToWritable(lastFailedPackageJSON);
WritableMap failedStatusReport = codePushTelemetryManager.getRollbackReport(lastFailedPackage);
if (failedStatusReport != null) {
promise.resolve(failedStatusReport);
@@ -492,62 +486,57 @@ public class CodePush {
@ReactMethod
public void installUpdate(final ReadableMap updatePackage, final int installMode, final int minimumBackgroundDuration, final Promise promise) {
AsyncTask asyncTask = new AsyncTask() {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Object... params) {
try {
codePushPackage.installPackage(updatePackage, isPendingUpdate(null));
protected Void doInBackground(Void... params) {
codePushPackage.installPackage(updatePackage, isPendingUpdate(null));
String pendingHash = CodePushUtils.tryGetString(updatePackage, codePushPackage.PACKAGE_HASH_KEY);
if (pendingHash == null) {
throw new CodePushUnknownException("Update package to be installed has no hash.");
} else {
savePendingUpdate(pendingHash, /* isLoading */false);
}
if (installMode == CodePushInstallMode.ON_NEXT_RESUME.getValue()) {
// Store the minimum duration on the native module as an instance
// variable instead of relying on a closure below, so that any
// subsequent resume-based installs could override it.
CodePushNativeModule.this.minimumBackgroundDuration = minimumBackgroundDuration;
if (lifecycleEventListener == null) {
// Ensure we do not add the listener twice.
lifecycleEventListener = new LifecycleEventListener() {
private Date lastPausedDate = null;
@Override
public void onHostResume() {
// Determine how long the app was in the background and ensure
// that it meets the minimum duration amount of time.
long durationInBackground = (new Date().getTime() - lastPausedDate.getTime()) / 1000;
if (durationInBackground >= CodePushNativeModule.this.minimumBackgroundDuration) {
loadBundle();
}
}
@Override
public void onHostPause() {
// Save the current time so that when the app is later
// resumed, we can detect how long it was in the background.
lastPausedDate = new Date();
}
@Override
public void onHostDestroy() {
}
};
getReactApplicationContext().addLifecycleEventListener(lifecycleEventListener);
}
}
promise.resolve("");
} catch (IOException e) {
e.printStackTrace();
promise.reject(e.getMessage());
String pendingHash = CodePushUtils.tryGetString(updatePackage, PACKAGE_HASH_KEY);
if (pendingHash == null) {
throw new CodePushUnknownException("Update package to be installed has no hash.");
} else {
savePendingUpdate(pendingHash, /* isLoading */false);
}
if (installMode == CodePushInstallMode.ON_NEXT_RESUME.getValue()) {
// Store the minimum duration on the native module as an instance
// variable instead of relying on a closure below, so that any
// subsequent resume-based installs could override it.
CodePushNativeModule.this.minimumBackgroundDuration = minimumBackgroundDuration;
if (lifecycleEventListener == null) {
// Ensure we do not add the listener twice.
lifecycleEventListener = new LifecycleEventListener() {
private Date lastPausedDate = null;
@Override
public void onHostResume() {
// Determine how long the app was in the background and ensure
// that it meets the minimum duration amount of time.
long durationInBackground = (new Date().getTime() - lastPausedDate.getTime()) / 1000;
if (durationInBackground >= CodePushNativeModule.this.minimumBackgroundDuration) {
loadBundle();
}
}
@Override
public void onHostPause() {
// Save the current time so that when the app is later
// resumed, we can detect how long it was in the background.
lastPausedDate = new Date();
}
@Override
public void onHostDestroy() {
}
};
getReactApplicationContext().addLifecycleEventListener(lifecycleEventListener);
}
}
promise.resolve("");
return null;
}
};
@@ -631,12 +620,12 @@ public class CodePush {
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return new ArrayList();
return new ArrayList<>();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) {
return new ArrayList();
return new ArrayList<>();
}
}
}

View File

@@ -11,7 +11,7 @@ import com.facebook.react.bridge.ReactMethod;
public class CodePushDialog extends ReactContextBaseJavaModule{
Activity mainActivity;
private Activity mainActivity;
public CodePushDialog(ReactApplicationContext reactContext, Activity mainActivity) {
super(reactContext);

View File

@@ -6,7 +6,7 @@ public enum CodePushInstallMode {
ON_NEXT_RESUME(2);
private final int value;
private CodePushInstallMode(int value) {
CodePushInstallMode(int value) {
this.value = value;
}
public int getValue() {

View File

@@ -1,7 +1,5 @@
package com.microsoft.codepush.react;
import android.content.Context;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
@@ -21,19 +19,19 @@ import java.nio.ByteBuffer;
public class CodePushPackage {
public final String CODE_PUSH_FOLDER_PREFIX = "CodePush";
public final String CURRENT_PACKAGE_KEY = "currentPackage";
public final String DIFF_MANIFEST_FILE_NAME = "hotcodepush.json";
public final int DOWNLOAD_BUFFER_SIZE = 1024 * 256;
public final String DOWNLOAD_FILE_NAME = "download.zip";
public final String DOWNLOAD_URL_KEY = "downloadUrl";
public final String PACKAGE_FILE_NAME = "app.json";
public final String PACKAGE_HASH_KEY = "packageHash";
public final String PREVIOUS_PACKAGE_KEY = "previousPackage";
public final String RELATIVE_BUNDLE_PATH_KEY = "bundlePath";
public final String STATUS_FILE = "codepush.json";
public final String UNZIPPED_FOLDER_NAME = "unzipped";
public final String UPDATE_BUNDLE_FILE_NAME = "app.jsbundle";
private final String CODE_PUSH_FOLDER_PREFIX = "CodePush";
private final String CURRENT_PACKAGE_KEY = "currentPackage";
private final String DIFF_MANIFEST_FILE_NAME = "hotcodepush.json";
private final int DOWNLOAD_BUFFER_SIZE = 1024 * 256;
private final String DOWNLOAD_FILE_NAME = "download.zip";
private final String DOWNLOAD_URL_KEY = "downloadUrl";
private final String PACKAGE_FILE_NAME = "app.json";
private final String PACKAGE_HASH_KEY = "packageHash";
private final String PREVIOUS_PACKAGE_KEY = "previousPackage";
private final String RELATIVE_BUNDLE_PATH_KEY = "bundlePath";
private final String STATUS_FILE = "codepush.json";
private final String UNZIPPED_FOLDER_NAME = "unzipped";
private final String UPDATE_BUNDLE_FILE_NAME = "app.jsbundle";
private String documentsDirectory;
@@ -41,19 +39,19 @@ public class CodePushPackage {
this.documentsDirectory = documentsDirectory;
}
public String getDownloadFilePath() {
private String getDownloadFilePath() {
return CodePushUtils.appendPathComponent(getCodePushPath(), DOWNLOAD_FILE_NAME);
}
public String getUnzippedFolderPath() {
private String getUnzippedFolderPath() {
return CodePushUtils.appendPathComponent(getCodePushPath(), UNZIPPED_FOLDER_NAME);
}
public String getDocumentsDirectory() {
private String getDocumentsDirectory() {
return documentsDirectory;
}
public String getCodePushPath() {
private String getCodePushPath() {
String codePushPath = CodePushUtils.appendPathComponent(getDocumentsDirectory(), CODE_PUSH_FOLDER_PREFIX);
if (CodePush.isUsingTestConfiguration()) {
codePushPath = CodePushUtils.appendPathComponent(codePushPath, "TestPackages");
@@ -62,7 +60,7 @@ public class CodePushPackage {
return codePushPath;
}
public String getStatusFilePath() {
private String getStatusFilePath() {
return CodePushUtils.appendPathComponent(getCodePushPath(), STATUS_FILE);
}
@@ -151,7 +149,7 @@ public class CodePushPackage {
}
}
public void downloadPackage(Context applicationContext, ReadableMap updatePackage, String expectedBundleFileName,
public void downloadPackage(ReadableMap updatePackage, String expectedBundleFileName,
DownloadProgressCallback progressCallback) throws IOException {
String newUpdateHash = CodePushUtils.tryGetString(updatePackage, PACKAGE_HASH_KEY);
String newUpdateFolderPath = getPackageFolderPath(newUpdateHash);
@@ -163,7 +161,6 @@ public class CodePushPackage {
}
String downloadUrlString = CodePushUtils.tryGetString(updatePackage, DOWNLOAD_URL_KEY);
URL downloadUrl = null;
HttpURLConnection connection = null;
BufferedInputStream bin = null;
FileOutputStream fos = null;
@@ -173,7 +170,7 @@ public class CodePushPackage {
// Download the file while checking if it is a zip and notifying client of progress.
try {
downloadUrl = new URL(downloadUrlString);
URL downloadUrl = new URL(downloadUrlString);
connection = (HttpURLConnection) (downloadUrl.openConnection());
long totalBytes = connection.getContentLength();
@@ -206,7 +203,10 @@ public class CodePushPackage {
progressCallback.call(new DownloadProgress(totalBytes, receivedBytes));
}
assert totalBytes == receivedBytes;
if (totalBytes != receivedBytes) {
throw new CodePushUnknownException("Received " + receivedBytes + " bytes, expected " + totalBytes);
}
isZip = ByteBuffer.wrap(header).getInt() == 0x504b0304;
} catch (MalformedURLException e) {
throw new CodePushMalformedDataException(downloadUrlString, e);
@@ -266,7 +266,7 @@ public class CodePushPackage {
" in update package.", e);
}
updatePackage = CodePushUtils.convertJsonObjectToWriteable(updatePackageJSON);
updatePackage = CodePushUtils.convertJsonObjectToWritable(updatePackageJSON);
}
} else {
// File is a jsbundle, move it to a folder with the packageHash as its name
@@ -277,7 +277,7 @@ public class CodePushPackage {
CodePushUtils.writeReadableMapToFile(updatePackage, newUpdateMetadataPath);
}
public void installPackage(ReadableMap updatePackage, boolean removePendingUpdate) throws IOException {
public void installPackage(ReadableMap updatePackage, boolean removePendingUpdate) {
String packageHash = CodePushUtils.tryGetString(updatePackage, PACKAGE_HASH_KEY);
WritableMap info = getCurrentPackageInfo();
if (removePendingUpdate) {

View File

@@ -1,6 +1,6 @@
package com.microsoft.codepush.react;
public class CodePushUnknownException extends RuntimeException {
class CodePushUnknownException extends RuntimeException {
public CodePushUnknownException(String message, Throwable cause) {
super(message, cause);

View File

@@ -115,7 +115,7 @@ public class CodePushUpdateUtils {
}
public static void verifyHashForDiffUpdate(String folderPath, String expectedHash) {
ArrayList<String> updateContentsManifest = new ArrayList<String>();
ArrayList<String> updateContentsManifest = new ArrayList<>();
addContentsOfFolderToManifest(folderPath, "", updateContentsManifest);
Collections.sort(updateContentsManifest);
JSONArray updateContentsJSONArray = new JSONArray();

View File

@@ -15,29 +15,22 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class CodePushUtils {
public static final String CODE_PUSH_TAG = "CodePush";
public static final String REACT_NATIVE_LOG_TAG = "ReactNative";
public static String appendPathComponent(String basePath, String appendPathComponent) {
return new File(basePath, appendPathComponent).getAbsolutePath();
}
public static WritableArray convertJsonArrayToWriteable(JSONArray jsonArr) {
public static WritableArray convertJsonArrayToWritable(JSONArray jsonArr) {
WritableArray arr = Arguments.createArray();
for (int i=0; i<jsonArr.length(); i++) {
Object obj = null;
@@ -49,9 +42,9 @@ public class CodePushUtils {
}
if (obj instanceof JSONObject)
arr.pushMap(convertJsonObjectToWriteable((JSONObject) obj));
arr.pushMap(convertJsonObjectToWritable((JSONObject) obj));
else if (obj instanceof JSONArray)
arr.pushArray(convertJsonArrayToWriteable((JSONArray) obj));
arr.pushArray(convertJsonArrayToWritable((JSONArray) obj));
else if (obj instanceof String)
arr.pushString((String) obj);
else if (obj instanceof Double)
@@ -69,7 +62,7 @@ public class CodePushUtils {
return arr;
}
public static WritableMap convertJsonObjectToWriteable(JSONObject jsonObj) {
public static WritableMap convertJsonObjectToWritable(JSONObject jsonObj) {
WritableMap map = Arguments.createMap();
Iterator<String> it = jsonObj.keys();
while(it.hasNext()){
@@ -83,9 +76,9 @@ public class CodePushUtils {
}
if (obj instanceof JSONObject)
map.putMap(key, convertJsonObjectToWriteable((JSONObject) obj));
map.putMap(key, convertJsonObjectToWritable((JSONObject) obj));
else if (obj instanceof JSONArray)
map.putArray(key, convertJsonArrayToWriteable((JSONArray) obj));
map.putArray(key, convertJsonArrayToWritable((JSONArray) obj));
else if (obj instanceof String)
map.putString(key, (String) obj);
else if (obj instanceof Double)
@@ -105,7 +98,7 @@ public class CodePushUtils {
public static WritableMap convertReadableMapToWritableMap(ReadableMap map) {
JSONObject mapJSON = convertReadableToJsonObject(map);
return convertJsonObjectToWriteable(mapJSON);
return convertJsonObjectToWritable(mapJSON);
}
public static JSONArray convertReadableToJsonArray(ReadableArray arr) {
@@ -204,16 +197,13 @@ public class CodePushUtils {
}
public static WritableMap getWritableMapFromFile(String filePath) throws IOException {
String content = FileUtils.readFileToString(filePath);
JSONObject json = null;
try {
json = new JSONObject(content);
return convertJsonObjectToWriteable(json);
JSONObject json = new JSONObject(content);
return convertJsonObjectToWritable(json);
} catch (JSONException jsonException) {
throw new CodePushMalformedDataException(filePath, jsonException);
}
}
public static void log(String message) {

View File

@@ -3,9 +3,9 @@ package com.microsoft.codepush.react;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
public class DownloadProgress {
public long totalBytes;
public long receivedBytes;
class DownloadProgress {
private long totalBytes;
private long receivedBytes;
public DownloadProgress (long totalBytes, long receivedBytes){
this.totalBytes = totalBytes;

View File

@@ -1,5 +1,5 @@
package com.microsoft.codepush.react;
public interface DownloadProgressCallback {
interface DownloadProgressCallback {
void call(DownloadProgress downloadProgress);
}

View File

@@ -9,12 +9,11 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class FileUtils {
public static final int WRITE_BUFFER_SIZE = 1024 * 8;
private static final int WRITE_BUFFER_SIZE = 1024 * 8;
public static void copyDirectoryContents(String sourceDirectoryPath, String destinationDirectoryPath) throws IOException {
File sourceDir = new File(sourceDirectoryPath);
@@ -55,21 +54,16 @@ public class FileUtils {
}
}
public static boolean createFolderAtPath(String filePath) {
File file = new File(filePath);
return file.mkdir();
}
public static void deleteDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
if (files != null) {
for (int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
for (File file : files) {
if(file.isDirectory()) {
deleteDirectory(file);
}
else {
files[i].delete();
file.delete();
}
}
}
@@ -88,12 +82,12 @@ public class FileUtils {
public static void deleteFileOrFolderSilently(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteFileOrFolderSilently(files[i]);
for (File fileEntry : files) {
if (fileEntry.isDirectory()) {
deleteFileOrFolderSilently(fileEntry);
} else {
if (!file.delete()) {
files[i].delete();
fileEntry.delete();
}
}
}