Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Delta Between Two Patch Sets: adblockplussbrowser/src/org/adblockplus/sbrowser/contentblocker/engine/Engine.java

Issue 29453722: Noissue - Lint adjustments and optimizations (Closed)
Left Patch Set: Adjustments based on review comments Created June 13, 2017, 9:23 p.m.
Right Patch Set: Adjusting HashSet initialization in Subscription Created July 19, 2017, 4:40 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
LEFTRIGHT
1 /* 1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>, 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-2016 Eyeo GmbH 3 * Copyright (C) 2006-2016 Eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
(...skipping 23 matching lines...) Expand all
34 import java.util.ArrayList; 34 import java.util.ArrayList;
35 import java.util.Collections; 35 import java.util.Collections;
36 import java.util.HashMap; 36 import java.util.HashMap;
37 import java.util.List; 37 import java.util.List;
38 import java.util.Map; 38 import java.util.Map;
39 import java.util.Set; 39 import java.util.Set;
40 import java.util.TreeSet; 40 import java.util.TreeSet;
41 import java.util.concurrent.LinkedBlockingQueue; 41 import java.util.concurrent.LinkedBlockingQueue;
42 import java.util.concurrent.TimeUnit; 42 import java.util.concurrent.TimeUnit;
43 import java.util.concurrent.locks.ReentrantLock; 43 import java.util.concurrent.locks.ReentrantLock;
44 import java.util.regex.Pattern;
45 44
46 import org.adblockplus.adblockplussbrowser.R; 45 import org.adblockplus.adblockplussbrowser.R;
47 import org.adblockplus.sbrowser.contentblocker.MainPreferences; 46 import org.adblockplus.sbrowser.contentblocker.util.SharedPrefsUtils;
48 47
49 import android.content.Context; 48 import android.content.Context;
50 import android.content.Intent; 49 import android.content.Intent;
51 import android.content.SharedPreferences;
52 import android.content.pm.PackageInfo; 50 import android.content.pm.PackageInfo;
53 import android.content.pm.PackageManager; 51 import android.content.pm.PackageManager;
54 import android.content.pm.ResolveInfo; 52 import android.content.pm.ResolveInfo;
55 import android.net.ConnectivityManager; 53 import android.net.ConnectivityManager;
56 import android.net.NetworkInfo; 54 import android.net.NetworkInfo;
57 import android.net.Uri; 55 import android.net.Uri;
58 import android.os.Handler; 56 import android.os.Handler;
59 import android.os.Looper; 57 import android.os.Looper;
60 import android.preference.PreferenceManager;
61 import android.text.TextUtils; 58 import android.text.TextUtils;
62 import android.text.format.DateUtils; 59 import android.text.format.DateUtils;
63 import android.util.Log; 60 import android.util.Log;
64 61
65 public final class Engine 62 public final class Engine
66 { 63 {
67 private static final String TAG = Engine.class.getSimpleName(); 64 private static final String TAG = Engine.class.getSimpleName();
68
69 // TODO make use of this regex's
70 public static final Pattern RE_SUBSCRIPTION_HEADER = Pattern.compile(
71 "\\[Adblock(?:\\s*Plus\\s*([\\d\\.]+)?)?\\]", Pattern.CASE_INSENSITIVE);
72 public static final Pattern RE_FILTER_META = Pattern.compile("^\\s*!\\s*(\\w+) \\s*:\\s*(.*)");
73 public static final Pattern RE_FILTER_ELEMHIDE = Pattern
74 .compile("^([^\\/\\*\\|\\@\"!]*?)#(\\@)?(?:([\\w\\-]+|\\*)((?:\\([\\w\\-]+ (?:[$^*]?=[^\\(\\)\"]*)?\\))*)|#([^{}]+))$");
75 public static final Pattern RE_FILTER_REGEXP = Pattern
76 .compile("^(@@)?\\/.*\\/(?:\\$~?[\\w\\-]+(?:=[^,\\s]+)?(?:,~?[\\w\\-]+(?:= [^,\\s]+)?)*)?$");
77 public static final Pattern RE_FILTER_OPTIONS = Pattern
78 .compile("\\$(~?[\\w\\-]+(?:=[^,\\s]+)?(?:,~?[\\w\\-]+(?:=[^,\\s]+)?)*)$") ;
79 public static final Pattern RE_FILTER_CSSPROPERTY = Pattern
80 .compile("\\[\\-abp\\-properties=([\"'])([^\"']+)\\1\\]");
81 65
82 public static final String USER_FILTERS_TITLE = "__filters"; 66 public static final String USER_FILTERS_TITLE = "__filters";
83 public static final String USER_EXCEPTIONS_TITLE = "__exceptions"; 67 public static final String USER_EXCEPTIONS_TITLE = "__exceptions";
84 68
85 public static final String SBROWSER_APP_ID = "com.sec.android.app.sbrowser"; 69 public static final String SBROWSER_APP_ID = "com.sec.android.app.sbrowser";
86 private static final String ACTION_OPEN_SETTINGS = "com.samsung.android.sbrows er.contentBlocker.ACTION_SETTING"; 70 private static final String ACTION_OPEN_SETTINGS = "com.samsung.android.sbrows er.contentBlocker.ACTION_SETTING";
87 private static final String ACTION_UPDATE = "com.samsung.android.sbrowser.cont entBlocker.ACTION_UPDATE"; 71 private static final String ACTION_UPDATE = "com.samsung.android.sbrowser.cont entBlocker.ACTION_UPDATE";
88 private static final String EASYLIST_URL = "https://easylist-downloads.adblock plus.org/easylist.txt"; 72 private static final String EASYLIST_URL = "https://easylist-downloads.adblock plus.org/easylist.txt";
89 73
90 public static final String SUBSCRIPTIONS_EXCEPTIONSURL = "subscriptions_except ionsurl"; 74 public static final String SUBSCRIPTIONS_EXCEPTIONSURL = "subscriptions_except ionsurl";
91
92 private static final String PREFS_KEY_PREVIOUS_VERSION = "key_previous_version ";
93 75
94 // The value below specifies an interval of [x, 2*x[, where x = 76 // The value below specifies an interval of [x, 2*x[, where x =
95 // INITIAL_UPDATE_CHECK_DELAY 77 // INITIAL_UPDATE_CHECK_DELAY
96 private static final long INITIAL_UPDATE_CHECK_DELAY = 5 * DateUtils.SECOND_IN _MILLIS; 78 private static final long INITIAL_UPDATE_CHECK_DELAY = 5 * DateUtils.SECOND_IN _MILLIS;
97 private static final long UPDATE_CHECK_INTERVAL = 30 * DateUtils.MINUTE_IN_MIL LIS; 79 private static final long UPDATE_CHECK_INTERVAL = 30 * DateUtils.MINUTE_IN_MIL LIS;
98 private static final long BROADCAST_COMBINATION_DELAY = 2500; 80 private static final long BROADCAST_COMBINATION_DELAY = 2500;
99 81
100 private static final int NO_FLAG = 0; 82 private static final int NO_FLAG = 0;
101 private static final int OLDEST_SAMSUNG_INTERNET_5_VERSIONCODE = 500000000; 83 private static final int OLDEST_SAMSUNG_INTERNET_5_VERSIONCODE = 500000000;
102 84
103 private final ReentrantLock accessLock = new ReentrantLock(); 85 private final ReentrantLock accessLock = new ReentrantLock();
104 private DefaultSubscriptions defaultSubscriptions; 86 private DefaultSubscriptions defaultSubscriptions;
105 private Subscriptions subscriptions; 87 private Subscriptions subscriptions;
106 private JSONPrefs jsonPrefs; 88 private JSONPrefs jsonPrefs;
107 private AppInfo appInfo; 89 private AppInfo appInfo;
108 private final LinkedBlockingQueue<EngineEvent> engineEvents = new LinkedBlocki ngQueue<>(); 90 private final LinkedBlockingQueue<EngineEvent> engineEvents = new LinkedBlocki ngQueue<>();
109 private Thread handlerThread; 91 private Thread handlerThread;
110 private Downloader downloader; 92 private Downloader downloader;
93 private SubscriptionUpdateCallback subscriptionUpdateCallback;
111 private final Context serviceContext; 94 private final Context serviceContext;
112 private boolean wasFirstRun = false; 95 private boolean wasFirstRun = false;
113 private long nextUpdateBroadcast = Long.MAX_VALUE; 96 private long nextUpdateBroadcast = Long.MAX_VALUE;
114 97
115 private Engine(final Context context) 98 private Engine(final Context context)
116 { 99 {
117 this.serviceContext = context; 100 this.serviceContext = context;
118 } 101 }
119 102
120 public String getPrefsDefault(final String key) 103 public String getPrefsDefault(final String key)
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after
178 } 161 }
179 catch (PackageManager.NameNotFoundException e) 162 catch (PackageManager.NameNotFoundException e)
180 { 163 {
181 // Should never happen, as checkAAStatusAndProceed() should not be called if the user 164 // Should never happen, as checkAAStatusAndProceed() should not be called if the user
182 // has no compatible SBrowser installed. Nevertheless we have to handle th e Exception. 165 // has no compatible SBrowser installed. Nevertheless we have to handle th e Exception.
183 Log.d(TAG, "No compatible Samsung Browser found.", e); 166 Log.d(TAG, "No compatible Samsung Browser found.", e);
184 return false; 167 return false;
185 } 168 }
186 } 169 }
187 170
171 public void setSubscriptionUpdateCallback(final SubscriptionUpdateCallback sub scriptionUpdateCallback)
172 {
173 this.subscriptionUpdateCallback = subscriptionUpdateCallback;
174 }
175
188 public void requestUpdateBroadcast() 176 public void requestUpdateBroadcast()
189 { 177 {
190 this.lock(); 178 this.nextUpdateBroadcast = System.currentTimeMillis() + BROADCAST_COMBINATIO N_DELAY;
191 try
192 {
193 this.nextUpdateBroadcast = System.currentTimeMillis() + BROADCAST_COMBINAT ION_DELAY;
194 }
195 finally
196 {
197 this.unlock();
198 }
199 } 179 }
200 180
201 private void writeFileAndSendUpdateBroadcast() 181 private void writeFileAndSendUpdateBroadcast()
202 { 182 {
203 createAndWriteFile(); 183 createAndWriteFile();
204 184
205 runOnUiThread(new Runnable() 185 runOnUiThread(new Runnable()
206 { 186 {
207 @Override 187 @Override
208 public void run() 188 public void run()
209 { 189 {
210 final Intent intent = new Intent(); 190 final Intent intent = new Intent();
211 intent.setAction(ACTION_UPDATE); 191 intent.setAction(ACTION_UPDATE);
212 intent.setData(Uri.parse("package:" + Engine.this.serviceContext.getPack ageName())); 192 intent.setData(Uri.parse("package:" + Engine.this.serviceContext.getPack ageName()));
213 Engine.this.serviceContext.sendBroadcast(intent); 193 Engine.this.serviceContext.sendBroadcast(intent);
214 } 194 }
215 }); 195 });
216 } 196 }
217 197
218 boolean canUseInternet() 198 boolean canUseInternet()
219 { 199 {
220 final ConnectivityManager connManager = (ConnectivityManager) this.serviceCo ntext 200 final ConnectivityManager connManager = (ConnectivityManager) this.serviceCo ntext
221 .getSystemService(Context.CONNECTIVITY_SERVICE); 201 .getSystemService(Context.CONNECTIVITY_SERVICE);
222 final NetworkInfo current = connManager.getActiveNetworkInfo(); 202 final NetworkInfo current = connManager.getActiveNetworkInfo();
223 if (current == null) 203 if (current == null)
224 { 204 {
225 return false; 205 return false;
226 } 206 }
227 207
228 final SharedPreferences prefs = PreferenceManager 208 final boolean wifiOnly = "1".equals(SharedPrefsUtils.getString(
229 .getDefaultSharedPreferences(this.serviceContext); 209 this.serviceContext, R.string.key_automatic_updates , "1"));
230 final boolean wifiOnly = prefs.getString(
231 this.serviceContext.getString(R.string.key_automatic_updates), "1").equa ls("1");
232 210
233 if (wifiOnly) 211 if (wifiOnly)
234 { 212 {
235 if (current.isConnected() && !current.isRoaming()) 213 if (current.isConnected() && !current.isRoaming())
236 { 214 {
237 switch (current.getType()) 215 switch (current.getType())
238 { 216 {
239 case ConnectivityManager.TYPE_BLUETOOTH: 217 case ConnectivityManager.TYPE_BLUETOOTH:
240 case ConnectivityManager.TYPE_ETHERNET: 218 case ConnectivityManager.TYPE_ETHERNET:
241 case ConnectivityManager.TYPE_WIFI: 219 case ConnectivityManager.TYPE_WIFI:
242 case ConnectivityManager.TYPE_WIMAX: 220 case ConnectivityManager.TYPE_WIMAX:
243 return true; 221 return true;
244 default: 222 default:
245 return false; 223 return false;
246 } 224 }
247 } 225 }
248 return false; 226 return false;
249 } 227 }
250 return current.isConnected(); 228 return current.isConnected();
251 } 229 }
252 230
253 public List<SubscriptionInfo> getListedSubscriptions() 231 public List<SubscriptionInfo> getListedSubscriptions()
254 { 232 {
255 this.lock(); 233 return this.subscriptions.getSubscriptions(this);
256 try
257 {
258 return this.subscriptions.getSubscriptions(this);
259 }
260 finally
261 {
262 this.unlock();
263 }
264 } 234 }
265 235
266 public void changeSubscriptionState(final String id, final boolean enabled) 236 public void changeSubscriptionState(final String id, final boolean enabled)
267 { 237 {
238 if (this.subscriptionUpdateCallback != null)
239 {
240 subscriptionUpdateCallback.subscriptionUpdateRequested(enabled);
241 }
268 this.engineEvents.add(new ChangeEnabledStateEvent(id, enabled)); 242 this.engineEvents.add(new ChangeEnabledStateEvent(id, enabled));
243 }
244
245 public void subscriptionStateChanged()
246 {
247 if (this.subscriptionUpdateCallback != null)
248 {
249 subscriptionUpdateCallback.subscriptionUpdatedApplied();
250 }
269 } 251 }
270 252
271 void downloadFinished(final String id, final int responseCode, final String re sponse, 253 void downloadFinished(final String id, final int responseCode, final String re sponse,
272 final Map<String, String> headers) 254 final Map<String, String> headers)
273 { 255 {
274 this.engineEvents.add(new DownloadFinishedEvent(id, responseCode, response, headers)); 256 this.engineEvents.add(new DownloadFinishedEvent(id, responseCode, response, headers));
275 } 257 }
276 258
277 private void createAndWriteFile() 259 private void createAndWriteFile()
278 { 260 {
279 this.lock(); 261 this.lock();
280 try 262 try
281 { 263 {
282 Log.d(TAG, "Writing filters..."); 264 Log.d(TAG, "Writing filters...");
283 final File filterFile = this.subscriptions.createAndWriteFile(); 265 final File filterFile = this.subscriptions.createAndWriteFile();
284 writeWhitelistedWebsites(this.serviceContext, filterFile); 266 writeWhitelistedWebsites(this.serviceContext, filterFile);
285 267
286 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferen ces(this.serviceContext); 268 SharedPrefsUtils.putString(
287 final String key = this.serviceContext.getString(R.string.key_cached_filte r_path); 269 this.serviceContext, R.string.key_cached_filter_path, filterFile.getAb solutePath());
288 prefs.edit().putString(key, filterFile.getAbsolutePath()).commit();
289 270
290 Log.d(TAG, "Cleaning up cache..."); 271 Log.d(TAG, "Cleaning up cache...");
291 final File dummyFile = getDummyFilterFile(this.serviceContext); 272 final File dummyFile = getDummyFilterFile(this.serviceContext);
292 final File[] cacheDirFiles = getFilterCacheDir(this.serviceContext).listFi les(); 273 final File[] cacheDirFiles = getFilterCacheDir(this.serviceContext).listFi les();
293 if (cacheDirFiles != null) 274 if (cacheDirFiles != null)
294 { 275 {
295 for (final File file : cacheDirFiles) 276 for (final File file : cacheDirFiles)
296 { 277 {
297 if (!file.equals(dummyFile) && !file.equals(filterFile)) 278 if (!file.equals(dummyFile) && !file.equals(filterFile))
298 { 279 {
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
340 { 321 {
341 return this.wasFirstRun; 322 return this.wasFirstRun;
342 } 323 }
343 324
344 private void migrateFromPreviousVersion(final Context context) 325 private void migrateFromPreviousVersion(final Context context)
345 { 326 {
346 try 327 try
347 { 328 {
348 final int versionCode = context.getPackageManager().getPackageInfo(context .getPackageName(), 329 final int versionCode = context.getPackageManager().getPackageInfo(context .getPackageName(),
349 0).versionCode; 330 0).versionCode;
350 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferen ces(context); 331
351 int previous = prefs.getInt(PREFS_KEY_PREVIOUS_VERSION, 0); 332 final int previousVersionCode = SharedPrefsUtils.getInt(
352 if (versionCode > previous) 333 context, R.string.key_previous_version_code, 0);
353 { 334
354 if (previous > 0) 335 if (versionCode > previousVersionCode)
336 {
337 if (previousVersionCode > 0)
355 { 338 {
356 // We can do possible migration stuff here 339 // We can do possible migration stuff here
357 // Currently we only persist the new version code 340 // Currently we only persist the new version code
358 } 341 }
359 prefs.edit().putInt(PREFS_KEY_PREVIOUS_VERSION, versionCode).commit(); 342 SharedPrefsUtils.putInt(context, R.string.key_previous_version_code, ver sionCode);
360 } 343 }
361 } 344 }
362 catch (final Throwable t) 345 catch (final Throwable t)
363 { 346 {
364 Log.e(TAG, "Failed on migration, please clear all application data", t); 347 Log.e(TAG, "Failed on migration, please clear all application data", t);
365 } 348 }
366 } 349 }
367 350
368 static Engine create(final Context context) throws IOException 351 static Engine create(final Context context) throws IOException
369 { 352 {
(...skipping 134 matching lines...) Expand 10 before | Expand all | Expand 10 after
504 487
505 public static void writeFilterHeaders(Writer writer) throws IOException 488 public static void writeFilterHeaders(Writer writer) throws IOException
506 { 489 {
507 writer.write("[Adblock Plus 2.0]\n"); 490 writer.write("[Adblock Plus 2.0]\n");
508 writer.write("! This file was automatically created.\n"); 491 writer.write("! This file was automatically created.\n");
509 } 492 }
510 493
511 private static void writeWhitelistedWebsites(Context context, File filterFile) throws IOException 494 private static void writeWhitelistedWebsites(Context context, File filterFile) throws IOException
512 { 495 {
513 Log.d(TAG, "Writing whitelisted websites..."); 496 Log.d(TAG, "Writing whitelisted websites...");
514 final SharedPreferences prefs =
515 PreferenceManager.getDefaultSharedPreferences(context.getApplicationCont ext());
516 final String key = context.getString(R.string.key_whitelisted_websites);
517
518 final Set<String> whitelistedWebsites = new TreeSet<>(); 497 final Set<String> whitelistedWebsites = new TreeSet<>();
519 whitelistedWebsites.addAll(prefs.getStringSet(key, Collections.<String>empty Set())); 498 whitelistedWebsites.addAll(SharedPrefsUtils.getStringSet(
499 context, R.string.key_whitelisted_websites, Collections.<String>emptySet ()));
520 500
521 try (final BufferedWriter w = new BufferedWriter( new OutputStreamWriter( 501 try (final BufferedWriter w = new BufferedWriter( new OutputStreamWriter(
522 new FileOutputStream(filterFile, true), StandardCharsets.UTF_8))) 502 new FileOutputStream(filterFile, true), StandardCharsets.UTF_8)))
523 { 503 {
524 for (final String url : whitelistedWebsites) 504 for (final String url : whitelistedWebsites)
525 { 505 {
526 try 506 try
527 { 507 {
528 final URI uri = new URI(url); 508 final URI uri = new URI(url);
529 final String host = uri.getHost() != null ? uri.getHost() : uri.getPat h(); 509 final String host = uri.getHost() != null ? uri.getHost() : uri.getPat h();
530 w.write("@@||" + host + "^$document"); 510 w.write("@@||" + host + "^$document");
531 w.write('\n'); 511 w.write('\n');
532 } 512 }
533 catch (URISyntaxException e) 513 catch (URISyntaxException e)
534 { 514 {
535 Log.w(TAG, "Failed to parse whitelisted website: " + url); 515 Log.w(TAG, "Failed to parse whitelisted website: " + url);
536 continue;
537 } 516 }
538 } 517 }
539 } 518 }
540 } 519 }
541 520
542 private static File getCachedFilterFile(Context context) 521 private static File getCachedFilterFile(Context context)
543 { 522 {
544 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreference s(context); 523 final String cachedFilterPath = SharedPrefsUtils.getString(
545 final String cachedFilterPath = prefs.getString(context.getString(R.string.k ey_cached_filter_path), null); 524 context, R.string.key_cached_filter_path, null);
525
546 if (cachedFilterPath != null) 526 if (cachedFilterPath != null)
547 { 527 {
548 return new File(cachedFilterPath); 528 return new File(cachedFilterPath);
549 } 529 }
550 530
551 return null; 531 return null;
552 } 532 }
553 533
554 private static File getDummyFilterFile(Context context) 534 private static File getDummyFilterFile(Context context)
555 { 535 {
(...skipping 215 matching lines...) Expand 10 before | Expand all | Expand 10 after
771 } 751 }
772 Log.d(TAG, headers.toString()); 752 Log.d(TAG, headers.toString());
773 this.downloader.enqueueDownload(this.createDownloadURL(sub), sub.getId(), headers); 753 this.downloader.enqueueDownload(this.createDownloadURL(sub), sub.getId(), headers);
774 } 754 }
775 } 755 }
776 756
777 public void connectivityChanged() 757 public void connectivityChanged()
778 { 758 {
779 this.downloader.connectivityChanged(); 759 this.downloader.connectivityChanged();
780 } 760 }
761
762 public interface SubscriptionUpdateCallback
763 {
764 void subscriptionUpdateRequested(boolean enabled);
765 void subscriptionUpdatedApplied();
766 }
781 } 767 }
LEFTRIGHT

Powered by Google App Engine
This is Rietveld