From e738cddd80f0ec5b8417396bcc030a4c69ff82d9 Mon Sep 17 00:00:00 2001 From: M66B Date: Wed, 10 Feb 2016 12:50:51 +0100 Subject: [PATCH] Make database helper single instance Refs #243 --- .../netguard/ActivityForwardApproval.java | 7 +--- .../faircode/netguard/ActivityForwarding.java | 17 ++++---- .../eu/faircode/netguard/ActivityLog.java | 19 ++++----- .../eu/faircode/netguard/ActivityMain.java | 10 ++--- .../faircode/netguard/ActivitySettings.java | 41 ++++++++----------- .../eu/faircode/netguard/DatabaseHelper.java | 15 ++++++- .../eu/faircode/netguard/RuleAdapter.java | 17 ++++---- .../eu/faircode/netguard/SinkholeService.java | 24 ++++------- 8 files changed, 66 insertions(+), 84 deletions(-) diff --git a/app/src/main/java/eu/faircode/netguard/ActivityForwardApproval.java b/app/src/main/java/eu/faircode/netguard/ActivityForwardApproval.java index bb898bc0..1f978ad1 100644 --- a/app/src/main/java/eu/faircode/netguard/ActivityForwardApproval.java +++ b/app/src/main/java/eu/faircode/netguard/ActivityForwardApproval.java @@ -83,10 +83,9 @@ am start -a eu.faircode.netguard.START_PORT_FORWARD \ --user 0 */ Log.i(TAG, "Start forwarding protocol " + protocol + " port " + dport + " to " + raddr + "/" + rport + " uid " + ruid); - DatabaseHelper dh = new DatabaseHelper(ActivityForwardApproval.this); + DatabaseHelper dh = DatabaseHelper.getInstance(ActivityForwardApproval.this); dh.deleteForward(protocol, dport); dh.addForward(protocol, dport, raddr, rport, ruid); - dh.close(); } else if (ACTION_STOP_PORT_FORWARD.equals(getIntent().getAction())) { /* @@ -97,9 +96,7 @@ am start -a eu.faircode.netguard.STOP_PORT_FORWARD \ --user 0 */ Log.i(TAG, "Stop forwarding protocol " + protocol + " port " + dport); - new DatabaseHelper(ActivityForwardApproval.this) - .deleteForward(protocol, dport) - .close(); + DatabaseHelper.getInstance(ActivityForwardApproval.this).deleteForward(protocol, dport); } SinkholeService.reload(null, "forwarding", ActivityForwardApproval.this); diff --git a/app/src/main/java/eu/faircode/netguard/ActivityForwarding.java b/app/src/main/java/eu/faircode/netguard/ActivityForwarding.java index c4566641..09f3528c 100644 --- a/app/src/main/java/eu/faircode/netguard/ActivityForwarding.java +++ b/app/src/main/java/eu/faircode/netguard/ActivityForwarding.java @@ -41,7 +41,6 @@ import java.net.InetAddress; public class ActivityForwarding extends AppCompatActivity { private boolean running; - private DatabaseHelper dh; private ListView lvForwarding; private ForwardingAdapter adapter; private AlertDialog dialog = null; @@ -57,10 +56,8 @@ public class ActivityForwarding extends AppCompatActivity { getSupportActionBar().setDisplayHomeAsUpEnabled(true); - dh = new DatabaseHelper(this); - lvForwarding = (ListView) findViewById(R.id.lvForwarding); - adapter = new ForwardingAdapter(this, dh.getForwarding()); + adapter = new ForwardingAdapter(this, DatabaseHelper.getInstance(this).getForwarding()); lvForwarding.setAdapter(adapter); lvForwarding.setOnItemClickListener(new AdapterView.OnItemClickListener() { @@ -82,9 +79,10 @@ public class ActivityForwarding extends AppCompatActivity { @Override public boolean onMenuItemClick(MenuItem menuItem) { if (menuItem.getItemId() == R.id.menu_delete) { - dh.deleteForward(protocol, dport); + DatabaseHelper.getInstance(ActivityForwarding.this).deleteForward(protocol, dport); SinkholeService.reload(null, "forwarding", ActivityForwarding.this); - adapter = new ForwardingAdapter(ActivityForwarding.this, dh.getForwarding()); + adapter = new ForwardingAdapter(ActivityForwarding.this, + DatabaseHelper.getInstance(ActivityForwarding.this).getForwarding()); lvForwarding.setAdapter(adapter); } return false; @@ -98,7 +96,6 @@ public class ActivityForwarding extends AppCompatActivity { @Override protected void onDestroy() { - dh.close(); running = false; if (dialog != null) { dialog.dismiss(); @@ -145,7 +142,8 @@ public class ActivityForwarding extends AppCompatActivity { protected Throwable doInBackground(Object... objects) { try { InetAddress.getByName(raddr); - dh.addForward(protocol, dport, raddr, rport, ruid); + DatabaseHelper.getInstance(ActivityForwarding.this) + .addForward(protocol, dport, raddr, rport, ruid); return null; } catch (Throwable ex) { return ex; @@ -157,7 +155,8 @@ public class ActivityForwarding extends AppCompatActivity { if (running) if (ex == null) { SinkholeService.reload(null, "forwarding", ActivityForwarding.this); - adapter = new ForwardingAdapter(ActivityForwarding.this, dh.getForwarding()); + adapter = new ForwardingAdapter(ActivityForwarding.this, + DatabaseHelper.getInstance(ActivityForwarding.this).getForwarding()); lvForwarding.setAdapter(adapter); } else Toast.makeText(ActivityForwarding.this, ex.toString(), Toast.LENGTH_LONG).show(); diff --git a/app/src/main/java/eu/faircode/netguard/ActivityLog.java b/app/src/main/java/eu/faircode/netguard/ActivityLog.java index 2c9c917e..36942f69 100644 --- a/app/src/main/java/eu/faircode/netguard/ActivityLog.java +++ b/app/src/main/java/eu/faircode/netguard/ActivityLog.java @@ -64,7 +64,6 @@ public class ActivityLog extends AppCompatActivity implements SharedPreferences. private LogAdapter adapter; private MenuItem menuSearch = null; - private DatabaseHelper dh; private boolean live; private boolean resolve; private InetAddress vpn4 = null; @@ -129,11 +128,10 @@ public class ActivityLog extends AppCompatActivity implements SharedPreferences. boolean allowed = prefs.getBoolean("traffic_allowed", true); boolean blocked = prefs.getBoolean("traffic_blocked", true); - dh = new DatabaseHelper(this); - adapter = new LogAdapter(this, dh.getLog(udp, tcp, other, allowed, blocked), resolve); + adapter = new LogAdapter(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked), resolve); adapter.setFilterQueryProvider(new FilterQueryProvider() { public Cursor runQuery(CharSequence constraint) { - return dh.searchLog(constraint.toString()); + return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString()); } }); @@ -220,7 +218,7 @@ public class ActivityLog extends AppCompatActivity implements SharedPreferences. protected void onResume() { super.onResume(); if (live) { - dh.addLogChangedListener(listener); + DatabaseHelper.getInstance(this).addLogChangedListener(listener); updateAdapter(); } } @@ -229,13 +227,12 @@ public class ActivityLog extends AppCompatActivity implements SharedPreferences. protected void onPause() { super.onPause(); if (live) - dh.removeLogChangedListener(listener); + DatabaseHelper.getInstance(this).removeLogChangedListener(listener); } @Override protected void onDestroy() { running = false; - dh.close(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); super.onDestroy(); } @@ -364,10 +361,10 @@ public class ActivityLog extends AppCompatActivity implements SharedPreferences. item.setChecked(!item.isChecked()); live = item.isChecked(); if (live) { - dh.addLogChangedListener(listener); + DatabaseHelper.getInstance(this).addLogChangedListener(listener); updateAdapter(); } else - dh.removeLogChangedListener(listener); + DatabaseHelper.getInstance(this).removeLogChangedListener(listener); return true; case R.id.menu_refresh: @@ -395,7 +392,7 @@ public class ActivityLog extends AppCompatActivity implements SharedPreferences. new AsyncTask() { @Override protected Object doInBackground(Object... objects) { - dh.clearLog(); + DatabaseHelper.getInstance(ActivityLog.this).clearLog(); if (prefs.getBoolean("pcap", false)) { SinkholeService.setPcap(null); if (pcap_file.exists() && !pcap_file.delete()) @@ -436,7 +433,7 @@ public class ActivityLog extends AppCompatActivity implements SharedPreferences. boolean other = prefs.getBoolean("proto_other", true); boolean allowed = prefs.getBoolean("traffic_allowed", true); boolean blocked = prefs.getBoolean("traffic_blocked", true); - adapter.changeCursor(dh.getLog(udp, tcp, other, allowed, blocked)); + adapter.changeCursor(DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked)); if (menuSearch != null && menuSearch.isActionViewExpanded()) { SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuSearch); adapter.getFilter().filter(searchView.getQuery().toString()); diff --git a/app/src/main/java/eu/faircode/netguard/ActivityMain.java b/app/src/main/java/eu/faircode/netguard/ActivityMain.java index 4ff7acb5..cfc91f6a 100644 --- a/app/src/main/java/eu/faircode/netguard/ActivityMain.java +++ b/app/src/main/java/eu/faircode/netguard/ActivityMain.java @@ -63,7 +63,6 @@ public class ActivityMain extends AppCompatActivity implements SharedPreferences private boolean running = false; private SwipeRefreshLayout swipeRefresh; - private DatabaseHelper dh; private RuleAdapter adapter = null; private MenuItem menuSearch = null; private AlertDialog dialogFirst = null; @@ -183,8 +182,7 @@ public class ActivityMain extends AppCompatActivity implements SharedPreferences RecyclerView rvApplication = (RecyclerView) findViewById(R.id.rvApplication); rvApplication.setHasFixedSize(true); rvApplication.setLayoutManager(new LinearLayoutManager(this)); - dh = new DatabaseHelper(this); - adapter = new RuleAdapter(dh, this); + adapter = new RuleAdapter(this); rvApplication.setAdapter(adapter); // Swipe to refresh @@ -298,7 +296,7 @@ public class ActivityMain extends AppCompatActivity implements SharedPreferences @Override protected void onResume() { - dh.addAccessChangedListener(accessChangedListener); + DatabaseHelper.getInstance(this).addAccessChangedListener(accessChangedListener); if (adapter != null) adapter.notifyDataSetChanged(); super.onResume(); @@ -307,7 +305,7 @@ public class ActivityMain extends AppCompatActivity implements SharedPreferences @Override protected void onPause() { super.onPause(); - dh.removeAccessChangedListener(accessChangedListener); + DatabaseHelper.getInstance(this).removeAccessChangedListener(accessChangedListener); } @Override @@ -321,8 +319,6 @@ public class ActivityMain extends AppCompatActivity implements SharedPreferences running = false; - dh.close(); - PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); LocalBroadcastManager.getInstance(this).unregisterReceiver(onRulesetChanged); diff --git a/app/src/main/java/eu/faircode/netguard/ActivitySettings.java b/app/src/main/java/eu/faircode/netguard/ActivitySettings.java index 1294b972..7ac2fcea 100644 --- a/app/src/main/java/eu/faircode/netguard/ActivitySettings.java +++ b/app/src/main/java/eu/faircode/netguard/ActivitySettings.java @@ -982,8 +982,7 @@ public class ActivitySettings extends AppCompatActivity implements SharedPrefere private void filterExport(XmlSerializer serializer) throws IOException { PackageManager pm = getPackageManager(); - DatabaseHelper dh = new DatabaseHelper(this); - Cursor cursor = dh.getAccess(); + Cursor cursor = DatabaseHelper.getInstance(this).getAccess(); int colUid = cursor.getColumnIndex("uid"); int colVersion = cursor.getColumnIndex("version"); int colProtocol = cursor.getColumnIndex("protocol"); @@ -1011,7 +1010,6 @@ public class ActivitySettings extends AppCompatActivity implements SharedPrefere } } cursor.close(); - dh.close(); } private void xmlImport(InputStream in) throws IOException, SAXException, ParserConfigurationException { @@ -1020,24 +1018,19 @@ public class ActivitySettings extends AppCompatActivity implements SharedPrefere prefs.edit().putBoolean("enabled", false).apply(); SinkholeService.stop("import", this); - DatabaseHelper dh = new DatabaseHelper(this); - dh.clearAccess(); - try { - XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); - XmlImportHandler handler = new XmlImportHandler(this, dh); - reader.setContentHandler(handler); - reader.parse(new InputSource(in)); + DatabaseHelper.getInstance(this).clearAccess(); + XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + XmlImportHandler handler = new XmlImportHandler(this); + reader.setContentHandler(handler); + reader.parse(new InputSource(in)); - xmlImport(handler.application, prefs); - xmlImport(handler.wifi, getSharedPreferences("wifi", Context.MODE_PRIVATE)); - xmlImport(handler.mobile, getSharedPreferences("other", Context.MODE_PRIVATE)); - xmlImport(handler.unused, getSharedPreferences("unused", Context.MODE_PRIVATE)); - xmlImport(handler.screen_wifi, getSharedPreferences("screen_wifi", Context.MODE_PRIVATE)); - xmlImport(handler.screen_other, getSharedPreferences("screen_other", Context.MODE_PRIVATE)); - xmlImport(handler.roaming, getSharedPreferences("roaming", Context.MODE_PRIVATE)); - } finally { - dh.close(); - } + xmlImport(handler.application, prefs); + xmlImport(handler.wifi, getSharedPreferences("wifi", Context.MODE_PRIVATE)); + xmlImport(handler.mobile, getSharedPreferences("other", Context.MODE_PRIVATE)); + xmlImport(handler.unused, getSharedPreferences("unused", Context.MODE_PRIVATE)); + xmlImport(handler.screen_wifi, getSharedPreferences("screen_wifi", Context.MODE_PRIVATE)); + xmlImport(handler.screen_other, getSharedPreferences("screen_other", Context.MODE_PRIVATE)); + xmlImport(handler.roaming, getSharedPreferences("roaming", Context.MODE_PRIVATE)); // Upgrade imported settings Receiver.upgrade(true, this); @@ -1075,7 +1068,6 @@ public class ActivitySettings extends AppCompatActivity implements SharedPrefere private class XmlImportHandler extends DefaultHandler { private Context context; - private DatabaseHelper dh; public boolean enabled = false; public Map application = new HashMap<>(); public Map wifi = new HashMap<>(); @@ -1087,9 +1079,8 @@ public class ActivitySettings extends AppCompatActivity implements SharedPrefere private Map current = null; private List listUid = new ArrayList<>(); - public XmlImportHandler(Context context, DatabaseHelper dh) { + public XmlImportHandler(Context context) { this.context = context; - this.dh = dh; } @Override @@ -1186,11 +1177,11 @@ public class ActivitySettings extends AppCompatActivity implements SharedPrefere if (!listUid.contains(packet.uid)) { Log.i(TAG, "Clear filters uid=" + packet.uid); listUid.add(packet.uid); - dh.clearAccess(packet.uid); + DatabaseHelper.getInstance(context).clearAccess(packet.uid); } Log.i(TAG, " Update access " + packet + " block=" + block); - dh.updateAccess(packet, null, block); + DatabaseHelper.getInstance(context).updateAccess(packet, null, block); } catch (PackageManager.NameNotFoundException ex) { Log.w(TAG, "Package not found pkg=" + pkg); } diff --git a/app/src/main/java/eu/faircode/netguard/DatabaseHelper.java b/app/src/main/java/eu/faircode/netguard/DatabaseHelper.java index 3bee15b3..3d120011 100644 --- a/app/src/main/java/eu/faircode/netguard/DatabaseHelper.java +++ b/app/src/main/java/eu/faircode/netguard/DatabaseHelper.java @@ -64,7 +64,20 @@ public class DatabaseHelper extends SQLiteOpenHelper { }; } - public DatabaseHelper(Context context) { + private static DatabaseHelper dh = null; + + public static DatabaseHelper getInstance(Context context) { + if (dh == null) + dh = new DatabaseHelper(context.getApplicationContext()); + return dh; + } + + @Override + public void close() { + Log.w(TAG, "Database is being closed"); + } + + private DatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); this.context = context; diff --git a/app/src/main/java/eu/faircode/netguard/RuleAdapter.java b/app/src/main/java/eu/faircode/netguard/RuleAdapter.java index 5c2195a5..56f4823f 100644 --- a/app/src/main/java/eu/faircode/netguard/RuleAdapter.java +++ b/app/src/main/java/eu/faircode/netguard/RuleAdapter.java @@ -68,7 +68,6 @@ public class RuleAdapter extends RecyclerView.Adapter im private static final String TAG = "NetGuard.Adapter"; private Activity context; - private DatabaseHelper dh; private RecyclerView rv; private boolean filter; private boolean debuggable; @@ -193,11 +192,10 @@ public class RuleAdapter extends RecyclerView.Adapter im } } - public RuleAdapter(DatabaseHelper dh, Activity context) { + public RuleAdapter(Activity context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); this.context = context; - this.dh = dh; this.filter = prefs.getBoolean("filter", false); this.debuggable = Util.isDebuggable(context); @@ -335,7 +333,7 @@ public class RuleAdapter extends RecyclerView.Adapter im @Override protected Long doInBackground(Object... objects) { - return dh.getRuleCount(rule.info.applicationInfo.uid); + return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid); } @Override @@ -543,7 +541,8 @@ public class RuleAdapter extends RecyclerView.Adapter im // Show access rules if (rule.expanded) { // Access the database when expanded only - final AccessAdapter badapter = new AccessAdapter(context, dh.getAccess(rule.info.applicationInfo.uid)); + final AccessAdapter badapter = new AccessAdapter(context, + DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid)); if (filter) holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override @@ -571,15 +570,15 @@ public class RuleAdapter extends RecyclerView.Adapter im public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_allow: - dh.setAccess(id, 0); + DatabaseHelper.getInstance(context).setAccess(id, 0); SinkholeService.reload(null, "allow host", context); return true; case R.id.menu_block: - dh.setAccess(id, 1); + DatabaseHelper.getInstance(context).setAccess(id, 1); SinkholeService.reload(null, "block host", context); return true; case R.id.menu_reset: - dh.setAccess(id, -1); + DatabaseHelper.getInstance(context).setAccess(id, -1); SinkholeService.reload(null, "reset host", context); return true; } @@ -637,7 +636,7 @@ public class RuleAdapter extends RecyclerView.Adapter im Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() { @Override public void onSure() { - dh.clearAccess(rule.info.applicationInfo.uid); + DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid); if (rv != null) rv.scrollToPosition(position); } diff --git a/app/src/main/java/eu/faircode/netguard/SinkholeService.java b/app/src/main/java/eu/faircode/netguard/SinkholeService.java index 680afe88..14c65819 100644 --- a/app/src/main/java/eu/faircode/netguard/SinkholeService.java +++ b/app/src/main/java/eu/faircode/netguard/SinkholeService.java @@ -678,7 +678,7 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS boolean notify = prefs.getBoolean("notify_access", false); boolean system = prefs.getBoolean("manage_system", false); - DatabaseHelper dh = new DatabaseHelper(SinkholeService.this); + DatabaseHelper dh = DatabaseHelper.getInstance(SinkholeService.this); // Get real name String dname = dh.getQName(packet.daddr); @@ -699,14 +699,12 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS if (packet.uid < 0 && packet.dport != 53) Log.w(TAG, "Unknown application packet=" + packet); - - dh.close(); } private void resolved(ResourceRecord rr) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SinkholeService.this); if (prefs.getBoolean("resolved", true)) - new DatabaseHelper(SinkholeService.this).insertDns(rr).close(); + DatabaseHelper.getInstance(SinkholeService.this).insertDns(rr); } private void set(Intent intent) { @@ -927,7 +925,7 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS private void prepareUidIPFilters() { Map> map = new HashMap<>(); - DatabaseHelper dh = new DatabaseHelper(SinkholeService.this); + DatabaseHelper dh = DatabaseHelper.getInstance(SinkholeService.this); Cursor cursor = dh.getDns(); int colUid = cursor.getColumnIndex("uid"); @@ -967,15 +965,13 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS } cursor.close(); - dh.close(); - synchronized (mapUidIPFilters) { mapUidIPFilters = map; } } private void updateUidIPFilters() { - DatabaseHelper dh = new DatabaseHelper(SinkholeService.this); + DatabaseHelper dh = DatabaseHelper.getInstance(SinkholeService.this); Cursor cursor = dh.getAccess(); int colDAddr = cursor.getColumnIndex("daddr"); while (cursor.moveToNext()) { @@ -988,13 +984,12 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS } } cursor.close(); - dh.close(); } private void prepareForwarding() { mapForward.clear(); - DatabaseHelper dh = new DatabaseHelper(SinkholeService.this); + DatabaseHelper dh = DatabaseHelper.getInstance(SinkholeService.this); Cursor cursor = dh.getForwarding(); int colProtocol = cursor.getColumnIndex("protocol"); @@ -1013,15 +1008,11 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS Log.i(TAG, "Forward " + fwd); } cursor.close(); - - dh.close(); } private void cleanupDNS() { // Keep records for a week - new DatabaseHelper(SinkholeService.this) - .cleanupDns(new Date().getTime() - 7 * 24 * 3600 * 1000L) - .close(); + DatabaseHelper.getInstance(SinkholeService.this).cleanupDns(new Date().getTime() - 7 * 24 * 3600 * 1000L); } private List getAllowedRules(List listRule) { @@ -1684,7 +1675,7 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS sp.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); notification.addLine(sp); - DatabaseHelper dh = new DatabaseHelper(SinkholeService.this); + DatabaseHelper dh = DatabaseHelper.getInstance(SinkholeService.this); Cursor cursor = dh.getAccessUnset(uid); int colDAddr = cursor.getColumnIndex("daddr"); int colTime = cursor.getColumnIndex("time"); @@ -1712,7 +1703,6 @@ public class SinkholeService extends VpnService implements SharedPreferences.OnS notification.addLine(sp); } cursor.close(); - dh.close(); NotificationManagerCompat.from(this).notify(uid + 10000, notification.build()); }