com.rukman.emde.smsgroups.client.NetworkUtilities.java Source code

Java tutorial

Introduction

Here is the source code for com.rukman.emde.smsgroups.client.NetworkUtilities.java

Source

/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.rukman.emde.smsgroups.client;

import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Provides utility methods for communicating with the server.
 */
final public class NetworkUtilities {
    /** The tag used to log to adb console. */
    private static final String TAG = "NetworkUtilities";

    /** POST parameter name for the user's account name */
    public static final String PARAM_USERNAME = "username";
    /** POST parameter name for the user's password */
    public static final String PARAM_PASSWORD = "password";
    /** POST parameter name for the user's email address */
    public static final String PARAM_EMAIL = "email";
    /** POST parameter name for the user's password */
    public static final String PARAM_PHONE = "phone";
    /** POST parameter for the group's name */
    public static final String PARAM_NAME = "name";
    /** POST parameter for the group's ID */
    public static final String PARAM_GROUP_ID = "groupId";
    /** POST parameter for the user's ID */
    public static final String PARAM_USER_ID = "userId";

    /** Http header key user's authentication token */
    public static final String PARAM_AUTHORIZATION = "Authorization";

    /** POST parameter name for the client's last-known sync state */
    public static final String PARAM_SYNC_STATE = "syncstate";
    /** POST parameter name for the sending client-edited contact info */
    public static final String PARAM_CONTACTS_DATA = "contacts";
    /** Timeout (in ms) we specify for each http request */
    public static final int HTTP_REQUEST_TIMEOUT_MS = 30 * 1000;

    /** The production version base URL for accessing the group API */
    public static final String GMS_PRODUCTION_URL = "http://api.funyip.com/";
    /** The test version base URL for accessing the group API */
    public static final String GMS_TEST_URL = "http://gms.apiary.io";
    /** The base server url for the app */
    public static final String GMS_BASE_URL = GMS_PRODUCTION_URL;
    /** API Key for Android clients */
    public static final String GMS_ANDROID_API_KEY = "652be249-77ad-4cee-b360-63a94b83a512";
    /** Path component for group */
    public static final String GMS_GROUP_PATH = "group";
    /** Path component for group removal */
    public static final String GMS_REMOVE_PATH = "remove";
    /** Path component for adding contact to group */
    public static final String GMS_USER_PATH = "user";
    /** Path component for querying user's groups */
    public static final String GMS_GET_MY_GROUPS_PATH = "myGroups";
    /** Path component for querying user's owned groups */
    public static final String GMS_GET_MY_OWNED_GROUPS_PATH = "myOwnedGroups";
    /** Path component for querying messaging group subscriptions */
    public static final String GMS_MESSAGING_GROUP_SUBSCRIPTIONS_PATH = "messaging/group/subscriptions";
    /** Path for login */
    public static final String GMS_LOGIN_PATH = "login";
    /** Path for registration */
    public static final String GMS_REGISTRATION_PATH = "register";

    /** Http Header API-KEY for server */
    public static final String GMS_HEADER_API_KEY = "api-key";

    // Building up the needed url pieces via Uri operations
    private static final Uri GMS_BASE_URI = Uri.parse(GMS_BASE_URL);
    private static final Uri GMS_GROUP_URI = GMS_BASE_URI.buildUpon().appendPath(GMS_GROUP_PATH).build();
    private static final Uri GMS_GROUP_USER_URI = GMS_GROUP_URI.buildUpon().appendPath(GMS_USER_PATH).build();

    // Urls we need, from the above Uris
    private static final String GMS_REGISTER_URL = GMS_BASE_URI.buildUpon().appendPath(GMS_REGISTRATION_PATH)
            .build().toString();
    private static final String GMS_LOGIN_URL = GMS_BASE_URI.buildUpon().appendPath(GMS_LOGIN_PATH).build()
            .toString();
    private static final String GMS_GET_MY_GROUPS_URL = GMS_BASE_URI.buildUpon().appendPath(GMS_GET_MY_GROUPS_PATH)
            .build().toString();
    private static final String GMS_GET_MY_OWNED_GROUPS_URL = GMS_BASE_URI.buildUpon()
            .appendPath(GMS_GET_MY_OWNED_GROUPS_PATH).build().toString();
    private static final String GMS_GROUP_URL = GMS_GROUP_URI.toString();
    private static final String GMS_GROUP_REMOVE_URL = GMS_GROUP_URI.buildUpon().appendPath(GMS_REMOVE_PATH).build()
            .toString();
    private static final String GMS_GROUP_USER_URL = GMS_GROUP_USER_URI.toString();
    private static final String GMS_GROUP_REMOVE_USER_URL = GMS_GROUP_USER_URI.buildUpon()
            .appendPath(GMS_REMOVE_PATH).build().toString();

    private static String sErrorString = null;

    private NetworkUtilities() {
    }

    /**
     * Configures the httpClient to connect to the URL provided.
     */
    public static HttpClient getHttpClient() {
        HttpClient httpClient = new DefaultHttpClient();
        final HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
        HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
        ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
        return httpClient;
    }

    public static String getErrorString() throws JSONException {
        return sErrorString;
    }

    public static void setErrorString(String errString) {
        sErrorString = errString;
    }

    private static String doPostRequest(String url, String authToken, JSONObject parameters)
            throws IOException, JSONException {
        final HttpPost post = new HttpPost(url);
        if (!TextUtils.isEmpty(authToken)) {
            post.addHeader(PARAM_AUTHORIZATION, authToken);
        }
        final StringEntity entity = new StringEntity(parameters.toString());
        entity.setContentType("application/json");
        post.addHeader(entity.getContentType());
        post.addHeader(new BasicHeader(GMS_HEADER_API_KEY, GMS_ANDROID_API_KEY));
        post.setEntity(entity);
        return executeHttpRequest(post);
    }

