Code refactor: add mAccount to EasServerConnection.

Change-Id: I19aa2d11735bff97c5577d6fc2e038d7c411c140
diff --git a/src/com/android/exchange/service/EasAccountSyncHandler.java b/src/com/android/exchange/service/EasAccountSyncHandler.java
index 2d3686e..b4fb1ea 100644
--- a/src/com/android/exchange/service/EasAccountSyncHandler.java
+++ b/src/com/android/exchange/service/EasAccountSyncHandler.java
@@ -34,8 +34,9 @@
 
     private boolean tryProvision() {
         try {
-            final EasAccountValidator validator = new EasAccountValidator(mContext, mHostAuth);
-            return validator.tryProvision(mAccount);
+            final EasAccountValidator validator =
+                    new EasAccountValidator(mContext, mAccount, mHostAuth);
+            return validator.tryProvision();
         } catch (final IOException e) {
 
         }
diff --git a/src/com/android/exchange/service/EasAccountValidator.java b/src/com/android/exchange/service/EasAccountValidator.java
index dc972df..6213b55 100644
--- a/src/com/android/exchange/service/EasAccountValidator.java
+++ b/src/com/android/exchange/service/EasAccountValidator.java
@@ -2,12 +2,14 @@
 
 import com.google.common.collect.Sets;
 
+import android.content.ContentValues;
 import android.content.Context;
 import android.os.Build;
 import android.os.Bundle;
 
 import com.android.emailcommon.mail.MessagingException;
 import com.android.emailcommon.provider.Account;
+import com.android.emailcommon.provider.EmailContent.AccountColumns;
 import com.android.emailcommon.provider.HostAuth;
 import com.android.emailcommon.provider.Policy;
 import com.android.emailcommon.service.EmailServiceProxy;
@@ -51,8 +53,7 @@
             Eas.SUPPORTED_PROTOCOL_EX2007, Eas.SUPPORTED_PROTOCOL_EX2007_SP1,
             Eas.SUPPORTED_PROTOCOL_EX2010, Eas.SUPPORTED_PROTOCOL_EX2010_SP1);
 
-    private String mProtocolVersion;
-    private Double mProtocolVersionDouble;
+    private double mProtocolVersionDouble;
     private int mRedirectCount;
 
     private static class RedirectException extends Exception {
@@ -62,60 +63,83 @@
         }
     }
 
