org.bibimbap.shortcutlink.RestClient.java Source code

Java tutorial

Introduction

Here is the source code for org.bibimbap.shortcutlink.RestClient.java

Source

/*
 * Copyright (C) 2010 Andy Prock
 *
 * 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 org.bibimbap.shortcutlink;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * Concrete subclass of StrategicAsyncTask for executing Rest commands
 * on a background thread, and posting status and results to the main
 * thread.
 */
public class RestClient
        extends StrategicAsyncTask<RestClientRequest, RestClient.RestfulState, RestClientRequest[]> {
    private static final String TAG = RestClient.class.getSimpleName();

    /**
     * State reported for progress
     */
    public enum RestfulState {
        DS_INITIATING, DS_ONGOING, DS_FAILED, DS_SUCCESS
    }

    /**
     * Construct the RestClient
     */
    public RestClient(ProgressStrategy<RestClient.RestfulState> progressStrategy,
            FinishedStrategy<RestClientRequest[]> finishedStrategy) {
        super(progressStrategy, finishedStrategy);
    }

    /**
     * Create a new RestfulState array, and send it to the main thread
     * <p>
     * null values, imply no change in state
     */
    private void publishProgress(int length, int index, RestfulState state) {
        RestfulState restfulState[] = new RestfulState[length];
        restfulState[index] = state;
        publishProgress(restfulState);
    }

    /**
     * Execute the REST subtasks
     */
    protected RestClientRequest[] doInBackground(RestClientRequest... params) {
        // HttpClient that is configured with reasonable default settings and registered schemes for Android
        final AndroidHttpClient httpClient = AndroidHttpClient.newInstance(RestClient.class.getSimpleName());

        for (int index = 0; index < params.length; index++) {
            RestClientRequest rcr = params[index];
            HttpUriRequest httprequest = null;
            try {
                HttpResponse httpresponse = null;
                HttpEntity httpentity = null;

                // initiating
                publishProgress(params.length, index, RestfulState.DS_INITIATING);

                switch (rcr.getHttpRequestType()) {
                case HTTP_PUT:
                    httprequest = new HttpPut(rcr.getURI());
                    break;
                case HTTP_POST:
                    httprequest = new HttpPost(rcr.getURI());
                    break;
                case HTTP_DELETE:
                    httprequest = new HttpDelete(rcr.getURI());
                    break;
                case HTTP_GET:
                default:
                    // default to HTTP_GET
                    httprequest = new HttpGet(rcr.getURI());
                    break;
                }

                // resting
                publishProgress(params.length, index, RestfulState.DS_ONGOING);

                if ((httpresponse = httpClient.execute(httprequest)) != null) {
                    if ((httpentity = httpresponse.getEntity()) != null) {
                        rcr.setResponse(EntityUtils.toByteArray(httpentity));
                    }
                }

                // success
                publishProgress(params.length, index, RestfulState.DS_SUCCESS);
            } catch (Exception ioe) {
                Log.i(TAG, ioe.getClass().getSimpleName());

                // clear out the response
                rcr.setResponse(null);

                // abort the request on failure
                httprequest.abort();

                // failed
                publishProgress(params.length, index, RestfulState.DS_FAILED);
            }
        }

        // close the connection
        if (httpClient != null)
            httpClient.close();

        return params;
    }
}