Example usage for org.apache.http.auth AuthenticationException AuthenticationException

List of usage examples for org.apache.http.auth AuthenticationException AuthenticationException

Introduction

In this page you can find the example usage for org.apache.http.auth AuthenticationException AuthenticationException.

Prototype

public AuthenticationException() 

Source Link

Document

Creates a new AuthenticationException with a null detail message.

Usage

From source file:com.example.cpulocal.myapplication_sample.samplesync.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.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account/*ww w .j a  v a 2s. c  o  m*/
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyContacts A list of the contacts to send to the server
 * @return A list of contacts that we need to update locally
 */
public static List<RawContact> syncContacts(Account account, String authtoken, long serverSyncState,
        List<RawContact> dirtyContacts)
        throws JSONException, ParseException, IOException, AuthenticationException {
    // Convert our list of User objects into a list of JSONObject
    List<JSONObject> jsonContacts = new ArrayList<JSONObject>();
    for (RawContact rawContact : dirtyContacts) {
        jsonContacts.add(rawContact.toJSONObject());
    }

    // Create a special JSONArray of our JSON contacts
    JSONArray buffer = new JSONArray(jsonContacts);

    // Create an array that will hold the server-side contacts
    // that have been changed (returned by the server).
    final ArrayList<RawContact> serverDirtyList = new ArrayList<RawContact>();

    // Prepare our POST data
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
    params.add(new BasicNameValuePair(PARAM_AUTH_TOKEN, authtoken));
    params.add(new BasicNameValuePair(PARAM_CONTACTS_DATA, buffer.toString()));
    if (serverSyncState > 0) {
        params.add(new BasicNameValuePair(PARAM_SYNC_STATE, Long.toString(serverSyncState)));
    }
    Log.i(TAG, params.toString());
    HttpEntity entity = new UrlEncodedFormEntity(params);

    // Send the updated friends data to the server
    Log.i(TAG, "Syncing to: " + SYNC_CONTACTS_URI);
    final HttpPost post = new HttpPost(SYNC_CONTACTS_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    final HttpResponse resp = getHttpClient().execute(post);
    final String response = EntityUtils.toString(resp.getEntity());
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // Our request to the server was successful - so we assume
        // that they accepted all the changes we sent up, and
        // that the response includes the contacts that we need
        // to update on our side...
        final JSONArray serverContacts = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < serverContacts.length(); i++) {
            RawContact rawContact = RawContact.valueOf(serverContacts.getJSONObject(i));
            if (rawContact != null) {
                serverDirtyList.add(rawContact);
            }
        }
    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in sending dirty contacts");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine());
            throw new IOException();
        }
    }

    return serverDirtyList;
}

From source file:com.example.makerecg.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side ADSampleFrames. 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.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account//from w w  w .j a  va2 s . c o m
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyFrames A list of the frames to send to the server
 * @return A list of frames that we need to update locally
 */
public static List<ADSampleFrame> syncSampleFrames(Account account, String authtoken, long serverSyncState,
        List<ADSampleFrame> dirtyFrames)
        throws JSONException, ParseException, IOException, AuthenticationException {

    List<JSONObject> jsonFrames = new ArrayList<JSONObject>();
    for (ADSampleFrame frame : dirtyFrames) {
        jsonFrames.add(frame.toJSONObject());
    }

    JSONArray buffer = new JSONArray(jsonFrames);
    JSONObject top = new JSONObject();

    top.put("data", buffer);

    // Create an array that will hold the server-side ADSampleFrame
    // that have been changed (returned by the server).
    final ArrayList<ADSampleFrame> serverDirtyList = new ArrayList<ADSampleFrame>();

    // Send the updated frames data to the server
    //Log.i(TAG, "Syncing to: " + SYNC_URI);
    URL urlToRequest = new URL(SYNC_URI);
    HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "Bearer " + authtoken);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(top.toString(1));
    writer.flush();
    writer.close();
    os.close();

    //Log.i(TAG, "body="+top.toString(1));

    int responseCode = conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        // Our request to the server was successful - so we assume
        // that they accepted all the changes we sent up, and
        // that the response includes the contacts that we need
        // to update on our side...

        // TODO: Only uploading data for now ...

        String response = "";
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
        br.close();

        //Log.i(TAG, "response="+response);
        /*
        final JSONArray serverContacts = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < serverContacts.length(); i++) {
        ADSampleFrame rawContact = ADSampleFrame.valueOf(serverContacts.getJSONObject(i));
        if (rawContact != null) {
            serverDirtyList.add(rawContact);
        }
        }
        */
    } else {
        if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in while uploading data");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in sending sample frames: " + responseCode);
            throw new IOException();
        }
    }

    return null;
}

From source file:edu.cmu.android.restaurant.authentication.NetworkUtilities.java

