Merge pull request #149 from Unpublished/cleanup

use try-with-resources and NotificationCompat
This commit is contained in:
Marcel Bokhorst 2019-02-25 21:10:00 +01:00 committed by GitHub
commit 4106bdd7d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 151 additions and 382 deletions

View File

@ -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();
}
}

View File

@ -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");

View File

@ -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<ShortcutInfo> 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();
}
}

View File

@ -1122,16 +1122,14 @@ public class AdapterMessage extends RecyclerView.Adapter<AdapterMessage.ViewHold
if (!TextUtils.isEmpty(email))
edit.putExtra(ContactsContract.Intents.Insert.EMAIL, email);
Cursor cursor = null;
try {
ContentResolver resolver = context.getContentResolver();
cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
ContactsContract.Contacts.LOOKUP_KEY
},
ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
new String[]{email}, null);
ContentResolver resolver = context.getContentResolver();
try (Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
ContactsContract.Contacts.LOOKUP_KEY
},
ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
new String[]{email}, null)) {
if (cursor != null && cursor.moveToNext()) {
int colContactId = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.CONTACT_ID);
int colLookupKey = cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
@ -1147,9 +1145,6 @@ public class AdapterMessage extends RecyclerView.Adapter<AdapterMessage.ViewHold
edit.setAction(Intent.ACTION_INSERT);
edit.setType(ContactsContract.Contacts.CONTENT_TYPE);
}
} finally {
if (cursor != null)
cursor.close();
}
PackageManager pm = context.getPackageManager();
@ -1375,11 +1370,8 @@ public class AdapterMessage extends RecyclerView.Adapter<AdapterMessage.ViewHold
String cid = '<' + src.substring(4) + '>';
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<AdapterMessage.ViewHold
sb.append(Base64.encodeToString(bytes, Base64.DEFAULT));
img.attr("src", sb.toString());
} finally {
if (is != null)
is.close();
}
}
}

View File

@ -129,21 +129,11 @@ public class ApplicationEx extends Application {
File file = new File(context.getCacheDir(), "crash.log");
Log.w("Writing exception to " + file);
FileWriter out = null;
try {
out = new FileWriter(file, true);
try (FileWriter out = new FileWriter(file, true)) {
out.write(BuildConfig.VERSION_NAME + " " + new Date() + "\r\n");
out.write(ex + "\r\n" + android.util.Log.getStackTraceString(ex) + "\r\n");
} catch (IOException e) {
Log.e(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
Log.e(e);
}
}
}
}
}

View File

