Example usage for android.accounts NetworkErrorException NetworkErrorException

List of usage examples for android.accounts NetworkErrorException NetworkErrorException

Introduction

In this page you can find the example usage for android.accounts NetworkErrorException NetworkErrorException.

Prototype

public NetworkErrorException(Throwable cause) 

Source Link

Usage

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side contacts. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 * /*from  www.  j  a  v  a  2 s  . c o  m*/
 * @param account
 *            The account being synced
 * @param authtoken
 *            The authtoken stored in the AccountManager for this account
 * @param serverSyncState
 *            A token returned from the server on the last sync
 * @param dirtyContacts
 *            A list of the contacts to send to the server
 * @param newIdMap
 *            Map of RawId to ServerId
 * @param explizitPhotoSave
 * @return A list of contacts that we need to update locally. Null if
 *         processing of server-results failed.
 * @throws ParserConfigurationException
 * @throws TransformerException
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 *             when Authentication was canceled from user
 * @throws SAXException
 * @throws ServerException
 * @throws NetworkErrorException
 * @throws HeaderParseException
 * @throws HeaderCreateException
 */
public static SyncResponse syncContacts(Account account, String authtoken, SyncAnchor serverSyncState,
        List<RawContact> dirtyContacts, List<ContactGroup> dirtyGroups, SecretKey key,
        AccountManager accountManager, Context context, SyncResult syncResult, String pwdSaltHexStr,
        Map<Long, String> newIdMap, Restrictions restr, boolean explizitPhotoSave)
        throws AuthenticationException, OperationCanceledException, AuthenticatorException, ServerException,
        NetworkErrorException, HeaderParseException, HeaderCreateException {
    String clientId = getClientId(accountManager, account);

    SyncPrepErrorStatistic prepError = new SyncPrepErrorStatistic();
    byte[] totBuffer = RequestGenerator.prepareServerRequest(serverSyncState, dirtyContacts, dirtyGroups, key,
            SystemHelper.getPkgVersion(context), clientId, pwdSaltHexStr, newIdMap, prepError, restr,
            explizitPhotoSave);
    syncResult.stats.numSkippedEntries += prepError.getIgnoredRows();
    String currAuthtoken = authtoken;

    SyncResponse syncResponse = null;
    boolean retry;
    int retrycount = 0;
    do {
        retry = false;

        HttpEntity entity = new ByteArrayEntity(totBuffer);

        // Send the updated friends data to the server
        final HttpPost post = new HttpPost(SYNC_URI);
        post.setHeader("Content-Encoding", "application/octect-stream");
        post.setEntity(entity);

        HttpEntity respEntity = null;

        try {
            final HttpResponse resp = getHttpClient(context).execute(post,
                    createHttpContext(account.name, currAuthtoken));

            respEntity = resp.getEntity();
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final byte[] response = EntityUtils.toByteArray(respEntity);

                syncResponse = processServerResponse(account, key, accountManager, clientId, response,
                        syncResult);
                if (Log.isLoggable(TAG, Log.INFO)) {
                    Log.i(TAG, "Response-Length: " + response.length);
                }
            } else {
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    currAuthtoken = retryAuthentification(retrycount, accountManager, currAuthtoken,
                            account.name, resp);
                    retry = true;
                } else {
                    throw new ServerException(
                            "Server error in sending dirty contacts: " + resp.getStatusLine());
                }
            }
        } catch (IOException ex) {
            throw new NetworkErrorException(ex);
        } finally {
            consumeContent(respEntity);
        }
        retrycount++;
    } while (retry);

    return syncResponse;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * // www .  ja  v a2s . c om
 * @param authtoken
 * @return KeySalt and KeyCheck. null if server was returning nothing
 * @throws IOException
 * @throws AuthenticationException
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 * @throws ServerException
 * @throws NetworkErrorException
 */
public static byte[] getKeySalt(Context context, String accountName, String authtoken)
        throws AuthenticationException, OperationCanceledException, ServerException, NetworkErrorException {

    boolean retry;
    int retryCount = 0;
    String currAuthtoken = authtoken;
    byte[] pwdSalt = null;
    do {
        retry = false;
        final HttpGet get = new HttpGet(PWDSALT_URI);
        HttpEntity entity = null;
        try {
            final HttpResponse resp = getHttpClient(context).execute(get,
                    createHttpContext(accountName, currAuthtoken));
            entity = resp.getEntity();
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                byte[] respBytes = EntityUtils.toByteArray(entity);
                if (BuildConfig.DEBUG) {
                    Log.v(TAG, "Get Response-Lenght:" + (respBytes != null ? respBytes.length : "null"));
                }
                pwdSalt = respBytes == null || respBytes.length == 0 ? null : respBytes;
            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                AccountManager accountManager = AccountManager.get(context);
                currAuthtoken = retryAuthentification(retryCount, accountManager, currAuthtoken, accountName,
                        resp);
                retry = true;
            } else {
                throw new ServerException("Server error in query getPwdSalt: " + resp.getStatusLine());
            }
        } catch (IOException ex) {
            throw new NetworkErrorException(ex);
        } finally {
            consumeContent(entity);
        }
        retryCount++;
    } while (retry);
    return pwdSalt;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * //from  w w w. j  a v a  2 s  . co m
 * @param authtoken
 * @return null if server returned no restrictions.
 * @throws IOException
 * @throws AuthenticationException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 * @throws NetworkErrorException
 * @throws ServerException
 */