    /**
     * Connects to the SampleSync test server, authenticates the provided
     * username and password.
     *
     * @param username The server account username
     * @param password The server account password
     *
     * @return String The authentication token returned by the server (or null)
     * @throws IOException
     * @throws ClientProtocolException
     * @throws JSONException
     */
    public static String authenticate(String username, String password)
            throws ClientProtocolException, IOException, JSONException {
        JSONObject parameters = new JSONObject();
        parameters.put(PARAM_USERNAME, username);
        parameters.put(PARAM_PASSWORD, password);
        String response = doPostRequest(GMS_LOGIN_URL, null, parameters);
        if (response != null) {
            JSONObject object = new JSONObject(response);
            String authToken = object.getString(JSONKeys.KEY_TOKEN);
            if ((authToken != null) && (authToken.length() > 0)) {
                Log.v(TAG, "Successful authentication");
                return authToken;
            } else {
                Log.e(TAG, "Error authenticating");
                sErrorString = "Error authenticating";
            }
        }
        return null;
    }

    /**
     * Connects to the GMS server and authenticates the provided
     * username and password.
     *
     * @param username The server account username
     * @param password The server account password
     * @param email - needed during registration
     * @param phone - needed during registration
     * @return String The authentication token returned by the server (or null)
     * @throws JSONException
     * @throws IOException
     */
    public static String register(String username, String password, String email, String phone)
            throws JSONException, IOException {
        JSONObject parameters = new JSONObject();
        parameters.put(PARAM_USERNAME, username);
        parameters.put(PARAM_PASSWORD, password);
        parameters.put(PARAM_EMAIL, email);
        parameters.put(PARAM_PHONE, phone);
        return doPostRequest(GMS_REGISTER_URL, null, parameters);
    }

    private static String executeHttpRequest(HttpUriRequest request)
            throws ClientProtocolException, IOException, JSONException {
        final HttpClient client = getHttpClient();
        StringBuilder sb = new StringBuilder();
        String output = null;
        int responseCode;
        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream istream = entity.getContent();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
                    int value = reader.read();
                    while (value != -1) {
                        sb.append((char) value);
                        value = reader.read();
                    }
                } finally {
                    if (istream != null) {
                        istream.close();
                    }
                }
            }
            responseCode = response.getStatusLine().getStatusCode();
            if (responseCode == HttpStatus.SC_OK) {
                output = sb.toString();
                Log.v(TAG, String.format("Response is: %1$s", output));
            } else {
                setErrorString(new JSONObject(sb.toString()).getString(JSONKeys.KEY_MESSAGE));
                Log.v(TAG, String.format("Error is: %1$s",
                        new JSONObject(sb.toString()).getString(JSONKeys.KEY_MESSAGE)));
            }
        } finally {
            client.getConnectionManager().shutdown();
        }
        return output;
    }

    private static String doGetRequest(String url, String authToken) throws IOException, JSONException {
        final HttpGet get = new HttpGet(url);

        get.addHeader(PARAM_AUTHORIZATION, authToken);
        get.addHeader(GMS_HEADER_API_KEY, GMS_ANDROID_API_KEY);
        return executeHttpRequest(get);
    }

    public static JSONArray getMyGroups(String authToken) throws IOException, JSONException {
        String response = doGetRequest(GMS_GET_MY_GROUPS_URL, authToken);
        return (response == null) ? null : new JSONArray(response);
    }

    public static JSONArray getMyOwnedGroups(String authToken) throws IOException, JSONException {
        String response = doGetRequest(GMS_GET_MY_OWNED_GROUPS_URL.toString(), authToken);
        return (response == null) ? null : new JSONArray(response);
    }

    public static JSONObject createGroup(String authToken, String groupName)
            throws ClientProtocolException, IOException, JSONException {
        JSONObject parameters = new JSONObject();
        String response = null;
        parameters.put(PARAM_NAME, groupName);
        response = doPostRequest(GMS_GROUP_URL, authToken, parameters);
        return (response == null) ? null : new JSONObject(response);
    }

    public static String deleteGroup(String authToken, String groupId)
            throws ClientProtocolException, IOException, JSONException {
        JSONObject parameters = new JSONObject();
        parameters.put(PARAM_GROUP_ID, groupId);
        return doPostRequest(GMS_GROUP_REMOVE_URL, authToken, parameters);
    }

    public static JSONObject getGroup(String authToken, String groupId) throws IOException, JSONException {
        String response = doGetRequest(GMS_GROUP_URL, authToken);
        return (response == null) ? null : new JSONObject(response);
    }

    public static JSONObject addUserToGroup(String authToken, String groupId, String name, String phone)
            throws ClientProtocolException, IOException, JSONException {
        JSONObject parameters = new JSONObject();
        String response = null;
        parameters.put(PARAM_GROUP_ID, groupId);
        parameters.put(PARAM_NAME, name);
        parameters.put(PARAM_PHONE, phone);
        response = doPostRequest(GMS_GROUP_USER_URL, authToken, parameters);
        return (TextUtils.isEmpty(response)) ? null : new JSONObject(response);
    }

    public static JSONObject removeGroupContact(String authToken, String groupId, String userId)
            throws ClientProtocolException, IOException, JSONException {
        JSONObject parameters = new JSONObject();
        String response = null;
        parameters.put(PARAM_GROUP_ID, groupId);
        parameters.put(PARAM_USER_ID, userId);
        response = doPostRequest(GMS_GROUP_REMOVE_USER_URL, authToken, parameters);
        return (TextUtils.isEmpty(response)) ? null : new JSONObject(response);
    }

}