@ -90,19 +90,17 @@ public class ContactInfo {
if (Helper.hasPermission(context, Manifest.permission.READ_CONTACTS))
try {
Cursor cursor = null;
try {
ContentResolver resolver = context.getContentResolver();
cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME
},
ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
new String[]{
address.getAddress()
}, null);
ContentResolver resolver = context.getContentResolver();
try (Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME
},
ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
new String[]{
address.getAddress()
}, null)) {
if (cursor != null && cursor.moveToNext()) {
int colContactId = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.CONTACT_ID);
@ -122,9 +120,6 @@ public class ContactInfo {
info.displayName = cursor.getString(colDisplayName);
info.lookupUri = lookupUri;
}
} finally {
if (cursor != null)
cursor.close();
}
} catch (Throwable ex) {
Log.e(ex);
@ -159,18 +154,16 @@ public class ContactInfo {
return null;
try {
Cursor cursor = null;
try {
ContentResolver resolver = context.getContentResolver();
cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
ContactsContract.Contacts.LOOKUP_KEY
},
ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
new String[]{
address.getAddress()
}, null);
ContentResolver resolver = context.getContentResolver();
try (Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
ContactsContract.Contacts.LOOKUP_KEY
},
ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
new String[]{
address.getAddress()
}, null)) {
if (cursor != null && cursor.moveToNext()) {
int colContactId = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.CONTACT_ID);
@ -181,9 +174,6 @@ public class ContactInfo {
return ContactsContract.Contacts.getLookupUri(contactId, lookupKey);
} else
return null;
} finally {
if (cursor != null)
cursor.close();
}
} catch (Throwable ex) {
Log.e(ex);

View File

@ -112,16 +112,11 @@ public abstract class DB extends RoomDatabase {
}
private static String exec(DB db, String command) {
Cursor cursor = null;
try {
cursor = db.query(command, new Object[0]);
try (Cursor cursor = db.query(command, new Object[0])) {
if (cursor != null && cursor.moveToNext())
return cursor.getString(0);
else
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
@ -358,9 +353,7 @@ public abstract class DB extends RoomDatabase {
public void migrate(SupportSQLiteDatabase db) {
Log.i("DB migration from version " + startVersion + " to " + endVersion);
Cursor cursor = null;
try {
cursor = db.query("SELECT `id`, `from` FROM message");
try (Cursor cursor = db.query("SELECT `id`, `from` FROM message")) {
while (cursor.moveToNext())
try {
long id = cursor.getLong(0);
@ -374,9 +367,6 @@ public abstract class DB extends RoomDatabase {
Log.e(ex);
}
} finally {
if (cursor != null)
cursor.close();
}
}
})

View File

@ -573,9 +573,7 @@ public class FragmentAccount extends FragmentBase {
Properties props = MessageHelper.getSessionProperties(auth_type, realm, insecure);
Session isession = Session.getInstance(props, null);
isession.setDebug(true);
Store istore = null;
try {
istore = isession.getStore("imap" + (starttls ? "" : "s"));
try (Store istore = isession.getStore("imap" + (starttls ? "" : "s"))) {
try {
istore.connect(host, Integer.parseInt(port), user, password);
} catch (AuthenticationFailedException ex) {
@ -680,9 +678,6 @@ public class FragmentAccount extends FragmentBase {
folder.display = folder.getDisplayName(getContext());
EntityFolder.sort(getContext(), result.folders);
} finally {
if (istore != null)
istore.close();
}
return result;
@ -880,9 +875,7 @@ public class FragmentAccount extends FragmentBase {
Session isession = Session.getInstance(props, null);
isession.setDebug(true);
Store istore = null;
try {
istore = isession.getStore("imap" + (starttls ? "" : "s"));
try (Store istore = isession.getStore("imap" + (starttls ? "" : "s"))) {
try {
istore.connect(host, Integer.parseInt(port), user, password);
} catch (AuthenticationFailedException ex) {
@ -914,9 +907,6 @@ public class FragmentAccount extends FragmentBase {
}
}
} finally {
if (istore != null)
istore.close();
}
}

View File

@ -550,14 +550,9 @@ public class FragmentCompose extends FragmentBase {
String plain = HtmlHelper.getText(ref);
String html = "<p>" + plain.replaceAll("\\r?\\n", "<br />" + "</p>");
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();
}

View File

@ -618,8 +618,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) {
@ -629,8 +628,6 @@ public class FragmentIdentity extends FragmentBase {
} else
throw ex;
}
} finally {
itransport.close();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -489,10 +489,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);
@ -502,9 +500,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();
}
}
@ -520,10 +515,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);
@ -538,9 +531,6 @@ public class Helper {
}
db.attachment().setDownloaded(attachment.id, size);
} finally {
if (os != null)
os.close();
}
}
@ -556,10 +546,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;
@ -569,9 +557,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();
}
}
@ -587,10 +572,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();
@ -604,9 +587,6 @@ public class Helper {
op.error));
db.attachment().setDownloaded(attachment.id, size);
} finally {
if (os != null)
os.close();
}
}
@ -623,11 +603,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",
@ -635,20 +612,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();
}
@ -683,20 +657,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) {
@ -704,26 +671,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();
}
}

View File

@ -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

View File

@ -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;
@ -234,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());
@ -624,13 +620,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()))
@ -710,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
@ -739,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();
}
}

View File

@ -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;
}

View File

@ -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;
@ -133,6 +132,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;
@ -450,7 +450,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)
@ -462,11 +462,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)
@ -477,10 +473,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)));
@ -525,11 +521,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)
@ -540,17 +532,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)
@ -584,7 +572,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);
@ -597,7 +585,7 @@ public class ServiceSynchronize extends LifecycleService {
sb.append("<br>");
}
builder.setStyle(new Notification.BigTextStyle()
builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText(HtmlHelper.fromHtml(sb.toString()))
.setSummaryText(title));
}
@ -636,26 +624,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)
@ -702,32 +687,25 @@ public class ServiceSynchronize extends LifecycleService {
sb.append(text);
sb.append("</em>");
}
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());
}
@ -735,11 +713,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)
@ -749,11 +727,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)
@ -765,9 +739,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;
@ -1755,14 +1729,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();
}
}
@ -1987,8 +1956,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 {
@ -2115,11 +2083,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);
}
}
@ -2143,14 +2107,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();
}
}