public static Restrictions getRestrictions(Context context, Account account, String authtoken,
        AccountManager accountManager) throws AuthenticationException, OperationCanceledException,
        AuthenticatorException, NetworkErrorException, ServerException {
    String currAuthtoken = authtoken;
    HttpEntity entity = null;
    Restrictions restr = null;
    boolean retry;
    int retryCount = 0;
    do {
        retry = false;

        final HttpGet get = new HttpGet(RESTRICTIONS_URI);
        try {
            final HttpResponse resp = getHttpClient(context).execute(get,
                    createHttpContext(account.name, currAuthtoken));

            entity = resp.getEntity();
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                byte[] respBytes = EntityUtils.toByteArray(entity);
                if (BuildConfig.DEBUG) {
                    Log.v(TAG, "Get Response-Lenght:" + (respBytes != null ? respBytes.length : "null"));
                }
                if (respBytes != null && respBytes.length > 0) {
                    restr = RequestGenerator.parseRestr(new ByteArrayInputStream(respBytes));
                }
            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                currAuthtoken = retryAuthentification(retryCount, accountManager, currAuthtoken, account.name,
                        resp);
                retry = true;
            } else {
                throw new ServerException("Server error in query getRestrictions: " + resp.getStatusLine());
            }
        } catch (IOException e) {
            throw new NetworkErrorException(e);
        } finally {
            consumeContent(entity);
        }
        retryCount++;
    } while (retry);
    return restr;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * Get current Prices for a Currency/*from  w w  w  . j  av  a2s  .  co  m*/
 * 
 * @param authtoken
 *            can be null
 * @return null if server returned no prices.
 * @throws IOException
 * @throws AuthenticationException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 * @throws ServerException
 * @throws NetworkErrorException
 */
public static List<Price> getPrices(Context context, Account account, String authtoken,
        AccountManager accountManager, String currency)
        throws OperationCanceledException, AuthenticationException, NetworkErrorException, ServerException {
    String currAuthtoken = authtoken;
    HttpEntity entity = null;
    List<Price> prices = null;
    boolean retry;
    int retryCount = 0;
    do {
        retry = false;

        final HttpGet get = new HttpGet(PRICE_URI + currency);
        LogHelper.logD(TAG, "getPrices with URI: {}", get.getURI());
        try {

            final HttpResponse resp = getHttpClient(context).execute(get,
                    createHttpContext(account.name, currAuthtoken));

            entity = resp.getEntity();
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                ObjectMapper mapper = new ObjectMapper();
                Class<?> clz = Price.class;
                JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, clz);
                byte[] respBytes = EntityUtils.toByteArray(entity);
                prices = mapper.readValue(respBytes, type);

            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                currAuthtoken = retryAuthentification(retryCount, accountManager, currAuthtoken, account.name,
                        resp);
                retry = true;
            } else {
                throw new ServerException("Server error in query getPrices: " + resp.getStatusLine());
            }
        } catch (IOException e) {
            throw new NetworkErrorException(e);
        } finally {
            consumeContent(entity);
        }
        retryCount++;
    } while (retry);
    return prices;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

