From c2b8cdeb2c94bb1e605fd9f0d5495cc0077ab78a Mon Sep 17 00:00:00 2001 From: str4d Date: Sat, 11 Jul 2015 03:34:57 +0000 Subject: [PATCH 1/2] Centralize Java proxy settings --- mobile/android/base/CrashReporter.java | 6 ++--- mobile/android/base/SuggestClient.java | 6 ++--- .../base/distribution/Distribution.java | 6 ++--- .../base/favicons/LoadFaviconTask.java | 24 ++++++++++--------- mobile/android/base/moz.build | 3 +++ .../android/base/sync/net/BaseResource.java | 6 ++--- .../android/base/util/ProxyRoutePlanner.java | 23 ++++++++++++++++++ mobile/android/base/util/ProxySettings.java | 21 ++++++++++++++++ .../search/providers/SearchEngineManager.java | 7 +++--- .../service/utils/AbstractCommunicator.java | 1 + 10 files changed, 72 insertions(+), 31 deletions(-) create mode 100644 mobile/android/base/util/ProxyRoutePlanner.java create mode 100644 mobile/android/base/util/ProxySettings.java diff --git a/mobile/android/base/CrashReporter.java b/mobile/android/base/CrashReporter.java index 654bb80e4dbf..69c36eb69ad4 100644 --- a/mobile/android/base/CrashReporter.java +++ b/mobile/android/base/CrashReporter.java @@ -17,13 +17,12 @@ import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; -import java.net.Proxy; -import java.net.InetSocketAddress; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.util.zip.GZIPOutputStream; import org.mozilla.gecko.AppConstants.Versions; +import org.mozilla.gecko.util.ProxySettings; import android.app.Activity; import android.app.AlertDialog; @@ -354,8 +353,7 @@ private void sendReport(File minidumpFile, Map extras, File extr Log.i(LOGTAG, "server url: " + spec); try { URL url = new URL(spec); - Proxy torProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118)); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(torProxy); + HttpURLConnection conn = (HttpURLConnection)url.openConnection(ProxySettings.getProxy()); conn.setRequestMethod("POST"); String boundary = generateBoundary(); conn.setDoOutput(true); diff --git a/mobile/android/base/SuggestClient.java b/mobile/android/base/SuggestClient.java index aa718d5a778f..f9e79c2c0056 100644 --- a/mobile/android/base/SuggestClient.java +++ b/mobile/android/base/SuggestClient.java @@ -7,8 +7,6 @@ import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.Proxy; -import java.net.InetSocketAddress; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; @@ -16,6 +14,7 @@ import org.json.JSONArray; import org.mozilla.gecko.mozglue.RobocopTarget; +import org.mozilla.gecko.util.ProxySettings; import org.mozilla.gecko.util.HardwareUtils; import android.content.Context; @@ -86,8 +85,7 @@ public ArrayList query(String query) { HttpURLConnection urlConnection = null; InputStream in = null; try { - Proxy torProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118)); - urlConnection = (HttpURLConnection) url.openConnection(torProxy); + urlConnection = (HttpURLConnection) url.openConnection(ProxySettings.getProxy()); urlConnection.setConnectTimeout(mTimeout); urlConnection.setRequestProperty("User-Agent", USER_AGENT); in = new BufferedInputStream(urlConnection.getInputStream()); diff --git a/mobile/android/base/distribution/Distribution.java b/mobile/android/base/distribution/Distribution.java index 0fe2ca0fe1a1..01297b6a3aee 100644 --- a/mobile/android/base/distribution/Distribution.java +++ b/mobile/android/base/distribution/Distribution.java @@ -18,8 +18,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; -import java.net.Proxy; -import java.net.InetSocketAddress; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; @@ -44,6 +42,7 @@ import org.mozilla.gecko.GeckoSharedPrefs; import org.mozilla.gecko.Telemetry; import org.mozilla.gecko.mozglue.RobocopTarget; +import org.mozilla.gecko.util.ProxySettings; import org.mozilla.gecko.util.FileUtils; import org.mozilla.gecko.util.HardwareUtils; import org.mozilla.gecko.util.ThreadUtils; @@ -469,8 +468,7 @@ private boolean checkIntentDistribution(final ReferrerDescriptor referrer) { Log.v(LOGTAG, "Downloading referred distribution: " + uri); try { - Proxy torProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118)); - final HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(torProxy); + final HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(ProxySettings.getProxy()); // If the Search Activity starts, and we handle the referrer intent, this'll return // null. Recover gracefully in this case. diff --git a/mobile/android/base/favicons/LoadFaviconTask.java b/mobile/android/base/favicons/LoadFaviconTask.java index 35aef910b319..c75cc4ec0d40 100644 --- a/mobile/android/base/favicons/LoadFaviconTask.java +++ b/mobile/android/base/favicons/LoadFaviconTask.java @@ -8,26 +8,25 @@ import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; -import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import android.text.TextUtils; import android.util.Log; import ch.boye.httpclientandroidlib.Header; import ch.boye.httpclientandroidlib.HttpEntity; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.client.methods.HttpGet; -import ch.boye.httpclientandroidlib.HttpHost; -import ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames; +import ch.boye.httpclientandroidlib.impl.client.CloseableHttpClient; +import ch.boye.httpclientandroidlib.impl.client.HttpClients; import org.mozilla.gecko.GeckoAppShell; import org.mozilla.gecko.GeckoProfile; import org.mozilla.gecko.db.BrowserDB; import org.mozilla.gecko.favicons.decoders.FaviconDecoder; import org.mozilla.gecko.favicons.decoders.LoadFaviconResult; +import org.mozilla.gecko.util.ProxyRoutePlanner; import org.mozilla.gecko.util.GeckoJarReader; import org.mozilla.gecko.util.IOUtils; import org.mozilla.gecko.util.ThreadUtils; import java.io.IOException; -import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; @@ -74,7 +73,10 @@ public class LoadFaviconTask { private LinkedList chainees; private boolean isChaining; - static DefaultHttpClient httpClient = new DefaultHttpClient(); + static CloseableHttpClient httpClient = HttpClients.custom() + .setUserAgent(GeckoAppShell.getGeckoInterface().getDefaultUAString()) + .setRoutePlanner(new ProxyRoutePlanner()) + .build(); public LoadFaviconTask(Context context, String pageURL, String faviconURL, int flags, OnFaviconLoadedListener listener) { this(context, pageURL, faviconURL, flags, listener, -1, false); @@ -128,12 +130,9 @@ private HttpResponse tryDownloadRecurse(URI faviconURI, HashSet visited) if (visited.size() == MAX_REDIRECTS_TO_FOLLOW) { return null; } - - HttpHost torProxy = new HttpHost("127.0.0.1", 8118); + HttpGet request = new HttpGet(faviconURI); - request.setHeader("User-Agent", GeckoAppShell.getGeckoInterface().getDefaultUAString()); - httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, torProxy); - + HttpResponse response = httpClient.execute(request); if (response == null) { return null; @@ -610,7 +609,10 @@ static void closeHTTPClient() { // which counts as network activity. if (ThreadUtils.isOnBackgroundThread()) { if (httpClient != null) { - httpClient.close(); + try { + httpClient.close(); + } catch (IOException e) { + } } return; } diff --git a/mobile/android/base/moz.build b/mobile/android/base/moz.build index 28b6e1c32c2a..d1244cee927d 100644 --- a/mobile/android/base/moz.build +++ b/mobile/android/base/moz.build @@ -78,7 +78,9 @@ gujar.sources += [ 'util/NativeJSObject.java', 'util/NonEvictingLruCache.java', 'util/PrefUtils.java', + 'util/ProxyRoutePlanner.java', 'util/ProxySelector.java', + 'util/ProxySettings.java', 'util/RawResource.java', 'util/StringUtils.java', 'util/ThreadUtils.java', @@ -89,6 +91,7 @@ gujar.sources += [ gujar.extra_jars = [ 'constants.jar', 'gecko-mozglue.jar', + 'sync-thirdparty.jar', ] gujar.javac_flags += ['-Xlint:all,-deprecation'] diff --git a/mobile/android/base/sync/net/BaseResource.java b/mobile/android/base/sync/net/BaseResource.java index 6b4cbbee0ef8..ea3dfc961857 100644 --- a/mobile/android/base/sync/net/BaseResource.java +++ b/mobile/android/base/sync/net/BaseResource.java @@ -21,6 +21,7 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.mozilla.gecko.background.common.log.Logger; +import org.mozilla.gecko.util.ProxyRoutePlanner; import org.mozilla.gecko.sync.ExtendedJSONObject; import ch.boye.httpclientandroidlib.Header; @@ -52,8 +53,6 @@ import ch.boye.httpclientandroidlib.protocol.BasicHttpContext; import ch.boye.httpclientandroidlib.protocol.HttpContext; import ch.boye.httpclientandroidlib.util.EntityUtils; -import ch.boye.httpclientandroidlib.HttpHost; -import ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames; /** * Provide simple HTTP access to a Sync server or similar. @@ -183,8 +182,7 @@ protected void prepareClient() throws KeyManagementException, NoSuchAlgorithmExc // We could reuse these client instances, except that we mess around // with their parameters… so we'd need a pool of some kind. client = new DefaultHttpClient(getConnectionManager()); - HttpHost torProxy = new HttpHost("127.0.0.1", 8118); - client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, torProxy); + client.setRoutePlanner(new ProxyRoutePlanner()); // TODO: Eventually we should use Apache HttpAsyncClient. It's not out of alpha yet. // Until then, we synchronously make the request, then invoke our delegate's callback. diff --git a/mobile/android/base/util/ProxyRoutePlanner.java b/mobile/android/base/util/ProxyRoutePlanner.java new file mode 100644 index 000000000000..eba22f7689db --- /dev/null +++ b/mobile/android/base/util/ProxyRoutePlanner.java @@ -0,0 +1,23 @@ +package org.mozilla.gecko.util; + +import ch.boye.httpclientandroidlib.HttpException; +import ch.boye.httpclientandroidlib.HttpHost; +import ch.boye.httpclientandroidlib.HttpRequest; +import ch.boye.httpclientandroidlib.impl.conn.DefaultRoutePlanner; +import ch.boye.httpclientandroidlib.impl.conn.DefaultSchemePortResolver; +import ch.boye.httpclientandroidlib.protocol.HttpContext; + +public class ProxyRoutePlanner extends DefaultRoutePlanner { + public ProxyRoutePlanner() { + super(DefaultSchemePortResolver.INSTANCE); + } + + @Override + protected HttpHost determineProxy( + final HttpHost target, + final HttpRequest request, + final HttpContext context) throws HttpException { + // TODO multiple proxies handling different domains + return ProxySettings.getProxyHost(); + } +} diff --git a/mobile/android/base/util/ProxySettings.java b/mobile/android/base/util/ProxySettings.java new file mode 100644 index 000000000000..0f5d363d543f --- /dev/null +++ b/mobile/android/base/util/ProxySettings.java @@ -0,0 +1,21 @@ +package org.mozilla.gecko.util; + +import java.net.InetSocketAddress; +import java.net.Proxy; + +import ch.boye.httpclientandroidlib.HttpHost; + +public class ProxySettings { + private static final String TOR_PROXY_ADDRESS = "127.0.0.1"; + private static final int TOR_PROXY_PORT = 8118; + + public static Proxy getProxy() { + // TODO make configurable + return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(TOR_PROXY_ADDRESS, TOR_PROXY_PORT)); + } + + public static HttpHost getProxyHost() { + // TODO make configurable + return new HttpHost(TOR_PROXY_ADDRESS, TOR_PROXY_PORT); + } +} diff --git a/mobile/android/search/java/org/mozilla/search/providers/SearchEngineManager.java b/mobile/android/search/java/org/mozilla/search/providers/SearchEngineManager.java index c712c0725a16..33fb49fee95c 100644 --- a/mobile/android/search/java/org/mozilla/search/providers/SearchEngineManager.java +++ b/mobile/android/search/java/org/mozilla/search/providers/SearchEngineManager.java @@ -16,6 +16,7 @@ import org.mozilla.gecko.Locales; import org.mozilla.gecko.R; import org.mozilla.gecko.distribution.Distribution; +import org.mozilla.gecko.util.ProxySettings; import org.mozilla.gecko.util.FileUtils; import org.mozilla.gecko.util.GeckoJarReader; import org.mozilla.gecko.util.HardwareUtils; @@ -34,8 +35,6 @@ import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; -import java.net.Proxy; -import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.Locale; @@ -329,8 +328,8 @@ private String fetchCountryCode() { String responseText = null; URL url = new URL(GEOIP_LOCATION_URL); - Proxy torProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118)); - HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(torProxy); + HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection( + ProxySettings.getProxy()); try { // POST an empty JSON object. final String message = "{}"; diff --git a/mobile/android/stumbler/java/org/mozilla/mozstumbler/service/utils/AbstractCommunicator.java b/mobile/android/stumbler/java/org/mozilla/mozstumbler/service/utils/AbstractCommunicator.java index f67b8bd45711..b2f6563b04d3 100644 --- a/mobile/android/stumbler/java/org/mozilla/mozstumbler/service/utils/AbstractCommunicator.java +++ b/mobile/android/stumbler/java/org/mozilla/mozstumbler/service/utils/AbstractCommunicator.java @@ -75,6 +75,7 @@ private void openConnectionAndSetHeaders() { sMozApiKey = prefs.getMozApiKey(); } URL url = new URL(getUrlString() + "?key=" + sMozApiKey); + // TODO are we allowed to link to code in base? Proxy torProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8118)); mHttpURLConnection = (HttpURLConnection) url.openConnection(torProxy); mHttpURLConnection.setRequestMethod("POST"); From 50e5a6c53ddb2bf8d99581ae9b55a96476d30d31 Mon Sep 17 00:00:00 2001 From: str4d Date: Thu, 16 Jul 2015 23:01:22 +0000 Subject: [PATCH 2/2] Pass Context through to BaseResource --- .../background/bagheera/BagheeraClient.java | 12 ++++++++---- .../background/fxa/FxAccountClient10.java | 9 +++++++-- .../background/fxa/FxAccountClient20.java | 6 ++++-- .../fxa/oauth/FxAccountOAuthClient10.java | 6 ++++-- .../fxa/profile/FxAccountProfileClient10.java | 6 ++++-- .../upload/AndroidSubmissionClient.java | 4 ++-- .../BrowserIDRemoteVerifierClient10.java | 12 +++++++++--- .../BrowserIDRemoteVerifierClient20.java | 11 ++++++++--- ...ountAbstractUpdateCredentialsActivity.java | 2 +- .../FxAccountCreateAccountActivity.java | 2 +- .../activities/FxAccountSignInActivity.java | 2 +- .../FxADefaultLoginStateMachineDelegate.java | 2 +- .../authenticator/FxAccountAuthenticator.java | 4 ++-- .../base/fxa/sync/FxAccountSyncAdapter.java | 4 ++-- .../base/fxa/tasks/FxAccountCodeResender.java | 2 +- .../tasks/FxAccountUnlockCodeResender.java | 2 +- .../base/reading/ReadingListClient.java | 13 ++++++++----- .../base/reading/ReadingListSyncAdapter.java | 2 +- mobile/android/base/sync/GlobalSession.java | 8 ++++---- .../android/base/sync/JSONRecordFetcher.java | 8 ++++++-- mobile/android/base/sync/MetaGlobal.java | 10 +++++++--- .../base/sync/MigrationSentinelSyncStage.java | 2 +- .../base/sync/PersistedMetaGlobal.java | 7 +++++-- .../base/sync/Sync11Configuration.java | 7 +++++-- .../android/base/sync/SyncConfiguration.java | 11 +++++++---- .../sync/config/ClientRecordTerminator.java | 6 ++++-- .../android/base/sync/jpake/JPakeClient.java | 4 ++++ .../base/sync/jpake/stage/DeleteChannel.java | 2 +- .../sync/jpake/stage/GetChannelStage.java | 8 +++++--- .../sync/jpake/stage/GetRequestStage.java | 2 +- .../sync/jpake/stage/PutRequestStage.java | 2 +- .../android/base/sync/net/BaseResource.java | 19 ++++++++++++------- .../net/SyncStorageCollectionRequest.java | 6 ++++-- .../sync/net/SyncStorageRecordRequest.java | 10 ++++++---- .../base/sync/net/SyncStorageRequest.java | 10 ++++++---- .../receivers/SyncAccountDeletedService.java | 4 ++-- .../sync/repositories/Server11Repository.java | 2 +- .../Server11RepositorySession.java | 17 ++++++++++++----- .../sync/setup/auth/AccountAuthenticator.java | 5 +++++ .../setup/auth/AuthenticateAccountStage.java | 8 +++++--- .../setup/auth/EnsureUserExistenceStage.java | 2 +- .../sync/setup/auth/FetchUserNodeStage.java | 8 +++++--- ...ndroidBrowserBookmarksServerSyncStage.java | 2 +- .../sync/stage/EnsureClusterURLStage.java | 9 ++++++--- .../sync/stage/EnsureCrypto5KeysStage.java | 2 +- .../base/sync/stage/FetchMetaGlobalStage.java | 2 +- .../SafeConstrainedServer11Repository.java | 6 +++--- .../base/sync/stage/ServerSyncStage.java | 2 +- .../sync/stage/SyncClientsEngineStage.java | 6 +++--- .../base/sync/syncadapter/SyncAdapter.java | 2 +- .../base/tokenserver/TokenServerClient.java | 7 +++++-- 51 files changed, 197 insertions(+), 110 deletions(-) diff --git a/mobile/android/base/background/bagheera/BagheeraClient.java b/mobile/android/base/background/bagheera/BagheeraClient.java index f8a3d6c4e576..906cf4ec8a7c 100644 --- a/mobile/android/base/background/bagheera/BagheeraClient.java +++ b/mobile/android/base/background/bagheera/BagheeraClient.java @@ -4,6 +4,8 @@ package org.mozilla.gecko.background.bagheera; +import android.content.Context; + import java.io.IOException; import java.net.URISyntaxException; import java.security.GeneralSecurityException; @@ -32,6 +34,7 @@ */ public class BagheeraClient { + protected final Context mCtx; protected final String serverURI; protected final Executor executor; protected static final Pattern URI_PATTERN = Pattern.compile("^[a-zA-Z0-9_-]+$"); @@ -51,13 +54,14 @@ public class BagheeraClient { * @param executor * the executor which will be used to invoke delegate callbacks. */ - public BagheeraClient(final String serverURI, final Executor executor) { + public BagheeraClient(final Context ctx, final String serverURI, final Executor executor) { if (serverURI == null) { throw new IllegalArgumentException("Must provide a server URI."); } if (executor == null) { throw new IllegalArgumentException("Must provide a non-null executor."); } + this.mCtx = ctx; this.serverURI = serverURI.endsWith("/") ? serverURI : serverURI + "/"; this.executor = executor; } @@ -71,8 +75,8 @@ public BagheeraClient(final String serverURI, final Executor executor) { * @param serverURI * the destination server URI. */ - public BagheeraClient(final String serverURI) { - this(serverURI, Executors.newSingleThreadExecutor()); + public BagheeraClient(final Context ctx, final String serverURI) { + this(ctx, serverURI, Executors.newSingleThreadExecutor()); } /** @@ -147,7 +151,7 @@ protected BaseResource makeResource(final String namespace, final String id) thr final String uri = this.serverURI + PROTOCOL_VERSION + SUBMIT_PATH + namespace + "/" + id; - return new BaseResource(uri); + return new BaseResource(mCtx, uri); } public class BagheeraResourceDelegate extends BaseResourceDelegate { diff --git a/mobile/android/base/background/fxa/FxAccountClient10.java b/mobile/android/base/background/fxa/FxAccountClient10.java index 5ed1ffcc0c4b..4c56e8067858 100644 --- a/mobile/android/base/background/fxa/FxAccountClient10.java +++ b/mobile/android/base/background/fxa/FxAccountClient10.java @@ -20,6 +20,8 @@ import javax.crypto.Mac; +import android.content.Context; + import org.json.simple.JSONObject; import org.mozilla.gecko.background.fxa.FxAccountClientException.FxAccountClientMalformedResponseException; import org.mozilla.gecko.background.fxa.FxAccountClientException.FxAccountClientRemoteException; @@ -77,6 +79,8 @@ public class FxAccountClient10 { protected static final String[] requiredErrorStringFields = { JSON_KEY_ERROR, JSON_KEY_MESSAGE, JSON_KEY_INFO }; protected static final String[] requiredErrorLongFields = { JSON_KEY_CODE, JSON_KEY_ERRNO }; + protected final Context mCtx; + /** * The server's URI. *

@@ -87,13 +91,14 @@ public class FxAccountClient10 { protected final Executor executor; - public FxAccountClient10(String serverURI, Executor executor) { + public FxAccountClient10(Context ctx, String serverURI, Executor executor) { if (serverURI == null) { throw new IllegalArgumentException("Must provide a server URI."); } if (executor == null) { throw new IllegalArgumentException("Must provide a non-null executor."); } + this.mCtx = ctx; this.serverURI = serverURI.endsWith("/") ? serverURI : serverURI + "/"; if (!this.serverURI.endsWith("/")) { throw new IllegalArgumentException("Constructed serverURI must end with a trailing slash: " + this.serverURI); @@ -140,7 +145,7 @@ protected BaseResource getBaseResource(String path, String... queryParameters) t sb.append(URLEncoder.encode(val, "UTF-8")); } } - return new BaseResource(new URI(sb.toString())); + return new BaseResource(mCtx, new URI(sb.toString())); } /** diff --git a/mobile/android/base/background/fxa/FxAccountClient20.java b/mobile/android/base/background/fxa/FxAccountClient20.java index 52b6e42c9552..d06282479a7c 100644 --- a/mobile/android/base/background/fxa/FxAccountClient20.java +++ b/mobile/android/base/background/fxa/FxAccountClient20.java @@ -8,6 +8,8 @@ import java.util.Map; import java.util.concurrent.Executor; +import android.content.Context; + import org.json.simple.JSONObject; import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.background.fxa.FxAccountClientException.FxAccountClientRemoteException; @@ -22,8 +24,8 @@ public class FxAccountClient20 extends FxAccountClient10 implements FxAccountCli protected static final String[] LOGIN_RESPONSE_REQUIRED_STRING_FIELDS_KEYS = new String[] { JSON_KEY_UID, JSON_KEY_SESSIONTOKEN, JSON_KEY_KEYFETCHTOKEN, }; protected static final String[] LOGIN_RESPONSE_REQUIRED_BOOLEAN_FIELDS = new String[] { JSON_KEY_VERIFIED }; - public FxAccountClient20(String serverURI, Executor executor) { - super(serverURI, executor); + public FxAccountClient20(Context ctx, String serverURI, Executor executor) { + super(ctx, serverURI, executor); } /** diff --git a/mobile/android/base/background/fxa/oauth/FxAccountOAuthClient10.java b/mobile/android/base/background/fxa/oauth/FxAccountOAuthClient10.java index c8480e73b52d..8500a844a73f 100644 --- a/mobile/android/base/background/fxa/oauth/FxAccountOAuthClient10.java +++ b/mobile/android/base/background/fxa/oauth/FxAccountOAuthClient10.java @@ -8,6 +8,8 @@ import java.net.URISyntaxException; import java.util.concurrent.Executor; +import android.content.Context; + import org.mozilla.gecko.sync.ExtendedJSONObject; import org.mozilla.gecko.sync.net.BaseResource; @@ -59,10 +61,10 @@ public AuthorizationResponse(String access_token, String token_type, String scop } public void authorization(String client_id, String assertion, String state, String scope, - RequestDelegate delegate) { + RequestDelegate delegate, Context context) { final BaseResource resource; try { - resource = new BaseResource(new URI(serverURI + "authorization")); + resource = new BaseResource(context, new URI(serverURI + "authorization")); } catch (URISyntaxException e) { invokeHandleError(delegate, e); return; diff --git a/mobile/android/base/background/fxa/profile/FxAccountProfileClient10.java b/mobile/android/base/background/fxa/profile/FxAccountProfileClient10.java index cb851a8db3a1..67c2b31ea8e7 100644 --- a/mobile/android/base/background/fxa/profile/FxAccountProfileClient10.java +++ b/mobile/android/base/background/fxa/profile/FxAccountProfileClient10.java @@ -8,6 +8,8 @@ import java.net.URISyntaxException; import java.util.concurrent.Executor; +import android.content.Context; + import org.mozilla.gecko.background.fxa.oauth.FxAccountAbstractClient; import org.mozilla.gecko.sync.ExtendedJSONObject; import org.mozilla.gecko.sync.net.AuthHeaderProvider; @@ -27,10 +29,10 @@ public FxAccountProfileClient10(String serverURI, Executor executor) { super(serverURI, executor); } - public void profile(final String token, RequestDelegate delegate) { + public void profile(final String token, RequestDelegate delegate, Context context) { BaseResource resource; try { - resource = new BaseResource(new URI(serverURI + "profile")); + resource = new BaseResource(context, new URI(serverURI + "profile")); } catch (URISyntaxException e) { invokeHandleError(delegate, e); return; diff --git a/mobile/android/base/background/healthreport/upload/AndroidSubmissionClient.java b/mobile/android/base/background/healthreport/upload/AndroidSubmissionClient.java index b7ebfc28e1cf..9f6b52fdfdda 100644 --- a/mobile/android/base/background/healthreport/upload/AndroidSubmissionClient.java +++ b/mobile/android/base/background/healthreport/upload/AndroidSubmissionClient.java @@ -100,7 +100,7 @@ protected JSONObject generateDocument(final long localTime, final long last, } protected void uploadPayload(String id, String payload, Collection oldIds, BagheeraRequestDelegate uploadDelegate) { - final BagheeraClient client = new BagheeraClient(getDocumentServerURI()); + final BagheeraClient client = new BagheeraClient(context, getDocumentServerURI()); Logger.pii(LOG_TAG, "New health report has id " + id + "and obsoletes " + (oldIds != null ? Integer.toString(oldIds.size()) : "no") + " old ids."); @@ -186,7 +186,7 @@ protected SubmissionsTracker getSubmissionsTracker(final HealthReportStorage sto @Override public void delete(final long localTime, final String id, Delegate delegate) { - final BagheeraClient client = new BagheeraClient(getDocumentServerURI()); + final BagheeraClient client = new BagheeraClient(context, getDocumentServerURI()); Logger.pii(LOG_TAG, "Deleting health report with id " + id + "."); diff --git a/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient10.java b/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient10.java index f61a82323fe9..eccc4394765e 100644 --- a/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient10.java +++ b/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient10.java @@ -4,6 +4,8 @@ package org.mozilla.gecko.browserid.verifier; +import android.content.Context; + import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; @@ -25,12 +27,16 @@ public class BrowserIDRemoteVerifierClient10 extends AbstractBrowserIDRemoteVeri public static final String DEFAULT_VERIFIER_URL = "https://verifier.login.persona.org/verify"; - public BrowserIDRemoteVerifierClient10() throws URISyntaxException { + private final Context mCtx; + + public BrowserIDRemoteVerifierClient10(Context ctx) throws URISyntaxException { super(new URI(DEFAULT_VERIFIER_URL)); + mCtx = ctx; } - public BrowserIDRemoteVerifierClient10(URI verifierUri) { + public BrowserIDRemoteVerifierClient10(Context ctx, URI verifierUri) { super(verifierUri); + mCtx = ctx; } @Override @@ -45,7 +51,7 @@ public void verify(String audience, String assertion, final BrowserIDVerifierDel throw new IllegalArgumentException("delegate cannot be null."); } - BaseResource r = new BaseResource(verifierUri); + BaseResource r = new BaseResource(mCtx, verifierUri); r.delegate = new RemoteVerifierResourceDelegate(r, delegate); diff --git a/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient20.java b/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient20.java index 013856576d16..8143c8856140 100644 --- a/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient20.java +++ b/mobile/android/base/browserid/verifier/BrowserIDRemoteVerifierClient20.java @@ -6,6 +6,7 @@ import java.net.URI; import java.net.URISyntaxException; +import android.content.Context; import org.mozilla.gecko.sync.ExtendedJSONObject; import org.mozilla.gecko.sync.net.BaseResource; @@ -22,12 +23,16 @@ public class BrowserIDRemoteVerifierClient20 extends AbstractBrowserIDRemoteVeri protected static final String JSON_KEY_ASSERTION = "assertion"; protected static final String JSON_KEY_AUDIENCE = "audience"; - public BrowserIDRemoteVerifierClient20() throws URISyntaxException { + private final Context mCtx; + + public BrowserIDRemoteVerifierClient20(Context ctx) throws URISyntaxException { super(new URI(DEFAULT_VERIFIER_URL)); + mCtx = ctx; } - public BrowserIDRemoteVerifierClient20(URI verifierUri) { + public BrowserIDRemoteVerifierClient20(Context ctx, URI verifierUri) { super(verifierUri); + mCtx = ctx; } @Override @@ -42,7 +47,7 @@ public void verify(String audience, String assertion, final BrowserIDVerifierDel throw new IllegalArgumentException("delegate cannot be null."); } - BaseResource r = new BaseResource(verifierUri); + BaseResource r = new BaseResource(mCtx, verifierUri); r.delegate = new RemoteVerifierResourceDelegate(r, delegate); final ExtendedJSONObject requestBody = new ExtendedJSONObject(); diff --git a/mobile/android/base/fxa/activities/FxAccountAbstractUpdateCredentialsActivity.java b/mobile/android/base/fxa/activities/FxAccountAbstractUpdateCredentialsActivity.java index d68eb3608429..74c738c2d4f0 100644 --- a/mobile/android/base/fxa/activities/FxAccountAbstractUpdateCredentialsActivity.java +++ b/mobile/android/base/fxa/activities/FxAccountAbstractUpdateCredentialsActivity.java @@ -161,7 +161,7 @@ public void handleSuccess(LoginResponse result) { public void updateCredentials(String email, String password) { String serverURI = fxAccount.getAccountServerURI(); Executor executor = Executors.newSingleThreadExecutor(); - FxAccountClient client = new FxAccountClient20(serverURI, executor); + FxAccountClient client = new FxAccountClient20(this, serverURI, executor); PasswordStretcher passwordStretcher = makePasswordStretcher(password); try { hideRemoteError(); diff --git a/mobile/android/base/fxa/activities/FxAccountCreateAccountActivity.java b/mobile/android/base/fxa/activities/FxAccountCreateAccountActivity.java index 1ba2be12b7b3..460548737deb 100644 --- a/mobile/android/base/fxa/activities/FxAccountCreateAccountActivity.java +++ b/mobile/android/base/fxa/activities/FxAccountCreateAccountActivity.java @@ -386,7 +386,7 @@ public void handleFailure(FxAccountClientRemoteException e) { }; Executor executor = Executors.newSingleThreadExecutor(); - FxAccountClient client = new FxAccountClient20(serverURI, executor); + FxAccountClient client = new FxAccountClient20(this, serverURI, executor); try { hideRemoteError(); new FxAccountCreateAccountTask(this, this, email, passwordStretcher, client, getQueryParameters(), delegate).execute(); diff --git a/mobile/android/base/fxa/activities/FxAccountSignInActivity.java b/mobile/android/base/fxa/activities/FxAccountSignInActivity.java index eed7a1b567ad..f69018928697 100644 --- a/mobile/android/base/fxa/activities/FxAccountSignInActivity.java +++ b/mobile/android/base/fxa/activities/FxAccountSignInActivity.java @@ -109,7 +109,7 @@ public void handleFailure(FxAccountClientRemoteException e) { }; Executor executor = Executors.newSingleThreadExecutor(); - FxAccountClient client = new FxAccountClient20(serverURI, executor); + FxAccountClient client = new FxAccountClient20(this, serverURI, executor); try { hideRemoteError(); new FxAccountSignInTask(this, this, email, passwordStretcher, client, getQueryParameters(), delegate).execute(); diff --git a/mobile/android/base/fxa/authenticator/FxADefaultLoginStateMachineDelegate.java b/mobile/android/base/fxa/authenticator/FxADefaultLoginStateMachineDelegate.java index ff31223224bd..375715906436 100644 --- a/mobile/android/base/fxa/authenticator/FxADefaultLoginStateMachineDelegate.java +++ b/mobile/android/base/fxa/authenticator/FxADefaultLoginStateMachineDelegate.java @@ -35,7 +35,7 @@ public FxADefaultLoginStateMachineDelegate(Context context, AndroidFxAccount fxA this.context = context; this.fxAccount = fxAccount; this.executor = Executors.newSingleThreadExecutor(); - this.client = new FxAccountClient20(fxAccount.getAccountServerURI(), executor); + this.client = new FxAccountClient20(context, fxAccount.getAccountServerURI(), executor); } abstract public void handleNotMarried(State notMarried); diff --git a/mobile/android/base/fxa/authenticator/FxAccountAuthenticator.java b/mobile/android/base/fxa/authenticator/FxAccountAuthenticator.java index c043ed102e55..dd004c65aa59 100644 --- a/mobile/android/base/fxa/authenticator/FxAccountAuthenticator.java +++ b/mobile/android/base/fxa/authenticator/FxAccountAuthenticator.java @@ -130,7 +130,7 @@ public FxADefaultLoginStateMachineDelegate(Context context, AndroidFxAccount fxA this.context = context; this.fxAccount = fxAccount; this.executor = Executors.newSingleThreadExecutor(); - this.client = new FxAccountClient20(fxAccount.getAccountServerURI(), executor); + this.client = new FxAccountClient20(context, fxAccount.getAccountServerURI(), executor); } @Override @@ -253,7 +253,7 @@ public void handleError(Exception e) { Logger.error(LOG_TAG, "OAuth error.", e); responder.fail(e); } - }); + }, context); } }); } diff --git a/mobile/android/base/fxa/sync/FxAccountSyncAdapter.java b/mobile/android/base/fxa/sync/FxAccountSyncAdapter.java index fef11a114ec0..46ba2691fafb 100644 --- a/mobile/android/base/fxa/sync/FxAccountSyncAdapter.java +++ b/mobile/android/base/fxa/sync/FxAccountSyncAdapter.java @@ -311,7 +311,7 @@ public void handleSuccess(final TokenServerToken token) { final AuthHeaderProvider authHeaderProvider = new HawkAuthHeaderProvider(token.id, token.key.getBytes("UTF-8"), includePayloadVerificationHash, storageServerSkew); final Context context = getContext(); - final SyncConfiguration syncConfig = new SyncConfiguration(token.uid, authHeaderProvider, sharedPrefs, syncKeyBundle); + final SyncConfiguration syncConfig = new SyncConfiguration(token.uid, authHeaderProvider, context, sharedPrefs, syncKeyBundle); Collection knownStageNames = SyncConfiguration.validEngineNames(); syncConfig.stagesToSync = Utils.getStagesToSyncFromBundle(knownStageNames, extras); @@ -365,7 +365,7 @@ private long delay(long delay) { }; TokenServerClient tokenServerclient = new TokenServerClient(tokenServerEndpointURI, executor); - tokenServerclient.getTokenFromBrowserIDAssertion(assertion, true, clientState, delegate); + tokenServerclient.getTokenFromBrowserIDAssertion(assertion, true, clientState, delegate, getContext()); } /** diff --git a/mobile/android/base/fxa/tasks/FxAccountCodeResender.java b/mobile/android/base/fxa/tasks/FxAccountCodeResender.java index d98e97f0804c..ac04e9524b1a 100644 --- a/mobile/android/base/fxa/tasks/FxAccountCodeResender.java +++ b/mobile/android/base/fxa/tasks/FxAccountCodeResender.java @@ -103,7 +103,7 @@ public static void resendCode(Context context, AndroidFxAccount fxAccount) { } Executor executor = Executors.newSingleThreadExecutor(); - FxAccountClient client = new FxAccountClient20(fxAccount.getAccountServerURI(), executor); + FxAccountClient client = new FxAccountClient20(context, fxAccount.getAccountServerURI(), executor); new FxAccountResendCodeTask(context, sessionToken, client, delegate).execute(); } } diff --git a/mobile/android/base/fxa/tasks/FxAccountUnlockCodeResender.java b/mobile/android/base/fxa/tasks/FxAccountUnlockCodeResender.java index 0f32f3e22272..8a1676661956 100644 --- a/mobile/android/base/fxa/tasks/FxAccountUnlockCodeResender.java +++ b/mobile/android/base/fxa/tasks/FxAccountUnlockCodeResender.java @@ -99,7 +99,7 @@ public static void resendUnlockCode(Context context, String authServerURI, byte[ } final Executor executor = Executors.newSingleThreadExecutor(); - final FxAccountClient client = new FxAccountClient20(authServerURI, executor); + final FxAccountClient client = new FxAccountClient20(context, authServerURI, executor); new FxAccountUnlockCodeTask(context, emailUTF8, client, delegate).execute(); } } diff --git a/mobile/android/base/reading/ReadingListClient.java b/mobile/android/base/reading/ReadingListClient.java index f43974bb7a22..dc9ecf6760a8 100644 --- a/mobile/android/base/reading/ReadingListClient.java +++ b/mobile/android/base/reading/ReadingListClient.java @@ -10,6 +10,7 @@ import java.security.GeneralSecurityException; import java.util.Queue; import java.util.concurrent.Executor; +import android.content.Context; import org.mozilla.gecko.background.ReadingListConstants; import org.mozilla.gecko.background.common.log.Logger; @@ -35,20 +36,22 @@ public class ReadingListClient { static final String LOG_TAG = ReadingListClient.class.getSimpleName(); private final AuthHeaderProvider auth; + private final Context mCtx; private final URI articlesURI; // .../articles private final URI articlesBaseURI; // .../articles/ /** * Use a {@link BasicAuthHeaderProvider} for testing, and an FxA OAuth provider for the real service. */ - public ReadingListClient(final URI serviceURI, final AuthHeaderProvider auth) { + public ReadingListClient(final Context ctx, final URI serviceURI, final AuthHeaderProvider auth) { + this.mCtx = ctx; this.articlesURI = serviceURI.resolve("articles"); this.articlesBaseURI = serviceURI.resolve("articles/"); this.auth = auth; } private BaseResource getRelativeArticleResource(final String rel) { - return new BaseResource(this.articlesBaseURI.resolve(rel)); + return new BaseResource(mCtx, this.articlesBaseURI.resolve(rel)); } private static final class DelegatingUploadResourceDelegate extends UploadResourceDelegate { @@ -516,7 +519,7 @@ public void getOne(final String guid, ReadingListRecordDelegate delegate, final // Deliberately declare `delegate` non-final so we can't capture it below. We prefer // to use `recordDelegate` explicitly. public void getAll(final FetchSpec spec, ReadingListRecordDelegate delegate, final long ifModifiedSince) throws URISyntaxException { - final BaseResource r = new BaseResource(spec.getURI(this.articlesURI)); + final BaseResource r = new BaseResource(mCtx, spec.getURI(this.articlesURI)); r.delegate = new MultipleRecordResourceDelegate(r, auth, delegate, ReadingListStorageResponse.FACTORY, ifModifiedSince); if (ReadingListConstants.DEBUG) { Logger.info(LOG_TAG, "Getting all records from " + r.getURIString()); @@ -571,7 +574,7 @@ public void add(final Queue queue, final Executor execu } public void add(final ClientReadingListRecord up, final ReadingListRecordUploadDelegate uploadDelegate) { - final BaseResource r = new BaseResource(this.articlesURI); + final BaseResource r = new BaseResource(mCtx, this.articlesURI); r.delegate = new DelegatingUploadResourceDelegate(r, auth, ReadingListRecordResponse.FACTORY, up, uploadDelegate); @@ -655,7 +658,7 @@ void onNonSuccess(ReadingListRecordResponse response) { // TODO: modified times etc. public void wipe(final ReadingListWipeDelegate delegate) { Logger.info(LOG_TAG, "Wiping server."); - final BaseResource r = new BaseResource(this.articlesURI); + final BaseResource r = new BaseResource(mCtx, this.articlesURI); r.delegate = new ReadingListResourceDelegate(r, auth, ReadingListStorageResponse.FACTORY) { diff --git a/mobile/android/base/reading/ReadingListSyncAdapter.java b/mobile/android/base/reading/ReadingListSyncAdapter.java index d29b36efbe4a..2dba0242e747 100644 --- a/mobile/android/base/reading/ReadingListSyncAdapter.java +++ b/mobile/android/base/reading/ReadingListSyncAdapter.java @@ -134,7 +134,7 @@ private void syncWithAuthorization(final Context context, final AuthHeaderProvider auth = new BearerAuthHeaderProvider(authToken); final PrefsBranch branch = new PrefsBranch(sharedPrefs, "readinglist."); - final ReadingListClient remote = new ReadingListClient(endpoint, auth); + final ReadingListClient remote = new ReadingListClient(context, endpoint, auth); final ContentProviderClient cpc = getContentProviderClient(context); // Released by the inner SyncAdapterSynchronizerDelegate. final LocalReadingListStorage local = new LocalReadingListStorage(cpc); diff --git a/mobile/android/base/sync/GlobalSession.java b/mobile/android/base/sync/GlobalSession.java index bb7c65738c5a..2cc67776ed30 100644 --- a/mobile/android/base/sync/GlobalSession.java +++ b/mobile/android/base/sync/GlobalSession.java @@ -520,7 +520,7 @@ protected void interpretHTTPBadRequestBody(final SyncStorageResponse storageResp } public void fetchInfoCollections(JSONRecordFetchDelegate callback) throws URISyntaxException { - final JSONRecordFetcher fetcher = new JSONRecordFetcher(config.infoCollectionsURL(), getAuthHeaderProvider()); + final JSONRecordFetcher fetcher = new JSONRecordFetcher(getContext(), config.infoCollectionsURL(), getAuthHeaderProvider()); fetcher.fetch(callback); } @@ -536,7 +536,7 @@ public void uploadKeys(final CollectionKeys keys, final KeyUploadDelegate keyUploadDelegate) { SyncStorageRecordRequest request; try { - request = new SyncStorageRecordRequest(this.config.keysURI()); + request = new SyncStorageRecordRequest(getContext(), this.config.keysURI()); } catch (URISyntaxException e) { keyUploadDelegate.onKeyUploadFailed(e); return; @@ -835,7 +835,7 @@ protected void wipeServer(final AuthHeaderProvider authHeaderProvider, final Wip final GlobalSession self = this; try { - request = new SyncStorageRequest(config.storageURL()); + request = new SyncStorageRequest(getContext(), config.storageURL()); } catch (URISyntaxException ex) { Logger.warn(LOG_TAG, "Invalid URI in wipeServer."); wipeDelegate.onWipeFailed(ex); @@ -1026,7 +1026,7 @@ public MetaGlobal generateNewMetaGlobal() { engines.put(engineName, engineSettings.toJSONObject()); } - MetaGlobal metaGlobal = new MetaGlobal(metaURL, this.getAuthHeaderProvider()); + MetaGlobal metaGlobal = new MetaGlobal(getContext(), metaURL, this.getAuthHeaderProvider()); metaGlobal.setSyncID(newSyncID); metaGlobal.setStorageVersion(STORAGE_VERSION); metaGlobal.setEngines(engines); diff --git a/mobile/android/base/sync/JSONRecordFetcher.java b/mobile/android/base/sync/JSONRecordFetcher.java index 982b5b0266b9..0343e821c03c 100644 --- a/mobile/android/base/sync/JSONRecordFetcher.java +++ b/mobile/android/base/sync/JSONRecordFetcher.java @@ -7,6 +7,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import android.content.Context; + import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.delegates.JSONRecordFetchDelegate; import org.mozilla.gecko.sync.net.AuthHeaderProvider; @@ -22,14 +24,16 @@ public class JSONRecordFetcher { private static final long DEFAULT_AWAIT_TIMEOUT_MSEC = 2 * 60 * 1000; // Two minutes. private static final String LOG_TAG = "JSONRecordFetcher"; + protected final Context mCtx; protected final AuthHeaderProvider authHeaderProvider; protected final String uri; protected JSONRecordFetchDelegate delegate; - public JSONRecordFetcher(final String uri, final AuthHeaderProvider authHeaderProvider) { + public JSONRecordFetcher(final Context ctx, final String uri, final AuthHeaderProvider authHeaderProvider) { if (uri == null) { throw new IllegalArgumentException("uri must not be null"); } + this.mCtx = ctx; this.uri = uri; this.authHeaderProvider = authHeaderProvider; } @@ -78,7 +82,7 @@ public void handleRequestError(Exception ex) { public void fetch(final JSONRecordFetchDelegate delegate) { this.delegate = delegate; try { - final SyncStorageRecordRequest r = new SyncStorageRecordRequest(this.getURI()); + final SyncStorageRecordRequest r = new SyncStorageRecordRequest(mCtx, this.getURI()); r.delegate = new JSONFetchHandler(); r.get(); } catch (Exception e) { diff --git a/mobile/android/base/sync/MetaGlobal.java b/mobile/android/base/sync/MetaGlobal.java index 62361831a461..99158960a714 100644 --- a/mobile/android/base/sync/MetaGlobal.java +++ b/mobile/android/base/sync/MetaGlobal.java @@ -12,6 +12,8 @@ import java.util.Map; import java.util.Set; +import android.content.Context; + import org.json.simple.JSONArray; import org.json.simple.parser.ParseException; import org.mozilla.gecko.background.common.log.Logger; @@ -25,6 +27,7 @@ public class MetaGlobal implements SyncStorageRequestDelegate { private static final String LOG_TAG = "MetaGlobal"; + protected final Context mCtx; protected String metaURL; // Fields. @@ -45,7 +48,8 @@ public class MetaGlobal implements SyncStorageRequestDelegate { private boolean isUploading; protected final AuthHeaderProvider authHeaderProvider; - public MetaGlobal(String metaURL, AuthHeaderProvider authHeaderProvider) { + public MetaGlobal(Context ctx, String metaURL, AuthHeaderProvider authHeaderProvider) { + this.mCtx = ctx; this.metaURL = metaURL; this.authHeaderProvider = authHeaderProvider; } @@ -54,7 +58,7 @@ public void fetch(MetaGlobalDelegate delegate) { this.callback = delegate; try { this.isUploading = false; - SyncStorageRecordRequest r = new SyncStorageRecordRequest(this.metaURL); + SyncStorageRecordRequest r = new SyncStorageRecordRequest(this.mCtx, this.metaURL); r.delegate = this; r.deferGet(); } catch (URISyntaxException e) { @@ -65,7 +69,7 @@ public void fetch(MetaGlobalDelegate delegate) { public void upload(MetaGlobalDelegate callback) { try { this.isUploading = true; - SyncStorageRecordRequest r = new SyncStorageRecordRequest(this.metaURL); + SyncStorageRecordRequest r = new SyncStorageRecordRequest(this.mCtx, this.metaURL); r.delegate = this; this.callback = callback; diff --git a/mobile/android/base/sync/MigrationSentinelSyncStage.java b/mobile/android/base/sync/MigrationSentinelSyncStage.java index 6a50beb8137d..9b3205407a3c 100644 --- a/mobile/android/base/sync/MigrationSentinelSyncStage.java +++ b/mobile/android/base/sync/MigrationSentinelSyncStage.java @@ -174,7 +174,7 @@ private void onError(Exception ex, String reason) { public void check() { final String url = session.config.storageURL() + META_FXA_CREDENTIALS; try { - final SyncStorageRecordRequest request = new SyncStorageRecordRequest(url); + final SyncStorageRecordRequest request = new SyncStorageRecordRequest(session.getContext(), url); request.delegate = new SyncStorageRequestDelegate() { @Override diff --git a/mobile/android/base/sync/PersistedMetaGlobal.java b/mobile/android/base/sync/PersistedMetaGlobal.java index d3467545c2a6..8284d67846ec 100644 --- a/mobile/android/base/sync/PersistedMetaGlobal.java +++ b/mobile/android/base/sync/PersistedMetaGlobal.java @@ -7,6 +7,7 @@ import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.net.AuthHeaderProvider; +import android.content.Context; import android.content.SharedPreferences; public class PersistedMetaGlobal { @@ -15,9 +16,11 @@ public class PersistedMetaGlobal { public static final String META_GLOBAL_SERVER_RESPONSE_BODY = "metaGlobalServerResponseBody"; public static final String META_GLOBAL_LAST_MODIFIED = "metaGlobalLastModified"; + protected Context mCtx; protected SharedPreferences prefs; - public PersistedMetaGlobal(SharedPreferences prefs) { + public PersistedMetaGlobal(Context ctx, SharedPreferences prefs) { + this.mCtx = ctx; this.prefs = prefs; } @@ -40,7 +43,7 @@ public MetaGlobal metaGlobal(String metaUrl, AuthHeaderProvider authHeaderProvid MetaGlobal metaGlobal = null; try { CryptoRecord cryptoRecord = CryptoRecord.fromJSONRecord(json); - MetaGlobal mg = new MetaGlobal(metaUrl, authHeaderProvider); + MetaGlobal mg = new MetaGlobal(mCtx, metaUrl, authHeaderProvider); mg.setFromRecord(cryptoRecord); metaGlobal = mg; } catch (Exception e) { diff --git a/mobile/android/base/sync/Sync11Configuration.java b/mobile/android/base/sync/Sync11Configuration.java index 4b2280895589..d0cc48ae7cec 100644 --- a/mobile/android/base/sync/Sync11Configuration.java +++ b/mobile/android/base/sync/Sync11Configuration.java @@ -10,6 +10,7 @@ import org.mozilla.gecko.sync.crypto.KeyBundle; import org.mozilla.gecko.sync.net.AuthHeaderProvider; +import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; @@ -24,15 +25,17 @@ public class Sync11Configuration extends SyncConfiguration { public Sync11Configuration(String username, AuthHeaderProvider authHeaderProvider, + Context ctx, SharedPreferences prefs) { - super(username, authHeaderProvider, prefs); + super(username, authHeaderProvider, ctx, prefs); } public Sync11Configuration(String username, AuthHeaderProvider authHeaderProvider, + Context ctx, SharedPreferences prefs, KeyBundle keyBundle) { - super(username, authHeaderProvider, prefs, keyBundle); + super(username, authHeaderProvider, ctx, prefs, keyBundle); } @Override diff --git a/mobile/android/base/sync/SyncConfiguration.java b/mobile/android/base/sync/SyncConfiguration.java index e1e6ad76afcc..0578c4731246 100644 --- a/mobile/android/base/sync/SyncConfiguration.java +++ b/mobile/android/base/sync/SyncConfiguration.java @@ -20,6 +20,7 @@ import org.mozilla.gecko.sync.net.AuthHeaderProvider; import org.mozilla.gecko.sync.stage.GlobalSyncStage.Stage; +import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; @@ -87,6 +88,7 @@ public class SyncConfiguration { public SharedPreferences prefs; protected final AuthHeaderProvider authHeaderProvider; + protected final Context mCtx; public static final String PREF_PREFS_VERSION = "prefs.version"; public static final long CURRENT_PREFS_VERSION = 1; @@ -112,15 +114,16 @@ public class SyncConfiguration { private static final String API_VERSION = "1.5"; - public SyncConfiguration(String username, AuthHeaderProvider authHeaderProvider, SharedPreferences prefs) { + public SyncConfiguration(String username, AuthHeaderProvider authHeaderProvider, Context ctx, SharedPreferences prefs) { this.username = username; this.authHeaderProvider = authHeaderProvider; + this.mCtx = ctx; this.prefs = prefs; this.loadFromPrefs(prefs); } - public SyncConfiguration(String username, AuthHeaderProvider authHeaderProvider, SharedPreferences prefs, KeyBundle syncKeyBundle) { - this(username, authHeaderProvider, prefs); + public SyncConfiguration(String username, AuthHeaderProvider authHeaderProvider, Context ctx, SharedPreferences prefs, KeyBundle syncKeyBundle) { + this(username, authHeaderProvider, ctx, prefs); this.syncKeyBundle = syncKeyBundle; } @@ -469,6 +472,6 @@ public PersistedCrypto5Keys persistedCryptoKeys() { } public PersistedMetaGlobal persistedMetaGlobal() { - return new PersistedMetaGlobal(getPrefs()); + return new PersistedMetaGlobal(mCtx, getPrefs()); } } diff --git a/mobile/android/base/sync/config/ClientRecordTerminator.java b/mobile/android/base/sync/config/ClientRecordTerminator.java index 0ec1d3955d03..40972a64f1b4 100644 --- a/mobile/android/base/sync/config/ClientRecordTerminator.java +++ b/mobile/android/base/sync/config/ClientRecordTerminator.java @@ -6,6 +6,8 @@ import java.net.URI; +import android.content.Context; + import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.SyncConfiguration; import org.mozilla.gecko.sync.net.AuthHeaderProvider; @@ -27,14 +29,14 @@ protected ClientRecordTerminator() { super(); // Stop this class from being instantiated. } - public static void deleteClientRecord(final SyncConfiguration config, final String clientGUID) + public static void deleteClientRecord(final Context context, final SyncConfiguration config, final String clientGUID) throws Exception { final String collection = "clients"; final URI wboURI = config.wboURI(collection, clientGUID); // Would prefer to break this out into a self-contained client library. - final SyncStorageRecordRequest r = new SyncStorageRecordRequest(wboURI); + final SyncStorageRecordRequest r = new SyncStorageRecordRequest(context, wboURI); r.delegate = new SyncStorageRequestDelegate() { @Override public AuthHeaderProvider getAuthHeaderProvider() { diff --git a/mobile/android/base/sync/jpake/JPakeClient.java b/mobile/android/base/sync/jpake/JPakeClient.java index dab820ba71d4..282052a84c61 100644 --- a/mobile/android/base/sync/jpake/JPakeClient.java +++ b/mobile/android/base/sync/jpake/JPakeClient.java @@ -9,6 +9,8 @@ import java.util.LinkedList; import java.util.Queue; +import android.content.Context; + import org.json.simple.JSONObject; import org.mozilla.apache.commons.codec.binary.Base64; import org.mozilla.gecko.background.common.log.Logger; @@ -83,6 +85,7 @@ public class JPakeClient { public JPakeParty jParty; public final JPakeNumGenerator numGen; + public final Context context; public int pollTries; @@ -92,6 +95,7 @@ public class JPakeClient { public JPakeClient(SetupSyncActivity activity) { controllerActivity = activity; + context = activity; jpakeServer = "https://setup.services.mozilla.com/"; jpakePollInterval = 1 * 1000; // 1 second jpakeMaxTries = MAX_TRIES; diff --git a/mobile/android/base/sync/jpake/stage/DeleteChannel.java b/mobile/android/base/sync/jpake/stage/DeleteChannel.java index 280a58767468..865846bf62c6 100644 --- a/mobile/android/base/sync/jpake/stage/DeleteChannel.java +++ b/mobile/android/base/sync/jpake/stage/DeleteChannel.java @@ -30,7 +30,7 @@ public class DeleteChannel { public void execute(final JPakeClient jClient, final String reason) { final BaseResource httpResource; try { - httpResource = new BaseResource(jClient.channelUrl); + httpResource = new BaseResource(jClient.context, jClient.channelUrl); } catch (URISyntaxException e) { Logger.debug(LOG_TAG, "Encountered URISyntax exception, displaying abort anyway."); jClient.displayAbort(reason); diff --git a/mobile/android/base/sync/jpake/stage/GetChannelStage.java b/mobile/android/base/sync/jpake/stage/GetChannelStage.java index 1a30c7240aab..97292a47a034 100644 --- a/mobile/android/base/sync/jpake/stage/GetChannelStage.java +++ b/mobile/android/base/sync/jpake/stage/GetChannelStage.java @@ -8,6 +8,8 @@ import java.net.URISyntaxException; import java.security.GeneralSecurityException; +import android.content.Context; + import org.json.simple.parser.JSONParser; import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.SyncConstants; @@ -66,7 +68,7 @@ public void handleError(Exception e) { }; try { - makeChannelRequest(callbackDelegate, jClient.jpakeServer + "new_channel", jClient.clientId); + makeChannelRequest(jClient.context, callbackDelegate, jClient.jpakeServer + "new_channel", jClient.clientId); } catch (URISyntaxException e) { Logger.error(LOG_TAG, "Incorrect URI syntax.", e); jClient.abort(Constants.JPAKE_ERROR_CHANNEL); @@ -78,8 +80,8 @@ public void handleError(Exception e) { } } - private void makeChannelRequest(final GetChannelStageDelegate callbackDelegate, String getChannelUrl, final String clientId) throws URISyntaxException { - final BaseResource httpResource = new BaseResource(getChannelUrl); + private void makeChannelRequest(final Context context, final GetChannelStageDelegate callbackDelegate, String getChannelUrl, final String clientId) throws URISyntaxException { + final BaseResource httpResource = new BaseResource(context, getChannelUrl); httpResource.delegate = new BaseResourceDelegate(httpResource) { @Override public String getUserAgent() { diff --git a/mobile/android/base/sync/jpake/stage/GetRequestStage.java b/mobile/android/base/sync/jpake/stage/GetRequestStage.java index 7d00b06b7778..8893a8dcc02e 100644 --- a/mobile/android/base/sync/jpake/stage/GetRequestStage.java +++ b/mobile/android/base/sync/jpake/stage/GetRequestStage.java @@ -100,7 +100,7 @@ public void handleError(Exception e) { } private Resource createGetRequest(final GetRequestStageDelegate callbackDelegate, final JPakeClient jpakeClient) throws URISyntaxException { - BaseResource httpResource = new BaseResource(jpakeClient.channelUrl); + BaseResource httpResource = new BaseResource(jpakeClient.context, jpakeClient.channelUrl); httpResource.delegate = new BaseResourceDelegate(httpResource) { @Override public String getUserAgent() { diff --git a/mobile/android/base/sync/jpake/stage/PutRequestStage.java b/mobile/android/base/sync/jpake/stage/PutRequestStage.java index d87318f10de6..4153ad812eab 100644 --- a/mobile/android/base/sync/jpake/stage/PutRequestStage.java +++ b/mobile/android/base/sync/jpake/stage/PutRequestStage.java @@ -91,7 +91,7 @@ public void handleError(Exception e) { } private Resource createPutRequest(final PutRequestStageDelegate callbackDelegate, final JPakeClient jpakeClient) throws URISyntaxException { - BaseResource httpResource = new BaseResource(jpakeClient.channelUrl); + BaseResource httpResource = new BaseResource(jpakeClient.context, jpakeClient.channelUrl); httpResource.delegate = new BaseResourceDelegate(httpResource) { @Override public String getUserAgent() { diff --git a/mobile/android/base/sync/net/BaseResource.java b/mobile/android/base/sync/net/BaseResource.java index ea3dfc961857..f48724a6f812 100644 --- a/mobile/android/base/sync/net/BaseResource.java +++ b/mobile/android/base/sync/net/BaseResource.java @@ -4,6 +4,8 @@ package org.mozilla.gecko.sync.net; +import android.content.Context; + import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -73,6 +75,7 @@ public class BaseResource implements Resource { private static final String LOG_TAG = "BaseResource"; + protected final Context mCtx; protected final URI uri; protected BasicHttpContext context; protected DefaultHttpClient client; @@ -88,19 +91,21 @@ public class BaseResource implements Resource { protected static final CopyOnWriteArrayList> httpResponseObservers = new CopyOnWriteArrayList<>(); - public BaseResource(String uri) throws URISyntaxException { - this(uri, rewriteLocalhost); + public BaseResource(Context ctx, String uri) throws URISyntaxException { + this(ctx, uri, rewriteLocalhost); } - public BaseResource(URI uri) { - this(uri, rewriteLocalhost); + public BaseResource(Context ctx, URI uri) { + this(ctx, uri, rewriteLocalhost); } - public BaseResource(String uri, boolean rewrite) throws URISyntaxException { - this(new URI(uri), rewrite); + public BaseResource(Context ctx, String uri, boolean rewrite) throws URISyntaxException { + this(ctx, new URI(uri), rewrite); } - public BaseResource(URI uri, boolean rewrite) { + public BaseResource(Context ctx, URI uri, boolean rewrite) { + this.mCtx = ctx; + if (uri == null) { throw new IllegalArgumentException("uri must not be null"); } diff --git a/mobile/android/base/sync/net/SyncStorageCollectionRequest.java b/mobile/android/base/sync/net/SyncStorageCollectionRequest.java index 3ae672f21e7c..724ee46c4046 100644 --- a/mobile/android/base/sync/net/SyncStorageCollectionRequest.java +++ b/mobile/android/base/sync/net/SyncStorageCollectionRequest.java @@ -4,6 +4,8 @@ package org.mozilla.gecko.sync.net; +import android.content.Context; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -29,8 +31,8 @@ public class SyncStorageCollectionRequest extends SyncStorageRequest { private static final String LOG_TAG = "CollectionRequest"; - public SyncStorageCollectionRequest(URI uri) { - super(uri); + public SyncStorageCollectionRequest(Context context, URI uri) { + super(context, uri); } protected volatile boolean aborting = false; diff --git a/mobile/android/base/sync/net/SyncStorageRecordRequest.java b/mobile/android/base/sync/net/SyncStorageRecordRequest.java index 5e87ce8c8ef9..4efc61503733 100644 --- a/mobile/android/base/sync/net/SyncStorageRecordRequest.java +++ b/mobile/android/base/sync/net/SyncStorageRecordRequest.java @@ -8,6 +8,8 @@ import java.net.URI; import java.net.URISyntaxException; +import android.content.Context; + import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.mozilla.gecko.sync.CryptoRecord; @@ -42,12 +44,12 @@ public class SyncStorageRecordResourceDelegate extends SyncStorageResourceDelega } } - public SyncStorageRecordRequest(URI uri) { - super(uri); + public SyncStorageRecordRequest(Context context, URI uri) { + super(context, uri); } - public SyncStorageRecordRequest(String url) throws URISyntaxException { - this(new URI(url)); + public SyncStorageRecordRequest(Context context, String url) throws URISyntaxException { + this(context, new URI(url)); } @Override diff --git a/mobile/android/base/sync/net/SyncStorageRequest.java b/mobile/android/base/sync/net/SyncStorageRequest.java index 18f0ab9e3540..69917e1954af 100644 --- a/mobile/android/base/sync/net/SyncStorageRequest.java +++ b/mobile/android/base/sync/net/SyncStorageRequest.java @@ -4,6 +4,8 @@ package org.mozilla.gecko.sync.net; +import android.content.Context; + import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -64,15 +66,15 @@ public static String getServerErrorMessage(String body) { * @param uri * @throws URISyntaxException */ - public SyncStorageRequest(String uri) throws URISyntaxException { - this(new URI(uri)); + public SyncStorageRequest(Context ctx, String uri) throws URISyntaxException { + this(ctx, new URI(uri)); } /** * @param uri */ - public SyncStorageRequest(URI uri) { - this.resource = new BaseResource(uri); + public SyncStorageRequest(Context ctx, URI uri) { + this.resource = new BaseResource(ctx, uri); this.resourceDelegate = this.makeResourceDelegate(this); this.resource.delegate = this.resourceDelegate; } diff --git a/mobile/android/base/sync/receivers/SyncAccountDeletedService.java b/mobile/android/base/sync/receivers/SyncAccountDeletedService.java index ac5db93731b0..17160e05f952 100644 --- a/mobile/android/base/sync/receivers/SyncAccountDeletedService.java +++ b/mobile/android/base/sync/receivers/SyncAccountDeletedService.java @@ -133,14 +133,14 @@ public static void deleteClientRecord(final Context context, final String accoun } BasicAuthHeaderProvider authHeaderProvider = new BasicAuthHeaderProvider(encodedUsername, password); - SyncConfiguration configuration = new Sync11Configuration(encodedUsername, authHeaderProvider, prefs); + SyncConfiguration configuration = new Sync11Configuration(encodedUsername, authHeaderProvider, context, prefs); if (configuration.getClusterURL() == null) { Logger.warn(LOG_TAG, "Cluster URL was null; not deleting client record from server."); return; } try { - ClientRecordTerminator.deleteClientRecord(configuration, clientGUID); + ClientRecordTerminator.deleteClientRecord(context, configuration, clientGUID); } catch (Exception e) { // This should never happen, but we really don't want to die in a background thread. Logger.warn(LOG_TAG, "Got exception deleting client record from server; ignoring.", e); diff --git a/mobile/android/base/sync/repositories/Server11Repository.java b/mobile/android/base/sync/repositories/Server11Repository.java index db6d1c72a926..d2b84cfea140 100644 --- a/mobile/android/base/sync/repositories/Server11Repository.java +++ b/mobile/android/base/sync/repositories/Server11Repository.java @@ -55,7 +55,7 @@ public Server11Repository(String collection, String storageURL, AuthHeaderProvid @Override public void createSession(RepositorySessionCreationDelegate delegate, Context context) { - delegate.onSessionCreated(new Server11RepositorySession(this)); + delegate.onSessionCreated(new Server11RepositorySession(this, context)); } public URI collectionURI() { diff --git a/mobile/android/base/sync/repositories/Server11RepositorySession.java b/mobile/android/base/sync/repositories/Server11RepositorySession.java index 512337c4d435..7ce838b42920 100644 --- a/mobile/android/base/sync/repositories/Server11RepositorySession.java +++ b/mobile/android/base/sync/repositories/Server11RepositorySession.java @@ -15,6 +15,8 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicLong; +import android.content.Context; + import org.json.simple.JSONArray; import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.CryptoRecord; @@ -206,6 +208,7 @@ public KeyBundle keyBundle() { } + Context mCtx; Server11Repository serverRepository; AtomicLong uploadTimestamp = new AtomicLong(0); @@ -221,9 +224,10 @@ private void bumpUploadTimestamp(long ts) { } } - public Server11RepositorySession(Repository repository) { + public Server11RepositorySession(Repository repository, Context ctx) { super(repository); serverRepository = (Server11Repository) repository; + mCtx = ctx; } private String flattenIDs(String[] guids) { @@ -259,7 +263,7 @@ protected void fetchWithParameters(long newer, throws URISyntaxException { URI collectionURI = serverRepository.collectionURI(full, newer, limit, sort, ids); - SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(collectionURI); + SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(mCtx, collectionURI); request.delegate = delegate; // So it can clean up. @@ -374,7 +378,7 @@ protected void flush() { final ArrayList outgoing = recordsBuffer; final ArrayList outgoingGuids = recordGuidsBuffer; RepositorySessionStoreDelegate uploadDelegate = this.delegate; - storeWorkQueue.execute(new RecordUploadRunnable(uploadDelegate, outgoing, outgoingGuids, byteCount)); + storeWorkQueue.execute(new RecordUploadRunnable(uploadDelegate, outgoing, outgoingGuids, byteCount, mCtx)); recordsBuffer = new ArrayList(); recordGuidsBuffer = new ArrayList(); @@ -430,17 +434,20 @@ protected class RecordUploadRunnable implements Runnable, SyncStorageRequestDele private final ArrayList outgoing; private ArrayList outgoingGuids; private final long byteCount; + private final Context context; public RecordUploadRunnable(RepositorySessionStoreDelegate storeDelegate, ArrayList outgoing, ArrayList outgoingGuids, - long byteCount) { + long byteCount, + Context context) { Logger.debug(LOG_TAG, "Preparing record upload for " + outgoing.size() + " records (" + byteCount + " bytes)."); this.outgoing = outgoing; this.outgoingGuids = outgoingGuids; this.byteCount = byteCount; + this.context = context; } @Override @@ -598,7 +605,7 @@ public void run() { } URI u = serverRepository.collectionURI(); - SyncStorageRequest request = new SyncStorageRequest(u); + SyncStorageRequest request = new SyncStorageRequest(context, u); request.delegate = this; diff --git a/mobile/android/base/sync/setup/auth/AccountAuthenticator.java b/mobile/android/base/sync/setup/auth/AccountAuthenticator.java index 9b747a8ad0fb..48afa8da64a4 100644 --- a/mobile/android/base/sync/setup/auth/AccountAuthenticator.java +++ b/mobile/android/base/sync/setup/auth/AccountAuthenticator.java @@ -4,6 +4,8 @@ package org.mozilla.gecko.sync.setup.auth; +import android.content.Context; + import java.util.LinkedList; import java.util.Queue; @@ -18,6 +20,8 @@ public class AccountAuthenticator { private final AccountActivity activityCallback; private Queue stages; + public final Context context; + // Values for authentication. public String password; public String username; @@ -30,6 +34,7 @@ public class AccountAuthenticator { public AccountAuthenticator(AccountActivity activity) { activityCallback = activity; + context = activity; prepareStages(); } diff --git a/mobile/android/base/sync/setup/auth/AuthenticateAccountStage.java b/mobile/android/base/sync/setup/auth/AuthenticateAccountStage.java index c73388183452..12cdd2575678 100644 --- a/mobile/android/base/sync/setup/auth/AuthenticateAccountStage.java +++ b/mobile/android/base/sync/setup/auth/AuthenticateAccountStage.java @@ -12,6 +12,8 @@ import java.net.URISyntaxException; import java.security.GeneralSecurityException; +import android.content.Context; + import org.mozilla.apache.commons.codec.binary.Base64; import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.SyncConstants; @@ -78,7 +80,7 @@ public void handleError(Exception e) { String authRequestUrl = makeAuthRequestUrl(aa.authServer, aa.username); // Might contain plaintext username for old Sync accounts. Logger.pii(LOG_TAG, "Making auth request to: " + authRequestUrl); - authenticateAccount(callbackDelegate, authRequestUrl, authHeader); + authenticateAccount(aa.context, callbackDelegate, authRequestUrl, authHeader); } @@ -91,8 +93,8 @@ public void handleError(Exception e) { * @throws URISyntaxException */ // Made public for testing. - public void authenticateAccount(final AuthenticateAccountStageDelegate callbackDelegate, final String authRequestUrl, final String authHeader) throws URISyntaxException { - final BaseResource httpResource = new BaseResource(authRequestUrl); + public void authenticateAccount(final Context context, final AuthenticateAccountStageDelegate callbackDelegate, final String authRequestUrl, final String authHeader) throws URISyntaxException { + final BaseResource httpResource = new BaseResource(context, authRequestUrl); httpResource.delegate = new BaseResourceDelegate(httpResource) { @Override public String getUserAgent() { diff --git a/mobile/android/base/sync/setup/auth/EnsureUserExistenceStage.java b/mobile/android/base/sync/setup/auth/EnsureUserExistenceStage.java index 056172b56613..36142e5c4c03 100644 --- a/mobile/android/base/sync/setup/auth/EnsureUserExistenceStage.java +++ b/mobile/android/base/sync/setup/auth/EnsureUserExistenceStage.java @@ -55,7 +55,7 @@ public void handleError(Exception e) { // This is not the same as Utils.nodeWeaveURL: it's missing the trailing node/weave. String userRequestUrl = aa.nodeServer + "user/1.0/" + aa.username; - final BaseResource httpResource = new BaseResource(userRequestUrl); + final BaseResource httpResource = new BaseResource(aa.context, userRequestUrl); httpResource.delegate = new BaseResourceDelegate(httpResource) { @Override public String getUserAgent() { diff --git a/mobile/android/base/sync/setup/auth/FetchUserNodeStage.java b/mobile/android/base/sync/setup/auth/FetchUserNodeStage.java index b0a9bf99d54d..8859c2c52113 100644 --- a/mobile/android/base/sync/setup/auth/FetchUserNodeStage.java +++ b/mobile/android/base/sync/setup/auth/FetchUserNodeStage.java @@ -11,6 +11,8 @@ import java.net.URISyntaxException; import java.security.GeneralSecurityException; +import android.content.Context; + import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.SyncConstants; import org.mozilla.gecko.sync.Utils; @@ -65,7 +67,7 @@ public void handleError(Exception e) { String nodeRequestUrl = Utils.nodeWeaveURL(aa.nodeServer, aa.username); // Might contain a plaintext username in the case of old Sync accounts. Logger.pii(LOG_TAG, "NodeUrl: " + nodeRequestUrl); - final BaseResource httpResource = makeFetchNodeRequest(callbackDelegate, nodeRequestUrl); + final BaseResource httpResource = makeFetchNodeRequest(aa.context, callbackDelegate, nodeRequestUrl); // Make request on separate thread. AccountAuthenticator.runOnThread(new Runnable() { @Override @@ -75,9 +77,9 @@ public void run() { }); } - private BaseResource makeFetchNodeRequest(final FetchNodeStageDelegate callbackDelegate, String fetchNodeUrl) throws URISyntaxException { + private BaseResource makeFetchNodeRequest(final Context context, final FetchNodeStageDelegate callbackDelegate, String fetchNodeUrl) throws URISyntaxException { // Fetch node containing user. - final BaseResource httpResource = new BaseResource(fetchNodeUrl); + final BaseResource httpResource = new BaseResource(context, fetchNodeUrl); httpResource.delegate = new BaseResourceDelegate(httpResource) { @Override public String getUserAgent() { diff --git a/mobile/android/base/sync/stage/AndroidBrowserBookmarksServerSyncStage.java b/mobile/android/base/sync/stage/AndroidBrowserBookmarksServerSyncStage.java index ac4cf750f6f8..b3782bc52367 100644 --- a/mobile/android/base/sync/stage/AndroidBrowserBookmarksServerSyncStage.java +++ b/mobile/android/base/sync/stage/AndroidBrowserBookmarksServerSyncStage.java @@ -43,7 +43,7 @@ protected Repository getRemoteRepository() throws URISyntaxException { // If this is a first sync, we need to check server counts to make sure that we aren't // going to screw up. SafeConstrainedServer11Repository does this. See Bug 814331. AuthHeaderProvider authHeaderProvider = session.getAuthHeaderProvider(); - final JSONRecordFetcher countsFetcher = new JSONRecordFetcher(session.config.infoCollectionCountsURL(), authHeaderProvider); + final JSONRecordFetcher countsFetcher = new JSONRecordFetcher(session.getContext(), session.config.infoCollectionCountsURL(), authHeaderProvider); String collection = getCollection(); return new SafeConstrainedServer11Repository( collection, diff --git a/mobile/android/base/sync/stage/EnsureClusterURLStage.java b/mobile/android/base/sync/stage/EnsureClusterURLStage.java index 0111c606da3d..e6c5caea37df 100644 --- a/mobile/android/base/sync/stage/EnsureClusterURLStage.java +++ b/mobile/android/base/sync/stage/EnsureClusterURLStage.java @@ -12,6 +12,8 @@ import java.net.URISyntaxException; import java.security.GeneralSecurityException; +import android.content.Context; + import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.sync.NodeAuthenticationException; import org.mozilla.gecko.sync.NullClusterURLException; @@ -71,11 +73,12 @@ public EnsureClusterURLStage(NodeAssignmentCallback callback) { * https://server/pathname/version/username/node/weave. * @throws URISyntaxException */ - public static void fetchClusterURL(final String nodeWeaveURL, + public static void fetchClusterURL(final Context context, + final String nodeWeaveURL, final ClusterURLFetchDelegate delegate) throws URISyntaxException { Logger.info(LOG_TAG, "In fetchClusterURL: node/weave is " + nodeWeaveURL); - BaseResource resource = new BaseResource(nodeWeaveURL); + BaseResource resource = new BaseResource(context, nodeWeaveURL); resource.delegate = new BaseResourceDelegate(resource) { @Override public String getUserAgent() { @@ -251,7 +254,7 @@ public void handleError(Exception e) { @Override public void run() { try { - fetchClusterURL(callback.nodeWeaveURL(), delegate); + fetchClusterURL(session.getContext(), callback.nodeWeaveURL(), delegate); } catch (URISyntaxException e) { session.abort(e, "Invalid URL for node/weave."); } diff --git a/mobile/android/base/sync/stage/EnsureCrypto5KeysStage.java b/mobile/android/base/sync/stage/EnsureCrypto5KeysStage.java index 5031cf770fbc..92d586bd32a4 100644 --- a/mobile/android/base/sync/stage/EnsureCrypto5KeysStage.java +++ b/mobile/android/base/sync/stage/EnsureCrypto5KeysStage.java @@ -55,7 +55,7 @@ public void execute() throws NoSuchStageException { // We need an update: fetch fresh keys. Logger.debug(LOG_TAG, "Fetching fresh collection keys for this session."); try { - SyncStorageRecordRequest request = new SyncStorageRecordRequest(session.wboURI(CRYPTO_COLLECTION, "keys")); + SyncStorageRecordRequest request = new SyncStorageRecordRequest(session.getContext(), session.wboURI(CRYPTO_COLLECTION, "keys")); request.delegate = this; request.get(); } catch (URISyntaxException e) { diff --git a/mobile/android/base/sync/stage/FetchMetaGlobalStage.java b/mobile/android/base/sync/stage/FetchMetaGlobalStage.java index b4407b26bb08..ac1c8968ec68 100644 --- a/mobile/android/base/sync/stage/FetchMetaGlobalStage.java +++ b/mobile/android/base/sync/stage/FetchMetaGlobalStage.java @@ -73,7 +73,7 @@ public void execute() throws NoSuchStageException { // We need an update: fetch or upload meta/global as necessary. Logger.info(LOG_TAG, "Fetching fresh meta/global for this session."); - MetaGlobal global = new MetaGlobal(session.config.metaURL(), session.getAuthHeaderProvider()); + MetaGlobal global = new MetaGlobal(session.getContext(), session.config.metaURL(), session.getAuthHeaderProvider()); global.fetch(new StageMetaGlobalDelegate(session)); } } diff --git a/mobile/android/base/sync/stage/SafeConstrainedServer11Repository.java b/mobile/android/base/sync/stage/SafeConstrainedServer11Repository.java index 54fbf8df344f..25ae449937f8 100644 --- a/mobile/android/base/sync/stage/SafeConstrainedServer11Repository.java +++ b/mobile/android/base/sync/stage/SafeConstrainedServer11Repository.java @@ -51,7 +51,7 @@ public SafeConstrainedServer11Repository(String collection, @Override public void createSession(RepositorySessionCreationDelegate delegate, Context context) { - delegate.onSessionCreated(new CountCheckingServer11RepositorySession(this, this.getDefaultFetchLimit())); + delegate.onSessionCreated(new CountCheckingServer11RepositorySession(this, context, this.getDefaultFetchLimit())); } public class CountCheckingServer11RepositorySession extends Server11RepositorySession { @@ -63,8 +63,8 @@ public class CountCheckingServer11RepositorySession extends Server11RepositorySe */ private final long fetchLimit; - public CountCheckingServer11RepositorySession(Repository repository, long fetchLimit) { - super(repository); + public CountCheckingServer11RepositorySession(Repository repository, Context context, long fetchLimit) { + super(repository, context); this.fetchLimit = fetchLimit; } diff --git a/mobile/android/base/sync/stage/ServerSyncStage.java b/mobile/android/base/sync/stage/ServerSyncStage.java index bcb3ca7d0639..2a701eaf7049 100644 --- a/mobile/android/base/sync/stage/ServerSyncStage.java +++ b/mobile/android/base/sync/stage/ServerSyncStage.java @@ -376,7 +376,7 @@ protected void wipeServer(final AuthHeaderProvider authHeaderProvider, final Wip SyncStorageRequest request; try { - request = new SyncStorageRequest(session.config.collectionURI(getCollection())); + request = new SyncStorageRequest(session.getContext(), session.config.collectionURI(getCollection())); } catch (URISyntaxException ex) { Logger.warn(LOG_TAG, "Invalid URI in wipeServer."); wipeDelegate.onWipeFailed(ex); diff --git a/mobile/android/base/sync/stage/SyncClientsEngineStage.java b/mobile/android/base/sync/stage/SyncClientsEngineStage.java index 7a45db368a80..e7f799c5c11e 100644 --- a/mobile/android/base/sync/stage/SyncClientsEngineStage.java +++ b/mobile/android/base/sync/stage/SyncClientsEngineStage.java @@ -543,7 +543,7 @@ protected void downloadClientRecords() { try { final URI getURI = session.config.collectionURI(COLLECTION_NAME, true); - final SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(getURI); + final SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(session.getContext(), getURI); request.delegate = clientDownloadDelegate; Logger.trace(LOG_TAG, "Downloading client records."); @@ -557,7 +557,7 @@ protected void uploadClientRecords(JSONArray records) { Logger.trace(LOG_TAG, "Uploading " + records.size() + " client records."); try { final URI postURI = session.config.collectionURI(COLLECTION_NAME, false); - final SyncStorageRecordRequest request = new SyncStorageRecordRequest(postURI); + final SyncStorageRecordRequest request = new SyncStorageRecordRequest(session.getContext(), postURI); request.delegate = clientUploadDelegate; request.post(records); } catch (URISyntaxException e) { @@ -574,7 +574,7 @@ protected void uploadClientRecord(CryptoRecord record) { Logger.debug(LOG_TAG, "Uploading client record " + record.guid); try { final URI postURI = session.config.collectionURI(COLLECTION_NAME); - final SyncStorageRecordRequest request = new SyncStorageRecordRequest(postURI); + final SyncStorageRecordRequest request = new SyncStorageRecordRequest(session.getContext(), postURI); request.delegate = clientUploadDelegate; request.post(record); } catch (URISyntaxException e) { diff --git a/mobile/android/base/sync/syncadapter/SyncAdapter.java b/mobile/android/base/sync/syncadapter/SyncAdapter.java index c8262485c89f..bc532fddbabf 100644 --- a/mobile/android/base/sync/syncadapter/SyncAdapter.java +++ b/mobile/android/base/sync/syncadapter/SyncAdapter.java @@ -513,7 +513,7 @@ public void run() { final AuthHeaderProvider authHeaderProvider = new BasicAuthHeaderProvider(username, password); final SharedPreferences prefs = getContext().getSharedPreferences(prefsPath, Utils.SHARED_PREFERENCES_MODE); - final SyncConfiguration config = new Sync11Configuration(username, authHeaderProvider, prefs, keyBundle); + final SyncConfiguration config = new Sync11Configuration(username, authHeaderProvider, this.mContext, prefs, keyBundle); Collection knownStageNames = SyncConfiguration.validEngineNames(); config.stagesToSync = Utils.getStagesToSyncFromBundle(knownStageNames, extras); diff --git a/mobile/android/base/tokenserver/TokenServerClient.java b/mobile/android/base/tokenserver/TokenServerClient.java index 93ec0008d553..3e611434af4e 100644 --- a/mobile/android/base/tokenserver/TokenServerClient.java +++ b/mobile/android/base/tokenserver/TokenServerClient.java @@ -4,6 +4,8 @@ package org.mozilla.gecko.tokenserver; +import android.content.Context; + import java.io.IOException; import java.net.URI; import java.security.GeneralSecurityException; @@ -320,8 +322,9 @@ public void addHeaders(HttpRequestBase request, DefaultHttpClient client) { public void getTokenFromBrowserIDAssertion(final String assertion, final boolean conditionsAccepted, final String clientState, - final TokenServerClientDelegate delegate) { - final BaseResource resource = new BaseResource(this.uri); + final TokenServerClientDelegate delegate, + final Context context) { + final BaseResource resource = new BaseResource(context, this.uri); resource.delegate = new TokenFetchResourceDelegate(this, resource, delegate, assertion, clientState, conditionsAccepted);