From 0edc7a862955d28f3c385425d6c2576a2e7a0dcb Mon Sep 17 00:00:00 2001 From: Unpublished Date: Fri, 22 Feb 2019 16:59:23 +0100 Subject: [PATCH] use try-with-resources --- .../java/eu/faircode/email/ActivityEml.java | 11 +-- .../java/eu/faircode/email/ActivitySetup.java | 20 ++---- .../java/eu/faircode/email/ActivityView.java | 48 +++++-------- .../eu/faircode/email/AdapterMessage.java | 31 +++----- .../java/eu/faircode/email/ApplicationEx.java | 12 +--- .../java/eu/faircode/email/ContactInfo.java | 52 ++++++-------- app/src/main/java/eu/faircode/email/DB.java | 14 +--- .../eu/faircode/email/FragmentAccount.java | 14 +--- .../eu/faircode/email/FragmentCompose.java | 38 ++-------- .../eu/faircode/email/FragmentIdentity.java | 5 +- .../eu/faircode/email/FragmentQuickSetup.java | 12 +--- .../java/eu/faircode/email/FragmentRule.java | 19 ++--- .../main/java/eu/faircode/email/Helper.java | 70 ++++--------------- .../java/eu/faircode/email/HtmlHelper.java | 26 ++----- .../java/eu/faircode/email/MessageHelper.java | 36 ++++------ .../eu/faircode/email/ServiceSynchronize.java | 25 ++----- 16 files changed, 117 insertions(+), 316 deletions(-) diff --git a/app/src/main/java/eu/faircode/email/ActivityEml.java b/app/src/main/java/eu/faircode/email/ActivityEml.java index fd2339ce4d..122bcf6e64 100644 --- a/app/src/main/java/eu/faircode/email/ActivityEml.java +++ b/app/src/main/java/eu/faircode/email/ActivityEml.java @@ -71,11 +71,9 @@ public class ActivityEml extends ActivityBase { Result result = new Result(); - InputStream is = null; - try { - ContentResolver resolver = context.getContentResolver(); - AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); - is = new BufferedInputStream(descriptor.createInputStream()); + ContentResolver resolver = context.getContentResolver(); + AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); + try (InputStream is = new BufferedInputStream(descriptor.createInputStream())) { Properties props = MessageHelper.getSessionProperties(Helper.AUTH_TYPE_PASSWORD, null, false); Session isession = Session.getInstance(props, null); @@ -112,9 +110,6 @@ public class ActivityEml extends ActivityBase { result.eml = new String(bos.toByteArray()); return result; - } finally { - if (is != null) - is.close(); } } diff --git a/app/src/main/java/eu/faircode/email/ActivitySetup.java b/app/src/main/java/eu/faircode/email/ActivitySetup.java index 8285f0b16b..eca03ea495 100644 --- a/app/src/main/java/eu/faircode/email/ActivitySetup.java +++ b/app/src/main/java/eu/faircode/email/ActivitySetup.java @@ -533,9 +533,7 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On ContentResolver resolver = context.getContentResolver(); DocumentFile file = DocumentFile.fromSingleUri(context, uri); - OutputStream raw = null; - try { - raw = new BufferedOutputStream(resolver.openOutputStream(uri)); + try (OutputStream raw = new BufferedOutputStream(resolver.openOutputStream(uri))) { Log.i("Writing URI=" + uri + " name=" + file.getName() + " virtual=" + file.isVirtual()); if (TextUtils.isEmpty(password)) @@ -564,9 +562,6 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On raw.flush(); Log.i("Exported data"); - } finally { - if (raw != null) - raw.close(); } return null; @@ -603,13 +598,11 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On throw new IllegalArgumentException(context.getString(R.string.title_no_stream)); } - InputStream raw = null; StringBuilder data = new StringBuilder(); - try { - Log.i("Reading URI=" + uri); - ContentResolver resolver = context.getContentResolver(); - AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); - raw = new BufferedInputStream(descriptor.createInputStream()); + Log.i("Reading URI=" + uri); + ContentResolver resolver = context.getContentResolver(); + AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(uri, "*/*", null); + try (InputStream raw = new BufferedInputStream(descriptor.createInputStream())) { InputStream in; if (TextUtils.isEmpty(password)) @@ -636,9 +629,6 @@ public class ActivitySetup extends ActivityBilling implements FragmentManager.On String line; while ((line = reader.readLine()) != null) data.append(line); - } finally { - if (raw != null) - raw.close(); } Log.i("Importing data"); diff --git a/app/src/main/java/eu/faircode/email/ActivityView.java b/app/src/main/java/eu/faircode/email/ActivityView.java index e2b469e265..c7f3bda5b0 100644 --- a/app/src/main/java/eu/faircode/email/ActivityView.java +++ b/app/src/main/java/eu/faircode/email/ActivityView.java @@ -584,15 +584,10 @@ public class ActivityView extends ActivityBilling implements FragmentManager.OnB if (file.exists()) { StringBuilder sb = new StringBuilder(); try { - BufferedReader in = null; - try { - String line; - in = new BufferedReader(new FileReader(file)); + String line; + try (BufferedReader in = new BufferedReader(new FileReader(file))) { while ((line = in.readLine()) != null) sb.append(line).append("\r\n"); - } finally { - if (in != null) - in.close(); } return Helper.getDebugInfo(context, R.string.title_crash_info_remark, null, sb.toString()).id; @@ -740,25 +735,23 @@ public class ActivityView extends ActivityBilling implements FragmentManager.OnB List shortcuts = new ArrayList<>(); if (hasPermission(Manifest.permission.READ_CONTACTS)) { - Cursor cursor = null; - try { - // https://developer.android.com/guide/topics/providers/contacts-provider#ObsoleteData - cursor = getContentResolver().query( - ContactsContract.CommonDataKinds.Email.CONTENT_URI, - new String[]{ - ContactsContract.RawContacts._ID, - ContactsContract.Contacts.LOOKUP_KEY, - ContactsContract.Contacts.DISPLAY_NAME, - ContactsContract.CommonDataKinds.Email.DATA, - ContactsContract.Contacts.STARRED, - ContactsContract.Contacts.TIMES_CONTACTED, - ContactsContract.Contacts.LAST_TIME_CONTACTED - }, - ContactsContract.CommonDataKinds.Email.DATA + " <> ''", - null, - ContactsContract.Contacts.STARRED + " DESC" + - ", " + ContactsContract.Contacts.TIMES_CONTACTED + " DESC" + - ", " + ContactsContract.Contacts.LAST_TIME_CONTACTED + " DESC"); + // https://developer.android.com/guide/topics/providers/contacts-provider#ObsoleteData + try (Cursor cursor = getContentResolver().query( + ContactsContract.CommonDataKinds.Email.CONTENT_URI, + new String[]{ + ContactsContract.RawContacts._ID, + ContactsContract.Contacts.LOOKUP_KEY, + ContactsContract.Contacts.DISPLAY_NAME, + ContactsContract.CommonDataKinds.Email.DATA, + ContactsContract.Contacts.STARRED, + ContactsContract.Contacts.TIMES_CONTACTED, + ContactsContract.Contacts.LAST_TIME_CONTACTED + }, + ContactsContract.CommonDataKinds.Email.DATA + " <> ''", + null, + ContactsContract.Contacts.STARRED + " DESC" + + ", " + ContactsContract.Contacts.TIMES_CONTACTED + " DESC" + + ", " + ContactsContract.Contacts.LAST_TIME_CONTACTED + " DESC")) { while (cursor != null && cursor.moveToNext()) try { long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.RawContacts._ID)); @@ -801,9 +794,6 @@ public class ActivityView extends ActivityBilling implements FragmentManager.OnB } catch (Throwable ex) { Log.e(ex); } - } finally { - if (cursor != null) - cursor.close(); } } diff --git a/app/src/main/java/eu/faircode/email/AdapterMessage.java b/app/src/main/java/eu/faircode/email/AdapterMessage.java index e2a3395dc5..2f5d8274dd 100644 --- a/app/src/main/java/eu/faircode/email/AdapterMessage.java +++ b/app/src/main/java/eu/faircode/email/AdapterMessage.java @@ -1122,16 +1122,14 @@ public class AdapterMessage extends RecyclerView.Adapter'; EntityAttachment attachment = DB.getInstance(context).attachment().getAttachment(id, cid); if (attachment != null && attachment.available) { - InputStream is = null; - try { - File file = EntityAttachment.getFile(context, attachment.id); - - is = new BufferedInputStream(new FileInputStream(file)); + File file = EntityAttachment.getFile(context, attachment.id); + try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { byte[] bytes = new byte[(int) file.length()]; if (is.read(bytes) != bytes.length) throw new IOException("length"); @@ -1391,9 +1383,6 @@ public class AdapterMessage extends RecyclerView.Adapter" + "

"); - BufferedWriter out = null; - try { - out = new BufferedWriter(new FileWriter(file)); + try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) { out.write(body); out.write(html); - } finally { - if (out != null) - out.close(); } refFile.delete(); @@ -1086,16 +1081,11 @@ public class FragmentCompose extends FragmentBase { File file1 = EntityAttachment.getFile(context, attachment1.id); - OutputStream os1 = null; - try { - byte[] bytes1 = encrypted.toByteArray(); - os1 = new BufferedOutputStream(new FileOutputStream(file1)); + byte[] bytes1 = encrypted.toByteArray(); + try (OutputStream os1 = new BufferedOutputStream(new FileOutputStream(file1))) { os1.write(bytes1); db.attachment().setDownloaded(attachment1.id, (long) bytes1.length); - } finally { - if (os1 != null) - os1.close(); } EntityAttachment attachment2 = new EntityAttachment(); @@ -1108,16 +1098,11 @@ public class FragmentCompose extends FragmentBase { File file2 = EntityAttachment.getFile(context, attachment2.id); - OutputStream os2 = null; - try { - byte[] bytes2 = key.getByteArrayExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE); - os2 = new BufferedOutputStream(new FileOutputStream(file2)); + byte[] bytes2 = key.getByteArrayExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE); + try (OutputStream os2 = new BufferedOutputStream(new FileOutputStream(file2))) { os2.write(bytes2); db.attachment().setDownloaded(attachment2.id, (long) bytes2.length); - } finally { - if (os2 != null) - os2.close(); } db.setTransactionSuccessful(); @@ -1357,17 +1342,12 @@ public class FragmentCompose extends FragmentBase { String name = uri.getLastPathSegment(); String s = null; - Cursor cursor = null; - try { - cursor = context.getContentResolver().query(uri, null, null, null, null, null); + try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null, null)) { if (cursor != null && cursor.moveToFirst()) { name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); s = cursor.getString(cursor.getColumnIndex(OpenableColumns.SIZE)); } - } finally { - if (cursor != null) - cursor.close(); } DB db = DB.getInstance(context); @@ -1456,16 +1436,12 @@ public class FragmentCompose extends FragmentBase { if (scaled != null) { Log.i("Image target size=" + scaled.getWidth() + "x" + scaled.getHeight()); - OutputStream out = null; - try { - out = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { scaled.compress("image/jpeg".equals(attachment.type) ? Bitmap.CompressFormat.JPEG : Bitmap.CompressFormat.PNG, REDUCED_IMAGE_QUALITY, out); } finally { - if (out != null) - out.close(); scaled.recycle(); } diff --git a/app/src/main/java/eu/faircode/email/FragmentIdentity.java b/app/src/main/java/eu/faircode/email/FragmentIdentity.java index f4f5cd0454..418962aa9d 100644 --- a/app/src/main/java/eu/faircode/email/FragmentIdentity.java +++ b/app/src/main/java/eu/faircode/email/FragmentIdentity.java @@ -616,8 +616,7 @@ public class FragmentIdentity extends FragmentBase { // Create transport String protocol = (starttls ? "smtp" : "smtps"); - Transport itransport = isession.getTransport(protocol); - try { + try (Transport itransport = isession.getTransport(protocol)) { try { itransport.connect(host, Integer.parseInt(port), user, password); } catch (AuthenticationFailedException ex) { @@ -627,8 +626,6 @@ public class FragmentIdentity extends FragmentBase { } else throw ex; } - } finally { - itransport.close(); } } diff --git a/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java b/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java index 3f2477c8ed..5e1455bb36 100644 --- a/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java +++ b/app/src/main/java/eu/faircode/email/FragmentQuickSetup.java @@ -255,9 +255,7 @@ public class FragmentQuickSetup extends FragmentBase { Properties props = MessageHelper.getSessionProperties(auth_type, null, false); Session isession = Session.getInstance(props, null); isession.setDebug(true); - IMAPStore istore = null; - try { - istore = (IMAPStore) isession.getStore(provider.imap_starttls ? "imap" : "imaps"); + try (IMAPStore istore = (IMAPStore) isession.getStore(provider.imap_starttls ? "imap" : "imaps")) { istore.connect(provider.imap_host, provider.imap_port, user, password); separator = istore.getDefaultFolder().getSeparator(); @@ -295,9 +293,6 @@ public class FragmentQuickSetup extends FragmentBase { if (!inbox || !drafts) throw new IllegalArgumentException( context.getString(R.string.title_setup_no_settings, dparts[1])); - } finally { - if (istore != null) - istore.close(); } } @@ -305,11 +300,8 @@ public class FragmentQuickSetup extends FragmentBase { Properties props = MessageHelper.getSessionProperties(auth_type, null, false); Session isession = Session.getInstance(props, null); isession.setDebug(true); - Transport itransport = isession.getTransport(provider.smtp_starttls ? "smtp" : "smtps"); - try { + try (Transport itransport = isession.getTransport(provider.smtp_starttls ? "smtp" : "smtps")) { itransport.connect(provider.smtp_host, provider.smtp_port, user, password); - } finally { - itransport.close(); } } diff --git a/app/src/main/java/eu/faircode/email/FragmentRule.java b/app/src/main/java/eu/faircode/email/FragmentRule.java index f5a48c315d..d2f8284e4f 100644 --- a/app/src/main/java/eu/faircode/email/FragmentRule.java +++ b/app/src/main/java/eu/faircode/email/FragmentRule.java @@ -296,23 +296,18 @@ public class FragmentRule extends FragmentBase { } private void handlePickContact(Intent data) { - Cursor cursor = null; - try { - Uri uri = data.getData(); - if (uri != null) - cursor = getContext().getContentResolver().query(uri, - new String[]{ - ContactsContract.CommonDataKinds.Email.ADDRESS - }, - null, null, null); + Uri uri = data.getData(); + if (uri == null) return; + try (Cursor cursor = getContext().getContentResolver().query(uri, + new String[]{ + ContactsContract.CommonDataKinds.Email.ADDRESS + }, + null, null, null)) { if (cursor != null && cursor.moveToFirst()) etSender.setText(cursor.getString(0)); } catch (Throwable ex) { Log.e(ex); Helper.unexpectedError(getContext(), getViewLifecycleOwner(), ex); - } finally { - if (cursor != null) - cursor.close(); } } diff --git a/app/src/main/java/eu/faircode/email/Helper.java b/app/src/main/java/eu/faircode/email/Helper.java index b787caf649..569564e637 100644 --- a/app/src/main/java/eu/faircode/email/Helper.java +++ b/app/src/main/java/eu/faircode/email/Helper.java @@ -488,10 +488,8 @@ public class Helper { attachment.progress = 0; attachment.id = db.attachment().insertAttachment(attachment); - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); @@ -501,9 +499,6 @@ public class Helper { size += write(os, key + "=" + settings.get(key) + "\r\n"); db.attachment().setDownloaded(attachment.id, size); - } finally { - if (os != null) - os.close(); } } @@ -519,10 +514,8 @@ public class Helper { attachment.progress = 0; attachment.id = db.attachment().insertAttachment(attachment); - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); @@ -537,9 +530,6 @@ public class Helper { } db.attachment().setDownloaded(attachment.id, size); - } finally { - if (os != null) - os.close(); } } @@ -555,10 +545,8 @@ public class Helper { log.progress = 0; log.id = db.attachment().insertAttachment(log); - OutputStream os = null; File file = EntityAttachment.getFile(context, log.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; long from = new Date().getTime() - 24 * 3600 * 1000L; @@ -568,9 +556,6 @@ public class Helper { size += write(os, String.format("%s %s\r\n", DF.format(entry.time), entry.data)); db.attachment().setDownloaded(log.id, size); - } finally { - if (os != null) - os.close(); } } @@ -586,10 +571,8 @@ public class Helper { attachment.progress = 0; attachment.id = db.attachment().insertAttachment(attachment); - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { long size = 0; DateFormat DF = SimpleDateFormat.getTimeInstance(); @@ -603,9 +586,6 @@ public class Helper { op.error)); db.attachment().setDownloaded(attachment.id, size); - } finally { - if (os != null) - os.close(); } } @@ -622,11 +602,8 @@ public class Helper { attachment.id = db.attachment().insertAttachment(attachment); Process proc = null; - BufferedReader br = null; - OutputStream os = null; File file = EntityAttachment.getFile(context, attachment.id); - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { String[] cmd = new String[]{"logcat", "-d", @@ -634,20 +611,17 @@ public class Helper { //"-t", "1000", Log.TAG + ":I"}; proc = Runtime.getRuntime().exec(cmd); - br = new BufferedReader(new InputStreamReader(proc.getInputStream())); long size = 0; + try (BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { + String line; + while ((line = br.readLine()) != null) + size += write(os, line + "\r\n"); + } - String line; - while ((line = br.readLine()) != null) - size += write(os, line + "\r\n"); db.attachment().setDownloaded(attachment.id, size); } finally { - if (os != null) - os.close(); - if (br != null) - br.close(); if (proc != null) proc.destroy(); } @@ -682,20 +656,13 @@ public class Helper { } static void writeText(File file, String content) throws IOException { - BufferedWriter out = null; - try { - out = new BufferedWriter(new FileWriter(file)); + try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) { out.write(content == null ? "" : content); - } finally { - if (out != null) - out.close(); } } static String readText(File file) throws IOException { - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(file)); + try (BufferedReader in = new BufferedReader(new FileReader(file))) { StringBuilder body = new StringBuilder(); String line; while ((line = in.readLine()) != null) { @@ -703,26 +670,17 @@ public class Helper { body.append('\n'); } return body.toString(); - } finally { - if (in != null) - in.close(); } } static void copy(File src, File dst) throws IOException { - InputStream in = new BufferedInputStream(new FileInputStream(src)); - try { - OutputStream out = new BufferedOutputStream(new FileOutputStream(dst)); - try { + try (InputStream in = new BufferedInputStream(new FileInputStream(src))) { + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) { byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); - } finally { - out.close(); } - } finally { - in.close(); } } diff --git a/app/src/main/java/eu/faircode/email/HtmlHelper.java b/app/src/main/java/eu/faircode/email/HtmlHelper.java index d35986daec..ef1998eded 100644 --- a/app/src/main/java/eu/faircode/email/HtmlHelper.java +++ b/app/src/main/java/eu/faircode/email/HtmlHelper.java @@ -261,24 +261,16 @@ public class HtmlHelper { } try { - InputStream probe = null; BitmapFactory.Options options = new BitmapFactory.Options(); - try { - Log.i("Probe " + source); - probe = new URL(source).openStream(); + Log.i("Probe " + source); + try (InputStream probe = new URL(source).openStream()) { options.inJustDecodeBounds = true; BitmapFactory.decodeStream(probe, null, options); - } finally { - if (probe != null) - probe.close(); } + Log.i("Download " + source); Bitmap bm; - InputStream is = null; - try { - Log.i("Download " + source); - is = new URL(source).openStream(); - + try (InputStream is = new URL(source).openStream()) { int scaleTo = context.getResources().getDisplayMetrics().widthPixels; int factor = 1; while (options.outWidth / factor > scaleTo) @@ -291,9 +283,6 @@ public class HtmlHelper { bm = BitmapFactory.decodeStream(is, null, options); } else bm = BitmapFactory.decodeStream(is); - } finally { - if (is != null) - is.close(); } if (bm == null) @@ -301,13 +290,8 @@ public class HtmlHelper { Log.i("Downloaded image"); - OutputStream os = null; - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { bm.compress(Bitmap.CompressFormat.PNG, 90, os); - } finally { - if (os != null) - os.close(); } // Create drawable from bitmap diff --git a/app/src/main/java/eu/faircode/email/MessageHelper.java b/app/src/main/java/eu/faircode/email/MessageHelper.java index 69494c402d..a4ce0ebfc9 100644 --- a/app/src/main/java/eu/faircode/email/MessageHelper.java +++ b/app/src/main/java/eu/faircode/email/MessageHelper.java @@ -235,17 +235,12 @@ public class MessageHelper { if (attachment.available && EntityAttachment.PGP_SIGNATURE.equals(attachment.encryption)) { InternetAddress from = (InternetAddress) message.from[0]; File file = EntityAttachment.getFile(context, attachment.id); - BufferedReader br = null; StringBuilder sb = new StringBuilder(); - try { - br = new BufferedReader(new FileReader(file)); + try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) if (!line.startsWith("-----") && !line.endsWith("-----")) sb.append(line); - } finally { - if (br != null) - br.close(); } imessage.addHeader("Autocrypt", "addr=" + from.getAddress() + "; keydata=" + sb.toString()); @@ -708,23 +703,21 @@ public class MessageHelper { File file = EntityAttachment.getFile(context, id); // Download attachment - OutputStream os = null; - try { - db.attachment().setProgress(id, null); - - InputStream is = apart.part.getInputStream(); - os = new BufferedOutputStream(new FileOutputStream(file)); - + db.attachment().setProgress(id, null); + try (InputStream is = apart.part.getInputStream()) { long size = 0; long total = apart.part.getSize(); - byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE]; - for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { - size += len; - os.write(buffer, 0, len); - // Update progress - if (total > 0) - db.attachment().setProgress(id, (int) (size * 100 / total)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { + byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE]; + for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { + size += len; + os.write(buffer, 0, len); + + // Update progress + if (total > 0) + db.attachment().setProgress(id, (int) (size * 100 / total)); + } } // Store attachment data @@ -737,9 +730,6 @@ public class MessageHelper { // Reset progress on failure db.attachment().setError(id, Helper.formatThrowable(ex)); return false; - } finally { - if (os != null) - os.close(); } } diff --git a/app/src/main/java/eu/faircode/email/ServiceSynchronize.java b/app/src/main/java/eu/faircode/email/ServiceSynchronize.java index 50d04e6373..33a83ebb2f 100644 --- a/app/src/main/java/eu/faircode/email/ServiceSynchronize.java +++ b/app/src/main/java/eu/faircode/email/ServiceSynchronize.java @@ -1754,14 +1754,9 @@ public class ServiceSynchronize extends LifecycleService { if (!file.exists()) throw new IllegalArgumentException("raw message file not found"); - InputStream is = null; - try { - Log.i(folder.name + " reading " + file); - is = new BufferedInputStream(new FileInputStream(file)); + Log.i(folder.name + " reading " + file); + try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { imessage = new MimeMessage(isession, is); - } finally { - if (is != null) - is.close(); } } @@ -1986,8 +1981,7 @@ public class ServiceSynchronize extends LifecycleService { // Create transport // TODO: cache transport? - Transport itransport = isession.getTransport(ident.getProtocol()); - try { + try (Transport itransport = isession.getTransport(ident.getProtocol())) { // Connect transport db.identity().setIdentityState(ident.id, "connecting"); try { @@ -2114,11 +2108,7 @@ public class ServiceSynchronize extends LifecycleService { throw ex; } finally { - try { - itransport.close(); - } finally { - db.identity().setIdentityState(ident.id, null); - } + db.identity().setIdentityState(ident.id, null); } } @@ -2142,14 +2132,9 @@ public class ServiceSynchronize extends LifecycleService { File file = EntityMessage.getRawFile(this, message.id); - OutputStream os = null; - try { - os = new BufferedOutputStream(new FileOutputStream(file)); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { imessage.writeTo(os); db.message().setMessageRaw(message.id, true); - } finally { - if (os != null) - os.close(); } }