public static boolean savePwdSalt(Context context, String accountName, String authtoken, String newSalt,
        String oldSalt, boolean clearData, String pwdCheck)
        throws AuthenticationException, ServerException, NetworkErrorException {
    final HttpPost post = new HttpPost(PWDSALT_URI);
    List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();
    values.add(new BasicNameValuePair("newSalt", newSalt == null ? "" : newSalt));
    values.add(new BasicNameValuePair("oldSalt", oldSalt == null ? "" : oldSalt));
    values.add(new BasicNameValuePair("clearData", String.valueOf(clearData)));
    values.add(new BasicNameValuePair("pwdCheck", pwdCheck == null ? "" : pwdCheck));

    HttpResponse resp = null;//from  w  w w.  j a  va2  s  .  c o  m
    final String respStr;
    HttpEntity entity = null;
    try {
        HttpEntity postEntity = new UrlEncodedFormEntity(values, SyncDataHelper.DEFAULT_CHARSET_NAME);
        post.setHeader(postEntity.getContentEncoding());
        post.setEntity(postEntity);

        resp = getHttpClient(context).execute(post, createHttpContext(accountName, authtoken));
        entity = resp.getEntity();
        respStr = EntityUtils.toString(entity);
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new NetworkErrorException(ex);
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException ex) {
                LogHelper.logD(TAG, "Close Entity failed with: " + ex.getMessage(), ex);
            }
        }
    }

    boolean saltSaved = true;
    StatusLine statusLine = resp.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException(statusLine.toString());
        } else if (statusCode == HttpStatus.SC_BAD_REQUEST) {
            saltSaved = false;
        } else {
            throw new ServerException("Server error in query savePwdSalt: " + statusLine);
        }
    } else {
        if (respStr != null && !respStr.startsWith("OK")) {
            Log.w(TAG, "SaltSaved failed with: " + respStr);
            saltSaved = false;
        }
    }
    return saltSaved;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * //ww w  .  j  a  v  a 2s  .  co m
 * @param acm
 * @param account
 * 
 * 
 * @param Activity
 *            if null show a notification when Login is needed otherwise
 *            show the Login-Activity in the context of the provided
 *            Activity. *
 * @return SessionId
 * @throws OperationCanceledException
 * @throws ServerException
 * @throws NetworkErrorException
 */
@SuppressWarnings("deprecation")
public static String blockingGetAuthToken(AccountManager acm, Account account, Activity activity)
        throws OperationCanceledException, ServerException, NetworkErrorException {
    String authToken = null;
    try {
        Bundle result;
        if (activity == null) {
            // New is available from API 14 -> use deprecated API
            result = acm.getAuthToken(account, Constants.AUTHTOKEN_TYPE, true, null, null).getResult();
        } else {
            result = acm.getAuthToken(account, Constants.AUTHTOKEN_TYPE, null, activity, null, null)
                    .getResult();
        }
        if (result != null) {
            if (result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
            }
            if (result.containsKey(AccountManager.KEY_ERROR_CODE)) {
                int errorCode = result.getInt(AccountManager.KEY_ERROR_CODE, -1);
                String msg = result.getString(AccountManager.KEY_ERROR_MESSAGE);
                if (errorCode == Constants.AUTH_ERRORCODE_SERVEREXCEPTION) {
                    throw new ServerException(msg);
                } else {
                    LogHelper.logE(TAG,
                            "Authentification failed with unknown errorCode:" + errorCode + " Message:" + msg,
                            null);
                }
            }
        }
    } catch (AuthenticatorException e) {
        LogHelper.logE(TAG, "Authentification failed.", e);
        // Should not happen -> report error
        ErrorHandler.reportException(e);
    } catch (IOException ex) {
        throw new NetworkErrorException(ex);
    }
    return authToken;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * Send a PayPalPayment to the server for verification an processing.
 * //  w  w w. j a  va2 s. c  om
 * @param priceId
 * @param jsonProofOfPayment
 * @return
 * @throws IOException
 * @throws AuthenticationException
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 * @throws ServerException
 * @throws NetworkErrorException
 */
public static PayPalConfirmationResult verifyPayPalPayment(Context context, Account account, String priceId,
        String jsonProofOfPayment, String authtoken, AccountManager accountManager)
        throws AuthenticationException, OperationCanceledException, ServerException, NetworkErrorException {

    String currAuthtoken = authtoken;
    HttpEntity entity;
    PayPalConfirmationResult result = null;

    boolean retry;
    int retryCount = 0;
    do {
        retry = false;
        entity = null;

        final HttpPost post = new HttpPost(PWDVERIFYPAYMENT_URI);
        List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();
        values.add(new BasicNameValuePair("priceid", priceId));
        values.add(new BasicNameValuePair("confirmation", jsonProofOfPayment));

        HttpResponse resp = null;
        final String respStr;
        try {
            HttpEntity postEntity = new UrlEncodedFormEntity(values, SyncDataHelper.DEFAULT_CHARSET_NAME);
            post.setHeader(postEntity.getContentEncoding());
            post.setEntity(postEntity);

            resp = getHttpClient(context).execute(post, createHttpContext(account.name, authtoken));
            entity = resp.getEntity();
            respStr = EntityUtils.toString(entity);

            StatusLine statusLine = resp.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = PayPalConfirmationResult.fromErrorVal(respStr);
            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                currAuthtoken = retryAuthentification(retryCount, accountManager, currAuthtoken, account.name,
                        resp);
                retry = true;
            } else {
                throw new ServerException("Server error in query verifyPayPalPayment: " + resp.getStatusLine());
            }

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new NetworkErrorException(e);
        } finally {
            consumeContent(entity);
        }
        retryCount++;
    } while (retry);

    return result;
}