-    public EasAccountValidator(final Context context, final HostAuth hostAuth) {
-        super(context, hostAuth);
-        mProtocolVersion = null;
-        mProtocolVersionDouble = null;
+    public EasAccountValidator(final Context context, final Account account,
+            final HostAuth hostAuth) {
+        super(context, account, hostAuth);
+        if (account.mProtocolVersion != null) {
+            mProtocolVersionDouble = Eas.getProtocolVersionDouble(account.mProtocolVersion);
+        } else {
+            mProtocolVersionDouble = 0.0d;
+        }
         mRedirectCount = 0;
     }
 
+    public EasAccountValidator(final Context context, final HostAuth hostAuth) {
+        this(context, new Account(), hostAuth);
+        mAccount.mEmailAddress = mHostAuth.mLogin;
+    }
+
     /**
-     * Get the protocol version to use, based on the server's supported versions.
+     * Get the protocol version to use, based on the server's supported versions, and update our
+     * account with this information.
      * @param versionHeader The {@link Header} for the server's supported versions.
+     * @return Whether we found a suitable protocol version.
      */
-    private void setProtocolVersion(final Header versionHeader) {
+    private boolean setProtocolVersion(final Header versionHeader) {
         // The string is a comma separated list of EAS versions in ascending order
         // e.g. 1.0,2.0,2.5,12.0,12.1,14.0,14.1
         final String supportedVersions = versionHeader.getValue();
         LogUtils.i(TAG, "Server supports versions: %s", supportedVersions);
         final String[] supportedVersionsArray = supportedVersions.split(",");
-        mProtocolVersion = null;
         // Find the most recent version we support
+        String newProtocolVersion = null;
         for (final String version: supportedVersionsArray) {
             if (SUPPORTED_PROTOCOL_VERSIONS.contains(version)) {
-                mProtocolVersion = version;
+                newProtocolVersion = version;
             }
         }
-        if (mProtocolVersion == null) {
+        if (newProtocolVersion == null) {
             LogUtils.w(TAG, "No supported EAS versions: %s", supportedVersions);
+            // TODO: if mAccount.isSaved(), we should delete the account.
+            mProtocolVersionDouble = 0.0d;
+            return false;
         } else {
-            mProtocolVersionDouble = Eas.getProtocolVersionDouble(mProtocolVersion);
+            mProtocolVersionDouble = Eas.getProtocolVersionDouble(newProtocolVersion);
         }
 
-        /*
-        // TODO: This code may be relevant when I unify EasAccountSyncHandler with this class.
-        Account account = service.mAccount;
-        if (account != null) {
-            account.mProtocolVersion = ourVersion;
-            // Fixup search flags, if they're not set
-            if (service.mProtocolVersionDouble >= 12.0 &&
-                    (account.mFlags & Account.FLAGS_SUPPORTS_SEARCH) == 0) {
-                if (account.isSaved()) {
-                    ContentValues cv = new ContentValues();
-                    account.mFlags |=
-                        Account.FLAGS_SUPPORTS_GLOBAL_SEARCH + Account.FLAGS_SUPPORTS_SEARCH;
-                    cv.put(AccountColumns.FLAGS, account.mFlags);
-                    account.update(service.mContext, cv);
-                }
-            }
+        // Update our account with the new protocol version.
+        final boolean protocolChanged = !newProtocolVersion.equals(mAccount.mProtocolVersion);
+        mAccount.mProtocolVersion = newProtocolVersion;
+
+        // Fixup search flags, if they're not set.
+        final boolean flagsChanged;
+        if (mProtocolVersionDouble >= 12.0) {
+            int oldFlags = mAccount.mFlags;
+            mAccount.mFlags |= Account.FLAGS_SUPPORTS_GLOBAL_SEARCH + Account.FLAGS_SUPPORTS_SEARCH;
+            flagsChanged = (oldFlags != mAccount.mFlags);
+        } else {
+            flagsChanged = false;
         }
-        */
+
+        // Write account back to DB if needed.
+        if ((protocolChanged || flagsChanged) && mAccount.isSaved()) {
+            final ContentValues cv = new ContentValues();
+            if (protocolChanged) {
+                cv.put(AccountColumns.PROTOCOL_VERSION, mAccount.mProtocolVersion);
+            }
+            if (flagsChanged) {
+                cv.put(AccountColumns.FLAGS, mAccount.mFlags);
+            }
+            mAccount.update(mContext, cv);
+        }
+        return true;
     }
 
     /**
-     * Make an OPTIONS request to determine the protocol version to use.
-     * @return A status code for getting the protocol version. If NO_ERROR, then mProtocolVersion
-     *     will be set correctly.
+     * Make an OPTIONS request to determine the protocol version to use, and update our account to
+     * use the most recent protocol that both we and the server understand.
+     * @return A status code for getting the protocol version. If NO_ERROR, then mAccount will be
+     *     updated to the best version we mutually understand.
      */
     private int doHttpOptions() throws IOException, RedirectException {
         final EasResponse resp = sendHttpClientOptions();
@@ -127,13 +151,14 @@
                 // No exception means successful validation
                 final Header commands = resp.getHeader("MS-ASProtocolCommands");
                 final Header versions = resp.getHeader("ms-asprotocolversions");
+                final boolean hasProtocolVersion;
                 if (commands == null || versions == null) {
                     LogUtils.e(TAG, "OPTIONS response without commands or versions");
-                    mProtocolVersion = null;
+                    hasProtocolVersion = false;
                 } else {
-                    setProtocolVersion(versions);
+                    hasProtocolVersion = setProtocolVersion(versions);
                 }
-                if (mProtocolVersion == null) {
+                if (!hasProtocolVersion) {
                     return MessagingException.PROTOCOL_VERSION_UNSUPPORTED;
                 }
                 return MessagingException.NO_ERROR;
@@ -160,14 +185,12 @@
     /**
      * Send a FolderSync request to the server to verify the response -- we aren't actually
      * syncing the account at this point, just want to make sure we get valid output.
-     * @param account The account we're verifying.
      * @return A status code indicating the result of this check.
      * @throws IOException
      * @throws CommandStatusException
      * @throws RedirectException
      */
-    private int doFolderSync(final Account account)
-            throws IOException, CommandStatusException, RedirectException {
+    private int doFolderSync() throws IOException, CommandStatusException, RedirectException {
         LogUtils.i(TAG, "Try FolderSync for %s, %s, ssl = %s", mHostAuth.mAddress, mHostAuth.mLogin,
                 mHostAuth.shouldUseSsl() ? "1" : "0");
 
@@ -176,7 +199,7 @@
         final Serializer s = new Serializer();
         s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text(syncKey)
             .end().end().done();
-        final EasResponse resp = sendHttpClientPost(account, "FolderSync", s.toByteArray());
+        final EasResponse resp = sendHttpClientPost("FolderSync", s.toByteArray());
         final int resultCode;
         try {
             final int code = resp.getStatus();
@@ -189,7 +212,7 @@
                     // seeing if a CommandStatusException is thrown (indicating a
                     // provisioning failure)
                     new FolderSyncParser(mContext, mContext.getContentResolver(),
-                            resp.getInputStream(), account, true).parse();
+                            resp.getInputStream(), mAccount, true).parse();
                 }
                 resultCode = MessagingException.NO_ERROR;
             } else if (code == HttpStatus.SC_FORBIDDEN) {
@@ -217,7 +240,12 @@
         return resultCode;
     }
 
-    private boolean sendSettings(final Account account) throws IOException {
+    /**
+     * Send a Settings request to the server and process the response.
+     * @return Whether the request succeeded.
+     * @throws IOException
+     */
+    private boolean sendSettings() throws IOException {
         final Serializer s = new Serializer();
         s.start(Tags.SETTINGS_SETTINGS);
         s.start(Tags.SETTINGS_DEVICE_INFORMATION).start(Tags.SETTINGS_SET);
@@ -225,7 +253,7 @@
         s.data(Tags.SETTINGS_OS, "Android " + Build.VERSION.RELEASE);
         s.data(Tags.SETTINGS_USER_AGENT, USER_AGENT);
         s.end().end().end().done(); // SETTINGS_SET, SETTINGS_DEVICE_INFORMATION, SETTINGS_SETTINGS
-        final EasResponse resp = sendHttpClientPost(account, "Settings", s.toByteArray());
+        final EasResponse resp = sendHttpClientPost("Settings", s.toByteArray());
         try {
             if (resp.getStatus() == HttpStatus.SC_OK) {
                 return new SettingsParser(resp.getInputStream()).parse();
@@ -237,29 +265,29 @@
         return false;
     }
 
-    private String getPolicyType(Double protocolVersion) {
-        return (protocolVersion >=
+    private String getPolicyType() {
+        return (mProtocolVersionDouble >=
             Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) ? EAS_12_POLICY_TYPE : EAS_2_POLICY_TYPE;
     }
 
-    private void acknowledgeRemoteWipe(final Account account, final String tempKey)
+    private void acknowledgeRemoteWipe(final String tempKey)
             throws IOException {
-        acknowledgeProvisionImpl(account, tempKey, PROVISION_STATUS_OK, true);
+        acknowledgeProvisionImpl(tempKey, PROVISION_STATUS_OK, true);
     }
 
-    private String acknowledgeProvision(final Account account, final String tempKey,
-            final String result) throws IOException {
-        return acknowledgeProvisionImpl(account, tempKey, result, false);
+    private String acknowledgeProvision(final String tempKey, final String result)
+            throws IOException {
+        return acknowledgeProvisionImpl(tempKey, result, false);
     }
 
-    private String acknowledgeProvisionImpl(final Account account, final String tempKey,
-            final String status, final boolean remoteWipe) throws IOException {
+    private String acknowledgeProvisionImpl(final String tempKey, final String status,
+            final boolean remoteWipe) throws IOException {
         final Serializer s = new Serializer();
         s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES);
         s.start(Tags.PROVISION_POLICY);
 
         // Use the proper policy type, depending on EAS version
-        s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType(mProtocolVersionDouble));
+        s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType());
 
         s.data(Tags.PROVISION_POLICY_KEY, tempKey);
         s.data(Tags.PROVISION_STATUS, status);
@@ -270,7 +298,7 @@
             s.end();
         }
         s.end().done(); // PROVISION_PROVISION
-        EasResponse resp = sendHttpClientPost(account, "Provision", s.toByteArray());
+        EasResponse resp = sendHttpClientPost("Provision", s.toByteArray());
         try {
             if (resp.getStatus() == HttpStatus.SC_OK) {
                 final ProvisionParser pp = new ProvisionParser(mContext, resp.getInputStream());
@@ -292,7 +320,7 @@
         return null;
     }
 
-    public ProvisionParser canProvision(final Account account) throws IOException {
+    public ProvisionParser canProvision() throws IOException {
         final Serializer s = new Serializer();
         s.start(Tags.PROVISION_PROVISION);
         if (mProtocolVersionDouble >= Eas.SUPPORTED_PROTOCOL_EX2010_SP1_DOUBLE) {
@@ -310,9 +338,9 @@
         }
         s.start(Tags.PROVISION_POLICIES);
         s.start(Tags.PROVISION_POLICY);
-        s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType(mProtocolVersionDouble));
+        s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType());
         s.end().end().end().done(); // PROVISION_POLICY, PROVISION_POLICIES, PROVISION_PROVISION
-        final EasResponse resp = sendHttpClientPost(account, "Provision", s.toByteArray());
+        final EasResponse resp = sendHttpClientPost("Provision", s.toByteArray());
         try {
             int code = resp.getStatus();
             if (code == HttpStatus.SC_OK) {
@@ -324,9 +352,8 @@
                             mProtocolVersionDouble == Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE) {
                         // In EAS 14.0, we need the final security key in order to use the settings
                         // command
-                        final String policyKey =
-                                acknowledgeProvision(account, pp.getSecuritySyncKey(),
-                                        PROVISION_STATUS_OK);
+                        final String policyKey = acknowledgeProvision(pp.getSecuritySyncKey(),
+                                PROVISION_STATUS_OK);
                         if (policyKey != null) {
                             pp.setSecuritySyncKey(policyKey);
                         }
@@ -335,7 +362,7 @@
                         // accommodate the required policies).  The server will agree to this if the
                         // "allow non-provisionable devices" setting is enabled on the server
                         LogUtils.i(TAG, "PolicySet is NOT fully supportable");
-                        if (acknowledgeProvision(account, pp.getSecuritySyncKey(),
+                        if (acknowledgeProvision(pp.getSecuritySyncKey(),
                                 PROVISION_STATUS_PARTIAL) != null) {
                             // The server's ok with our inability to support policies, so we'll
                             // clear them
@@ -354,36 +381,34 @@
     }
 
 
-    public boolean tryProvision(final Account account) throws IOException {
-        mProtocolVersion = account.mProtocolVersion;
-        mProtocolVersionDouble = Eas.getProtocolVersionDouble(mProtocolVersion);
+    public boolean tryProvision() throws IOException {
         // First, see if provisioning is even possible, i.e. do we support the policies required
         // by the server
-        ProvisionParser pp = canProvision(account);
+        ProvisionParser pp = canProvision();
         if (pp == null) return false;
         // Get the policies from ProvisionParser
         Policy policy = pp.getPolicy();
         Policy oldPolicy = null;
         // Grab the old policy (if any)
-        if (account.mPolicyKey > 0) {
-            oldPolicy = Policy.restorePolicyWithId(mContext, account.mPolicyKey);
+        if (mAccount.mPolicyKey > 0) {
+            oldPolicy = Policy.restorePolicyWithId(mContext, mAccount.mPolicyKey);
         }
         // Update the account with a null policyKey (the key we've gotten is
         // temporary and cannot be used for syncing)
-        PolicyServiceProxy.setAccountPolicy(mContext, account.mId, policy, null);
+        PolicyServiceProxy.setAccountPolicy(mContext, mAccount.mId, policy, null);
         // Make sure mAccount is current (with latest policy key)
-        account.refresh(mContext);
+        mAccount.refresh(mContext);
         if (pp.getRemoteWipe()) {
             // We've gotten a remote wipe command
             LogUtils.i(TAG, "!!! Remote wipe request received");
             // Start by setting the account to security hold
-            PolicyServiceProxy.setAccountHoldFlag(mContext, account, true);
+            PolicyServiceProxy.setAccountHoldFlag(mContext, mAccount, true);
 
             // First, we've got to acknowledge it, but wrap the wipe in try/catch so that
             // we wipe the device regardless of any errors in acknowledgment
             try {
                 LogUtils.i(TAG, "!!! Acknowledging remote wipe to server");
-                acknowledgeRemoteWipe(account, pp.getSecuritySyncKey());
+                acknowledgeRemoteWipe(pp.getSecuritySyncKey());
             } catch (Exception e) {
                 // Because remote wipe is such a high priority task, we don't want to
                 // circumvent it if there's an exception in acknowledgment
@@ -400,7 +425,7 @@
             if (mProtocolVersionDouble == Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE) {
                 securitySyncKey = pp.getSecuritySyncKey();
             } else {
-                securitySyncKey = acknowledgeProvision(account, pp.getSecuritySyncKey(),
+                securitySyncKey = acknowledgeProvision(pp.getSecuritySyncKey(),
                         PROVISION_STATUS_OK);
             }
             if (securitySyncKey != null) {
@@ -408,11 +433,11 @@
                 if (oldPolicy != null) {
                     if ((oldPolicy.mDontAllowAttachments != policy.mDontAllowAttachments) ||
                             (oldPolicy.mMaxAttachmentSize != policy.mMaxAttachmentSize)) {
-                        Policy.setAttachmentFlagsForNewPolicy(mContext, account, policy);
+                        Policy.setAttachmentFlagsForNewPolicy(mContext, mAccount, policy);
                     }
                 }
                 // Write the final policy key to the Account and say we've been successful
-                PolicyServiceProxy.setAccountPolicy(mContext, account.mId, policy, securitySyncKey);
+                PolicyServiceProxy.setAccountPolicy(mContext, mAccount.mId, policy, securitySyncKey);
                 return true;
             }
         }
@@ -439,8 +464,7 @@
         }
 
         int resultCode;
-        final Account account = new Account();
-        account.mEmailAddress = mHostAuth.mLogin;
+
         // Need a nested try here because the provisioning exception handler can throw IOException.
         try {
             try {
@@ -449,23 +473,22 @@
                     bundle.putInt(EmailServiceProxy.VALIDATE_BUNDLE_RESULT_CODE, optionsResult);
                     return bundle;
                 }
-                account.mProtocolVersion = mProtocolVersion;
                 bundle.putString(EmailServiceProxy.VALIDATE_BUNDLE_PROTOCOL_VERSION,
-                        mProtocolVersion);
-                resultCode = doFolderSync(account);
+                        mAccount.mProtocolVersion);
+                resultCode = doFolderSync();
             } catch (final CommandStatusException e) {
                 final int status = e.mStatus;
                 if (CommandStatus.isNeedsProvisioning(status)) {
                     // Get the policies and see if we are able to support them
-                    final ProvisionParser pp = canProvision(account);
+                    final ProvisionParser pp = canProvision();
                     if (pp != null && pp.hasSupportablePolicySet()) {
                         // Set the proper result code and save the PolicySet in our Bundle
                         resultCode = MessagingException.SECURITY_POLICIES_REQUIRED;
                         bundle.putParcelable(EmailServiceProxy.VALIDATE_BUNDLE_POLICY_SET,
                                 pp.getPolicy());
                         if (mProtocolVersionDouble == Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE) {
-                            account.mSecuritySyncKey = pp.getSecuritySyncKey();
-                            if (!sendSettings(account)) {
+                            mAccount.mSecuritySyncKey = pp.getSecuritySyncKey();
+                            if (!sendSettings()) {
                                 LogUtils.i(TAG, "Denied access: %s",
                                         CommandStatus.toString(status));
                                 resultCode = MessagingException.ACCESS_DENIED;
diff --git a/src/com/android/exchange/service/EasPingSyncHandler.java b/src/com/android/exchange/service/EasPingSyncHandler.java
index a63fae8..1439cbe 100644
--- a/src/com/android/exchange/service/EasPingSyncHandler.java
+++ b/src/com/android/exchange/service/EasPingSyncHandler.java
@@ -33,7 +33,6 @@
  */
 public class EasPingSyncHandler extends EasServerConnection {
     private final ContentResolver mContentResolver;
-    private final Account mAccount;
     private final PingTask mPingTask;
 
     private class PingTask extends AsyncTask<Void, Void, Void> {
@@ -86,8 +85,8 @@
                         // in handleOneMailbox when the Serializer is first created.
                         // If either side changes, the other must be kept in sync.
                         s.end().end().done();
-                        final EasResponse resp = sendHttpClientPost(mAccount, "Ping",
-                                s.toByteArray(), PING_HEARTBEAT);
+                        final EasResponse resp = sendHttpClientPost("Ping", s.toByteArray(),
+                                PING_HEARTBEAT);
                         try {
                             continuePing = handleResponse(resp, amAccount);
                         } finally {
@@ -288,9 +287,8 @@
 
     public EasPingSyncHandler(final Context context, final Account account,
             final EmailSyncAdapterService.SyncHandlerSychronizer syncHandlerMap) {
-        super(context, HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
+        super(context, account, HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
         mContentResolver = context.getContentResolver();
-        mAccount = account;
         mPingTask = new PingTask(syncHandlerMap);
         mPingTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
     }
diff --git a/src/com/android/exchange/service/EasServerConnection.java b/src/com/android/exchange/service/EasServerConnection.java
index 78dc9ba..b96e3e3 100644
--- a/src/com/android/exchange/service/EasServerConnection.java
+++ b/src/com/android/exchange/service/EasServerConnection.java
@@ -60,7 +60,10 @@
     };
 
     protected final Context mContext;
+    // TODO: Make this private if possible. Subclasses must be careful about altering the HostAuth
+    // to not screw up any connection caching (use redirectHostAuth).
     protected final HostAuth mHostAuth;
+    protected final Account mAccount;
 
     // Bookkeeping for interrupting a POST. This is primarily for use by Ping (there's currently
     // no mechanism for stopping a sync).
@@ -115,9 +118,11 @@
     }
     private static final ConnectionManagerCache sConnectionManagers = new ConnectionManagerCache();
 
-    protected EasServerConnection(final Context context, final HostAuth hostAuth) {
+    protected EasServerConnection(final Context context, final Account account,
+            final HostAuth hostAuth) {
         mContext = context;
         mHostAuth = hostAuth;
+        mAccount = account;
     }
 
     protected EmailClientConnectionManager getClientConnectionManager() {
@@ -175,38 +180,35 @@
 
     /**
      * Get the protocol version for an account, or a default if we can't determine it.
-     * @param account The account whose protocol version we want to get.
      * @return The protocol version for account, as a String.
      */
-    protected String getProtocolVersion(final Account account) {
-        if (account != null && account.mProtocolVersion != null) {
-            return account.mProtocolVersion;
+    protected String getProtocolVersion() {
+        if (mAccount.mProtocolVersion != null) {
+            return mAccount.mProtocolVersion;
         }
         return Eas.DEFAULT_PROTOCOL_VERSION;
     }
 
     /**
      * Set standard HTTP headers, using a policy key if required
-     * @param account The Account for which we are communicating.
      * @param method the method we are going to send
      * @param usePolicyKey whether or not a policy key should be sent in the headers
      */
-    private void setHeaders(final Account account, final HttpRequestBase method,
-            final boolean usePolicyKey) {
+    private void setHeaders(final HttpRequestBase method, final boolean usePolicyKey) {
         method.setHeader("Authorization", makeAuthString());
-        method.setHeader("MS-ASProtocolVersion", getProtocolVersion(account));
+        method.setHeader("MS-ASProtocolVersion", getProtocolVersion());
         method.setHeader("User-Agent", USER_AGENT);
         method.setHeader("Accept-Encoding", "gzip");
         if (usePolicyKey) {
             // If there's an account in existence, use its key; otherwise (we're creating the
             // account), send "0".  The server will respond with code 449 if there are policies
             // to be enforced
-            String key = "0";
-            if (account != null) {
-                final String accountKey = account.mSecuritySyncKey;
-                if (!TextUtils.isEmpty(accountKey)) {
-                    key = accountKey;
-                }
+            final String key;
+            final String accountKey = mAccount.mSecuritySyncKey;
+            if (!TextUtils.isEmpty(accountKey)) {
+                key = accountKey;
+            } else {
+                key = "0";
             }
             method.setHeader("X-MS-PolicyKey", key);
         }
@@ -229,15 +231,14 @@
 
     /**
      * Send a POST request to the server.
-     * @param account The {@link Account} for which we're sending the POST.
      * @param cmd The command we're sending to the server.
      * @param entity The {@link HttpEntity} containing the payload of the message.
      * @param timeout The timeout for this POST.
      * @return The response from the Exchange server.
      * @throws IOException
      */
-    protected EasResponse sendHttpClientPost(final Account account,
-            String cmd, final HttpEntity entity, final long timeout) throws IOException {
+    protected EasResponse sendHttpClientPost(String cmd, final HttpEntity entity,
+            final long timeout) throws IOException {
         final EmailClientConnectionManager connectionManager = getClientConnectionManager();
         final HttpClient client = getHttpClient(connectionManager, timeout);
         final boolean isPingCommand = cmd.equals("Ping");
@@ -259,14 +260,14 @@
         // Send the proper Content-Type header; it's always wbxml except for messages when
         // the EAS protocol version is < 14.0
         // If entity is null (e.g. for attachments), don't set this header
-        final String protocolVersion = getProtocolVersion(account);
+        final String protocolVersion = getProtocolVersion();
         final Double protocolVersionDouble = Eas.getProtocolVersionDouble(protocolVersion);
         if (msg && (protocolVersionDouble < Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE)) {
             method.setHeader("Content-Type", "message/rfc822");
         } else if (entity != null) {
             method.setHeader("Content-Type", "application/vnd.ms-sync.wbxml");
         }
-        setHeaders(account, method, !isPingCommand);
+        setHeaders(method, !isPingCommand);
         // NOTE
         // The next lines are added at the insistence of $VENDOR, who is seeing inappropriate
         // network activity related to the Ping command on some networks with some servers.
@@ -296,14 +297,14 @@
         }
     }
 
-    protected EasResponse sendHttpClientPost(final Account account, final String cmd,
-            final byte[] bytes, final long timeout) throws IOException {
-        return sendHttpClientPost(account, cmd, new ByteArrayEntity(bytes), timeout);
+    protected EasResponse sendHttpClientPost(final String cmd, final byte[] bytes,
+            final long timeout) throws IOException {
+        return sendHttpClientPost(cmd, new ByteArrayEntity(bytes), timeout);
     }
 
-    protected EasResponse sendHttpClientPost(final Account account, final String cmd,
-            final byte[] bytes) throws IOException {
-        return sendHttpClientPost(account, cmd, bytes, COMMAND_TIMEOUT);
+    protected EasResponse sendHttpClientPost(final String cmd, final byte[] bytes)
+            throws IOException {
+        return sendHttpClientPost(cmd, bytes, COMMAND_TIMEOUT);
     }
 
     /**
diff --git a/src/com/android/exchange/service/EasSyncHandler.java b/src/com/android/exchange/service/EasSyncHandler.java
index 4496c1d..30d9785 100644
--- a/src/com/android/exchange/service/EasSyncHandler.java
+++ b/src/com/android/exchange/service/EasSyncHandler.java
@@ -9,11 +9,6 @@
 import com.android.emailcommon.provider.HostAuth;
 import com.android.emailcommon.provider.Mailbox;
 import com.android.emailcommon.service.EmailServiceStatus;
-import com.android.exchange.EasResponse;
-
-import org.apache.http.HttpEntity;
-
-import java.io.IOException;
 
 /**
  * Base class for performing a single sync action. It holds the state needed for all sync actions
@@ -23,7 +18,6 @@
  */
 public abstract class EasSyncHandler extends EasServerConnection {
     protected final ContentResolver mContentResolver;
-    protected final Account mAccount;
     protected final Mailbox mMailbox;
     protected final Bundle mSyncExtras;
     protected final SyncResult mSyncResult;
@@ -49,9 +43,8 @@
     protected EasSyncHandler(final Context context, final ContentResolver contentResolver,
             final Account account, final Mailbox mailbox, final Bundle syncExtras,
             final SyncResult syncResult) {
-        super(context, HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
+        super(context, account, HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
         mContentResolver = contentResolver;
-        mAccount = account;
         mMailbox = mailbox;
         mSyncExtras = syncExtras;
         mSyncResult = syncResult;
@@ -101,22 +94,6 @@
      */
     public abstract SyncStatus performSync();
 
-    // Convenience versions of EasServerConnection functions, using our member variables.
-
-    protected String getProtocolVersion() {
-        return getProtocolVersion(mAccount);
-    }
-
-    protected EasResponse sendHttpClientPost(final String cmd, final HttpEntity entity,
-            final long timeout) throws IOException {
-        return sendHttpClientPost(mAccount, cmd, entity, timeout);
-    }
-
-    protected EasResponse sendHttpClientPost(final String cmd, final byte[] bytes)
-            throws IOException {
-        return sendHttpClientPost(mAccount, cmd, bytes, COMMAND_TIMEOUT);
-    }
-
     // Communication with the application.
 
     // TODO: Consider bringing the EmailServiceStatus functions here?