From ae77f48a6d150409565e45330b9f2fc60ce09337 Mon Sep 17 00:00:00 2001 From: ardevd Date: Thu, 11 Apr 2019 14:25:00 +0200 Subject: [PATCH] utils: use try-with-resources to properly close Closable. (#522) Use try-with-resources to properly close Closable --- .../com/nextcloud/talk/utils/PushUtils.java | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/utils/PushUtils.java b/app/src/main/java/com/nextcloud/talk/utils/PushUtils.java index 3160af5b8..e079e7d25 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/PushUtils.java +++ b/app/src/main/java/com/nextcloud/talk/utils/PushUtils.java @@ -24,7 +24,9 @@ import android.content.Context; import android.text.TextUtils; import android.util.Base64; import android.util.Log; + import autodagger.AutoInjector; + import com.bluelinelabs.logansquare.LoganSquare; import com.nextcloud.talk.R; import com.nextcloud.talk.api.NcApi; @@ -36,12 +38,15 @@ import com.nextcloud.talk.models.json.push.PushConfigurationState; import com.nextcloud.talk.models.json.push.PushRegistrationOverall; import com.nextcloud.talk.utils.database.user.UserUtils; import com.nextcloud.talk.utils.preferences.AppPreferences; + import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; + import org.greenrobot.eventbus.EventBus; import javax.inject.Inject; + import java.io.*; import java.security.*; import java.security.spec.InvalidKeySpecException; @@ -128,15 +133,18 @@ public class PushUtils { private int saveKeyToFile(Key key, String path) { byte[] encoded = key.getEncoded(); - FileOutputStream keyFileOutputStream = null; + try { if (!new File(path).exists()) { - new File(path).createNewFile(); + if (!new File(path).createNewFile()) { + return -1; + } + } + + try (FileOutputStream keyFileOutputStream = new FileOutputStream(path)) { + keyFileOutputStream.write(encoded); + return 0; } - keyFileOutputStream = new FileOutputStream(path); - keyFileOutputStream.write(encoded); - keyFileOutputStream.close(); - return 0; } catch (FileNotFoundException e) { Log.d(TAG, "Failed to save key to file"); } catch (IOException e) { @@ -397,12 +405,9 @@ public class PushUtils { path = privateKeyFile.getAbsolutePath(); } - FileInputStream fileInputStream = null; - try { - fileInputStream = new FileInputStream(path); + try (FileInputStream fileInputStream = new FileInputStream(path)) { byte[] bytes = new byte[fileInputStream.available()]; fileInputStream.read(bytes); - fileInputStream.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA");