From 72dcc50ea1d7462f17cba4a85e2ed75e73103ef1 Mon Sep 17 00:00:00 2001
From: Unpublished
Date: Fri, 22 Feb 2019 16:57:52 +0100
Subject: [PATCH 1/3] replace "ISO-8859-1" with StandardCharsets
---
.../main/java/eu/faircode/email/MessageHelper.java | 12 +++++-------
1 file changed, 5 insertions(+), 7 deletions(-)
diff --git a/app/src/main/java/eu/faircode/email/MessageHelper.java b/app/src/main/java/eu/faircode/email/MessageHelper.java
index 704cf1a881..69494c402d 100644
--- a/app/src/main/java/eu/faircode/email/MessageHelper.java
+++ b/app/src/main/java/eu/faircode/email/MessageHelper.java
@@ -34,6 +34,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
@@ -624,13 +625,10 @@ public class MessageHelper {
if (TextUtils.isEmpty(charset)) {
if (BuildConfig.DEBUG)
warnings.add(context.getString(R.string.title_no_charset, ct.toString()));
- if (part.isMimeType("text/plain"))
- try {
- // The first 127 characters are the same as in US-ASCII
- result = new String(result.getBytes("ISO-8859-1"));
- } catch (UnsupportedEncodingException ex) {
- warnings.add(Helper.formatThrowable(ex));
- }
+ if (part.isMimeType("text/plain")) {
+ // The first 127 characters are the same as in US-ASCII
+ result = new String(result.getBytes(StandardCharsets.ISO_8859_1));
+ }
} else {
if ("US-ASCII".equals(Charset.forName(charset).name()) &&
!"US-ASCII".equals(charset.toUpperCase()))
From 0edc7a862955d28f3c385425d6c2576a2e7a0dcb Mon Sep 17 00:00:00 2001
From: Unpublished
Date: Fri, 22 Feb 2019 16:59:23 +0100
Subject: [PATCH 2/3] 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 | 38 ++++------
.../eu/faircode/email/ServiceSynchronize.java | 25 ++-----
16 files changed, 118 insertions(+), 317 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();
}
}
From 7f66558566d1764f974887e39cf2fadf5df35254 Mon Sep 17 00:00:00 2001
From: Unpublished
Date: Fri, 22 Feb 2019 17:04:53 +0100
Subject: [PATCH 3/3] use NotificationCompat to get rid of some version checks
---
.../eu/faircode/email/ServiceExternal.java | 12 +--
.../eu/faircode/email/ServiceSynchronize.java | 76 ++++++-------------
2 files changed, 29 insertions(+), 59 deletions(-)
diff --git a/app/src/main/java/eu/faircode/email/ServiceExternal.java b/app/src/main/java/eu/faircode/email/ServiceExternal.java
index cdb082804b..4be5b9a499 100644
--- a/app/src/main/java/eu/faircode/email/ServiceExternal.java
+++ b/app/src/main/java/eu/faircode/email/ServiceExternal.java
@@ -4,11 +4,11 @@ import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
-import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
+import androidx.core.app.NotificationCompat;
public class ServiceExternal extends Service {
private final static String ACTION_ENABLE = "eu.faircode.email.ENABLE";
@@ -61,12 +61,8 @@ public class ServiceExternal extends Service {
return null;
}
- private Notification.Builder getNotification() {
- Notification.Builder builder;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
- builder = new Notification.Builder(this, "service");
- else
- builder = new Notification.Builder(this);
+ private NotificationCompat.Builder getNotification() {
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "service");
builder
.setSmallIcon(R.drawable.baseline_compare_arrows_white_24)
@@ -75,7 +71,7 @@ public class ServiceExternal extends Service {
.setShowWhen(false)
.setPriority(Notification.PRIORITY_MIN)
.setCategory(Notification.CATEGORY_STATUS)
- .setVisibility(Notification.VISIBILITY_SECRET);
+ .setVisibility(NotificationCompat.VISIBILITY_SECRET);
return builder;
}
diff --git a/app/src/main/java/eu/faircode/email/ServiceSynchronize.java b/app/src/main/java/eu/faircode/email/ServiceSynchronize.java
index 33a83ebb2f..03cb3df1fb 100644
--- a/app/src/main/java/eu/faircode/email/ServiceSynchronize.java
+++ b/app/src/main/java/eu/faircode/email/ServiceSynchronize.java
@@ -23,7 +23,6 @@ import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
-import android.app.Person;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -132,6 +131,7 @@ import javax.net.ssl.SSLException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleService;
import androidx.lifecycle.LiveData;
@@ -449,7 +449,7 @@ public class ServiceSynchronize extends LifecycleService {
return START_STICKY;
}
- private Notification.Builder getNotificationService(TupleAccountStats stats) {
+ private NotificationCompat.Builder getNotificationService(TupleAccountStats stats) {
if (stats == null)
stats = lastStats;
if (stats == null)
@@ -461,11 +461,7 @@ public class ServiceSynchronize extends LifecycleService {
PendingIntent pi = PendingIntent.getService(this, PI_WHY, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Build notification
- Notification.Builder builder;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
- builder = new Notification.Builder(this, "service");
- else
- builder = new Notification.Builder(this);
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "service");
builder
.setSmallIcon(R.drawable.baseline_compare_arrows_white_24)
@@ -476,10 +472,10 @@ public class ServiceSynchronize extends LifecycleService {
.setShowWhen(false)
.setPriority(Notification.PRIORITY_MIN)
.setCategory(Notification.CATEGORY_STATUS)
- .setVisibility(Notification.VISIBILITY_SECRET);
+ .setVisibility(NotificationCompat.VISIBILITY_SECRET);
if (stats.operations > 0)
- builder.setStyle(new Notification.BigTextStyle().setSummaryText(
+ builder.setStyle(new NotificationCompat.BigTextStyle().setSummaryText(
getResources().getQuantityString(
R.plurals.title_notification_operations, stats.operations, stats.operations)));
@@ -524,11 +520,7 @@ public class ServiceSynchronize extends LifecycleService {
String channelName = (account == 0 ? "notification" : EntityAccount.getNotificationChannelName(account));
// Build public notification
- Notification.Builder pbuilder;
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
- pbuilder = new Notification.Builder(this);
- else
- pbuilder = new Notification.Builder(this, channelName);
+ NotificationCompat.Builder pbuilder = new NotificationCompat.Builder(this, channelName);
pbuilder
.setSmallIcon(R.drawable.baseline_email_white_24)
@@ -539,17 +531,13 @@ public class ServiceSynchronize extends LifecycleService {
.setDeleteIntent(piClear)
.setPriority(Notification.PRIORITY_DEFAULT)
.setCategory(Notification.CATEGORY_STATUS)
- .setVisibility(Notification.VISIBILITY_PUBLIC);
+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
if (!TextUtils.isEmpty(accountName))
pbuilder.setSubText(accountName);
// Build notification
- Notification.Builder builder;
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
- builder = new Notification.Builder(this);
- else
- builder = new Notification.Builder(this, channelName);
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelName);
builder
.setSmallIcon(R.drawable.baseline_email_white_24)
@@ -583,7 +571,7 @@ public class ServiceSynchronize extends LifecycleService {
builder.setOnlyAlertOnce(true);
} else
- builder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN);
+ builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
if (pro) {
DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
@@ -596,7 +584,7 @@ public class ServiceSynchronize extends LifecycleService {
sb.append("
");
}
- builder.setStyle(new Notification.BigTextStyle()
+ builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText(HtmlHelper.fromHtml(sb.toString()))
.setSummaryText(title));
}
@@ -635,26 +623,23 @@ public class ServiceSynchronize extends LifecycleService {
PendingIntent piTrash = PendingIntent.getService(this, PI_TRASH, trash, PendingIntent.FLAG_UPDATE_CURRENT);
- Notification.Action.Builder actionSeen = new Notification.Action.Builder(
+ NotificationCompat.Action.Builder actionSeen = new NotificationCompat.Action.Builder(
R.drawable.baseline_visibility_24,
getString(R.string.title_action_seen),
piSeen);
- Notification.Action.Builder actionArchive = new Notification.Action.Builder(
+ NotificationCompat.Action.Builder actionArchive = new NotificationCompat.Action.Builder(
R.drawable.baseline_archive_24,
getString(R.string.title_action_archive),
piArchive);
- Notification.Action.Builder actionTrash = new Notification.Action.Builder(
+ NotificationCompat.Action.Builder actionTrash = new NotificationCompat.Action.Builder(
R.drawable.baseline_delete_24,
getString(R.string.title_action_trash),
piTrash);
- Notification.Builder mbuilder;
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
- mbuilder = new Notification.Builder(this);
- else
- mbuilder = new Notification.Builder(this, channelName);
+ NotificationCompat.Builder mbuilder;
+ mbuilder = new NotificationCompat.Builder(this, channelName);
String folderName = message.folderDisplay == null
? Helper.localizeFolderName(this, message.folderName)
@@ -701,32 +686,25 @@ public class ServiceSynchronize extends LifecycleService {
sb.append(text);
sb.append("");
}
- mbuilder.setStyle(new Notification.BigTextStyle().bigText(HtmlHelper.fromHtml(sb.toString())));
+ mbuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(HtmlHelper.fromHtml(sb.toString())));
} catch (IOException ex) {
Log.e(ex);
- mbuilder.setStyle(new Notification.BigTextStyle().bigText(ex.toString()));
+ mbuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(ex.toString()));
}
if (info.hasPhoto())
mbuilder.setLargeIcon(info.getPhotoBitmap());
if (info.hasLookupUri())
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
- mbuilder.addPerson(new Person.Builder()
- .setUri(info.getLookupUri().toString())
- .build());
- else
- mbuilder.addPerson(info.getLookupUri().toString());
+ mbuilder.addPerson(info.getLookupUri().toString());
if (message.accountColor != null) {
mbuilder.setColor(message.accountColor);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
- mbuilder.setColorized(true);
+ mbuilder.setColorized(true);
}
}
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
- mbuilder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN);
+ mbuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
notifications.add(mbuilder.build());
}
@@ -734,11 +712,11 @@ public class ServiceSynchronize extends LifecycleService {
return notifications;
}
- private Notification.Builder getNotificationError(String title, Throwable ex) {
+ private NotificationCompat.Builder getNotificationError(String title, Throwable ex) {
return getNotificationError("error", title, ex, true);
}
- private Notification.Builder getNotificationError(String channel, String title, Throwable ex, boolean debug) {
+ private NotificationCompat.Builder getNotificationError(String channel, String title, Throwable ex, boolean debug) {
// Build pending intent
Intent intent = new Intent(this, ActivitySetup.class);
if (debug)
@@ -748,11 +726,7 @@ public class ServiceSynchronize extends LifecycleService {
this, ActivitySetup.REQUEST_ERROR, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Build notification
- Notification.Builder builder;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
- builder = new Notification.Builder(this, channel);
- else
- builder = new Notification.Builder(this);
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channel);
builder
.setSmallIcon(R.drawable.baseline_warning_white_24)
@@ -764,9 +738,9 @@ public class ServiceSynchronize extends LifecycleService {
.setPriority(Notification.PRIORITY_MAX)
.setOnlyAlertOnce(true)
.setCategory(Notification.CATEGORY_ERROR)
- .setVisibility(Notification.VISIBILITY_SECRET);
+ .setVisibility(NotificationCompat.VISIBILITY_SECRET);
- builder.setStyle(new Notification.BigTextStyle()
+ builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText(Helper.formatThrowable(ex, false, "\n")));
return builder;