/**
 * Fetches the list of friend data updates from the server
 * /*from  ww w  . j  ava 2s  . c  o m*/
 * @param account
 *            The account being synced.
 * @param authtoken
 *            The authtoken stored in AccountManager for this account
 * @param lastUpdated
 *            The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account, String authtoken, Date lastUpdated)
        throws JSONException, ParseException, IOException, AuthenticationException {
    final ArrayList<User> friendList = new ArrayList<User>();
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken));
    if (lastUpdated != null) {
        final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        params.add(new BasicNameValuePair(PARAM_UPDATED, formatter.format(lastUpdated)));
    }
    Log.i(TAG, params.toString());

    HttpEntity entity = null;
    entity = new UrlEncodedFormEntity(params);
    final HttpPost post = new HttpPost(FETCH_FRIEND_UPDATES_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

    final HttpResponse resp = mHttpClient.execute(post);
    final String response = EntityUtils.toString(resp.getEntity());

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // Succesfully connected to the samplesyncadapter server and
        // authenticated.
        // Extract friends data in json format.
        final JSONArray friends = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < friends.length(); i++) {
            friendList.add(User.valueOf(friends.getJSONObject(i)));
        }
    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in fetching remote contacts");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in fetching remote contacts: " + resp.getStatusLine());
            throw new IOException();
        }
    }
    return friendList;
}

From source file:com.zoterodroid.client.ZoteroApi.java

private static String ZoteroApiCall(String url, TreeMap<String, String> params, Account account,
        Context context) throws IOException, AuthenticationException {

    String username = account.name;
    String authtoken = null;/* w  ww.  j a v  a 2 s  .c o m*/
    String scheme = null;

    AuthToken at = new AuthToken(context, account);
    authtoken = at.getAuthToken();

    scheme = SCHEME;

    HttpResponse resp = null;
    HttpGet post = null;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(scheme);
    builder.authority(ZOTERO_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }

    Log.d("apiCallUrl", builder.build().toString());
    post = new HttpGet(builder.build().toString());

    maybeCreateHttpClient();
    post.setHeader("User-Agent", "ZoteroDroid");

    CredentialsProvider provider = mHttpClient.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, authtoken);
    provider.setCredentials(SCOPE, credentials);

    resp = mHttpClient.execute(post);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return EntityUtils.toString(resp.getEntity());
    } else if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        throw new AuthenticationException();
    } else {
        throw new IOException();
    }
}

From source file:com.bearstech.android.myownsync.client.NetworkUtilities.java

/**
 * Fetches the list of friend data updates from the server
 * //from  ww w.  j a  v  a 2s  .co  m
 * @param account The account being synced.
 * @param authtoken The authtoken stored in AccountManager for this account
 * @param lastUpdated The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account, String authtoken, Date lastUpdated)
        throws JSONException, ParseException, IOException, AuthenticationException {
    final ArrayList<User> friendList = new ArrayList<User>();
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken));
    if (lastUpdated != null) {
        final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        params.add(new BasicNameValuePair(PARAM_UPDATED, formatter.format(lastUpdated)));
    }
    Log.i(TAG, params.toString());

    HttpEntity entity = null;
    entity = new UrlEncodedFormEntity(params);
    final HttpPost post = new HttpPost(base_url + FETCH_FRIEND_UPDATES_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

    final HttpResponse resp = mHttpClient.execute(post);
    final String response = EntityUtils.toString(resp.getEntity());

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // Succesfully connected to the samplesyncadapter server and
        // authenticated.
        // Extract friends data in json format.
        final JSONArray friends = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < friends.length(); i++) {
            friendList.add(User.valueOf(friends.getJSONObject(i)));
        }
    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in fetching remote contacts");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in fetching remote contacts: " + resp.getStatusLine());
            throw new IOException();
        }
    }
    return friendList;
}

From source file:org.ohmage.sync.StreamSyncAdapterTest.java

public void testOnPerformSyncForStreams_authError_closesWriter() throws Exception {
    Streams fakeStreams = new Streams();
    fakeStreams.add(fakeStream);//  w  ww .  jav a 2s  .c o  m
    when(fakeWriter.moveToNextBatch()).thenReturn(true, false);
    whenAccountStillExists();
    when(fakeOhmageService.uploadStreamData(fakeStreamId, fakeStreamVersion, fakeWriter))
            .thenThrow(new AuthenticationException());

    mSyncAdapter.performSyncForStreams(fakeAccount, fakeStreams, fakeWriter, fakeSyncResult);

    verify(fakeWriter).close();
}

From source file:edu.cmu.android.restaurant.authentication.NetworkUtilities.java

/**
 * Fetches status messages for the user's friends from the server
 * /*  w  w w . ja va  2s. com*/
 * @param account
 *            The account being synced.
 * @param authtoken
 *            The authtoken stored in the AccountManager for the account
 * @return list The list of status messages received from the server.
 */
public static List<User.Status> fetchFriendStatuses(Account account, String authtoken)
        throws JSONException, ParseException, IOException, AuthenticationException {
    final ArrayList<User.Status> statusList = new ArrayList<User.Status>();
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken));

    HttpEntity entity = null;
    entity = new UrlEncodedFormEntity(params);
    final HttpPost post = new HttpPost(FETCH_STATUS_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

    final HttpResponse resp = mHttpClient.execute(post);
    final String response = EntityUtils.toString(resp.getEntity());

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // Succesfully connected to the samplesyncadapter server and
        // authenticated.
        // Extract friends data in json format.
        final JSONArray statuses = new JSONArray(response);
        for (int i = 0; i < statuses.length(); i++) {
            statusList.add(User.Status.valueOf(statuses.getJSONObject(i)));
        }
    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in fetching friend status list");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in fetching friend status list");
            throw new IOException();
        }
    }
    return statusList;
}