Android Open Source - Joetz-Android-V2 Api Connection






From Project

Back to project page Joetz-Android-V2.

License

The source code is released under:

GNU General Public License

If you think the Android project Joetz-Android-V2 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.example.jens.myapplication.apimanager;
/*from  w w  w . j  a v  a  2s.com*/
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;


import com.example.jens.myapplication.apimanager.manager.ImageManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
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.HttpRequestBase;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.UnknownHostException;

/**
 * Class for handling requests to the backend
 */
public class ApiConnection {
    /**
     * Indicates the server could not be reached.
     */
    public static final int STATUS_UNKNOWN_HOST = -1;
    public static final int STATUS_CONNECTION_EXCEPTION = -2;
    public static final int STATUS_OTHER = Integer.MIN_VALUE;

    public static final int STATUS_OK = 200;
    public static final int STATUS_OK_NO_BODY = 204;

    public static final int STATUS_BAD_REQUEST = 400;
    public static final int STATUS_UNAUTHORIZED = 401;
    public static final int STATUS_CONFLICT = 409;

    public static final int STATUS_INTERNAL_SERVER_ERROR = 500;

    public static final int REQUEST_GET = 0;
    public static final int REQUEST_POST = 1;
    public static final int REQUEST_PUT = 2;
    public static final int REQUEST_DELETE = 3;

    //MOCK SERVER
    //private static final String URL = "http://private-anon-a7172db42-joetz.apiary-mock.com/";

    //REAL SERVER
    public static final String URL = "http://joetzdev.azurewebsites.net/";

    private static final String STANDARD_CONTENT_TYPE = "application/json";

    /**
     *  Sends a POST request to the Joetz server.
     * @param action (www.example.com/{action}) [e.g. api/camps]
     * @param jsonTask Function that parses the JSON code and returns an object.
     * @param postTask Object holding a procedure to be executed AFTER the request and json parsing
     *                 has completed.
     *                 (Executed on main thread, possible to do UI adjustment here)
     * @param requestParams Parameters for the request
     */
    public static <T> CancellableTask post(String action, JSONParsingTask<T> jsonTask,
                                           PostRequestTask<T> postTask, RequestParams requestParams){
        HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_POST, jsonTask, postTask, requestParams);
        task.execute();
        return task;
    }

    /**
     *  Sends a GET request to the Joetz server.
     * @param action (www.example.com/{action}) [e.g. api/camps]
     * @param jsonTask Function that parses the JSON code and returns an object.
     * @param postTask Object holding a procedure to be executed AFTER the request and json parsing
     *                 has completed.
     *                 (Executed on main thread, possible to do UI adjustment here)
     * @param requestParams Parameters for the request
     */
    public static <T> CancellableTask get(String action, JSONParsingTask<T> jsonTask,
                                          PostRequestTask<T> postTask, RequestParams requestParams){
        //new HttpGetAsyncTask(action, postTask, authToken).execute();
        HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_GET, jsonTask, postTask, requestParams);
        task.execute();
        return task;
    }

    /**
     *  Sends a PUT request to the Joetz server.
     * @param action (www.example.com/{action}) [e.g. api/camps]
     * @param jsonTask Function that parses the JSON code and returns an object.
     * @param postTask Object holding a procedure to be executed AFTER the request and json parsing
     *                 has completed.
     *                 (Executed on main thread, possible to do UI adjustment here)
     * @param requestParams Parameters for the request
     */
    public static <T> CancellableTask put(String action, JSONParsingTask<T> jsonTask,
                                          PostRequestTask<T> postTask, RequestParams requestParams){
        HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_PUT, jsonTask, postTask, requestParams);
        task.execute();
        return task;
    }

    /**
     *  Sends a DELETE request to the Joetz server.
     * @param action (www.example.com/{action}) [e.g. api/users/people/{id}]
     * @param jsonTask Function that parses the JSON code and returns an object.
     * @param postTask Object holding a procedure to be executed AFTER the request and json parsing
     *                 has completed.
     *                 (Executed on main thread, possible to do UI adjustment here)
     * @param requestParams Parameters for the request
     */
    public static <T> CancellableTask delete(String action, JSONParsingTask<T> jsonTask,
                                          PostRequestTask<T> postTask, RequestParams requestParams){
        HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_DELETE, jsonTask, postTask, requestParams);
        task.execute();
        return task;
    }

    @Deprecated
    public static CancellableTask getImage(String action, ImageManager.OnImageLoadedListener callback){
        ImageLoadingAsyncTask task = new ImageLoadingAsyncTask(action, callback);
        task.execute();
        return task;
    }

    /**
     * Converts the inputstream into a String.
     * @param inputStream Input stream returned by the HttpResponse
     * @return JSON String
     * @throws java.io.IOException
     */
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null){
            result += line;
        }

        inputStream.close();
        return result;
    }

    public static boolean isSuccessCode(int statusCode){
        return statusCode >= 200 && statusCode < 300;
    }

    public static boolean isConnectionFailedCode(int statusCode){
        return statusCode < 0;
    }

    /**
     * AsyncTask to handle API requests
     */
    private static class HttpAsyncTask<T> extends AsyncTask<Void, Void, T>
            implements CancellableTask{

        private String action;
        private int requestType;
        private JSONParsingTask<T> jsonTask;
        private PostRequestTask<T> postTask;
        private RequestParams requestParams;

        private volatile boolean wasCancelled = false;

        private volatile int statusCode;

        /**
         *  Executes the request to the server
         * @param action (www.example.com/api/{action})
         * //@param jsonObject JSON Object containing required data to post. [optional (null)]
         * @param jsonTask Task that will parse the JSON and return an object.
         * @param postTask Task that will be executed AFTER the request and the JSON parsing
         *                 are finished.
         * @param requestParams Parameters for the request
         */
        public HttpAsyncTask(String action, int requestType, JSONParsingTask<T> jsonTask,
                             PostRequestTask<T> postTask, RequestParams requestParams){
            super();
            this.action = action;
            this.requestType = requestType;
            this.jsonTask = jsonTask;
            this.postTask = postTask;
            this.requestParams = requestParams == null ? new RequestParams() : requestParams;
        }

        @Override
        protected T doInBackground(Void... params) {
            try {
                //testing purposes waiting time
                /*try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/

                HttpRequestBase requestBase = null;

                String fullUrl = URL + action;
                if(requestType == REQUEST_POST ||
                        requestType == REQUEST_PUT){
                    HttpEntityEnclosingRequestBase httpBase;
                    switch(requestType){
                        case REQUEST_POST: httpBase = new HttpPost(fullUrl); break;
                        case REQUEST_PUT: httpBase = new HttpPut(fullUrl); break;
                        default: Log.wtf("ApiConnection", "something else in post/put"); return null;
                    }

                    if(requestParams.getRawBody() != null){
                        httpBase.setEntity(requestParams.getRawBody());
                    }

                    if(requestParams.getContentType() == null){
                        httpBase.setHeader("Content-type", STANDARD_CONTENT_TYPE);
                    }else{
                        httpBase.setHeader("Content-Type", requestParams.getContentType());
                    }

                    requestBase = httpBase;
                }else if(requestType == REQUEST_GET) {
                    requestBase = new HttpGet(fullUrl);
                }else if(requestType == REQUEST_DELETE){
                    requestBase = new HttpDelete(fullUrl);
                }else{
                    statusCode = STATUS_OTHER;
                    return null;
                }

                if(requestParams.getAcceptHeader() != null){
                    requestBase.setHeader("Accept", requestParams.getAcceptHeader());
                }

                if(requestParams.getAuthKey() != null){
                    requestBase.setHeader("Authorization", requestParams.getAuthKey());
                }

                HttpResponse response = executeRequest(requestBase);
                if(wasCancelled){
                    return null;
                }
                statusCode = response.getStatusLine().getStatusCode();

                Log.d("ApiConnection", "Statuscode: " + statusCode);
                String pureJson = null;
                if(response.getEntity() != null){
                    InputStream inputStream = response.getEntity().getContent();
                    pureJson = convertInputStreamToString(inputStream);
                    Log.d("ApiConnection", "JSON: " + pureJson);
                }
                if(wasCancelled){
                    return null;
                }

                if(statusCode != STATUS_OK || jsonTask == null){
                    return null;
                }

                try{
                    return jsonTask.handleJSON(pureJson);
                }catch(IOException e){
                    e.printStackTrace();
                    return null;
                }
            }catch(UnknownHostException e){
                statusCode = ApiConnection.STATUS_UNKNOWN_HOST;
                return null;
            }catch(HttpHostConnectException e){
                statusCode = ApiConnection.STATUS_CONNECTION_EXCEPTION;
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                statusCode = STATUS_OTHER;
                return null;
            }
        }

        private HttpResponse executeRequest(HttpRequestBase requestBase) throws IOException {
            HttpClient httpClient = new DefaultHttpClient();
            return httpClient.execute(requestBase);
        }

        @Override
        protected void onPostExecute(T result) {
            if(!wasCancelled && postTask != null){
                postTask.doTask(result, statusCode);
            }
        }

        @Override
        public void cancelTask(){
            wasCancelled = true;
        }
    }

    @Deprecated
    private static class ImageLoadingAsyncTask extends AsyncTask<Void, Integer, Drawable>
            implements  CancellableTask{
        private String imgUrl;
        private ImageManager.OnImageLoadedListener callback;

        //private volatile InputStream inputStream;

        private volatile boolean cancelled = false;

        public ImageLoadingAsyncTask(String action, ImageManager.OnImageLoadedListener callback){
            this.imgUrl = ApiConnection.URL + action;
            this.callback = callback;
        }

        @Override
        protected Drawable doInBackground(Void... params) {
            InputStream inputStream = null;
            try{
                inputStream = (InputStream) new java.net.URL(imgUrl).getContent();
                if(!cancelled){
                    Drawable d = Drawable.createFromStream(inputStream, "src name");
                    return d;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch(FileNotFoundException e){
                Log.e("ApiConnection", "File was not found: " + imgUrl);
                return null;
            } catch(IOException e) {
                e.printStackTrace();
            }finally{
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Drawable drawable) {
            if(!cancelled && drawable != null){
                callback.onImageLoaded(drawable);
            }
        }

        @Override
        public void cancelTask() {
            cancelled = true;
        }
    }
}




Java Source Code List

com.example.jens.myapplication.ApplicationTest.java
com.example.jens.myapplication.account.FragmentAccount.java
com.example.jens.myapplication.account.LoginDialogActivity.java
com.example.jens.myapplication.account.LoginFragment.java
com.example.jens.myapplication.account.PersonsFragment.java
com.example.jens.myapplication.account.ProfileFragment.java
com.example.jens.myapplication.account.RegisterDialogActivity.java
com.example.jens.myapplication.account.RegisterFragment.java
com.example.jens.myapplication.account.TabsPagerAdapter.java
com.example.jens.myapplication.activities.ActivityDetailActivity.java
com.example.jens.myapplication.activities.ActivityDetailFragment.java
com.example.jens.myapplication.activities.FragmentListActivities.java
com.example.jens.myapplication.activities.JoetzActivitiesAdapter.java
com.example.jens.myapplication.activities.JoetzActivity.java
com.example.jens.myapplication.activities.StartActivity.java
com.example.jens.myapplication.apimanager.ApiConnection.java
com.example.jens.myapplication.apimanager.CancellableTask.java
com.example.jens.myapplication.apimanager.JSONParsingTask.java
com.example.jens.myapplication.apimanager.PostRequestTask.java
com.example.jens.myapplication.apimanager.RequestParams.java
com.example.jens.myapplication.apimanager.SimpleRequestTask.java
com.example.jens.myapplication.apimanager.filter.PersonFilter.java
com.example.jens.myapplication.apimanager.manager.ActivityManager.java
com.example.jens.myapplication.apimanager.manager.AuthToken.java
com.example.jens.myapplication.apimanager.manager.BookingManager.java
com.example.jens.myapplication.apimanager.manager.CampManager.java
com.example.jens.myapplication.apimanager.manager.ImageManager.java
com.example.jens.myapplication.apimanager.manager.LoginManager.java
com.example.jens.myapplication.apimanager.manager.ProfileManager.java
com.example.jens.myapplication.apimanager.manager.RegisterManager.java
com.example.jens.myapplication.booking.AddPersonActivity.java
com.example.jens.myapplication.booking.BookingActivity.java
com.example.jens.myapplication.booking.BookingBondFragment.java
com.example.jens.myapplication.booking.BookingContactFragment.java
com.example.jens.myapplication.booking.BookingExtraFragment.java
com.example.jens.myapplication.booking.BookingParticipantsFragment.java
com.example.jens.myapplication.bookingHistory.BookingHistoryDetailActivity.java
com.example.jens.myapplication.bookingHistory.BookingHistoryDetailFragment.java
com.example.jens.myapplication.bookingHistory.BookingHistoryOverviewFragment.java
com.example.jens.myapplication.bookingHistory.BookingsAdapter.java
com.example.jens.myapplication.calendar.FragmentCalendar.java
com.example.jens.myapplication.calendar.KalenderAdapter.java
com.example.jens.myapplication.calendar.KalenderItem.java
com.example.jens.myapplication.camps.CampAdapter.java
com.example.jens.myapplication.camps.CampDetailActivity.java
com.example.jens.myapplication.camps.CampFilterActivity.java
com.example.jens.myapplication.camps.FilterFragment.java
com.example.jens.myapplication.camps.FragmentListCamps.java
com.example.jens.myapplication.camps.ImageActivity.java
com.example.jens.myapplication.camps.ImagePagerFragment.java
com.example.jens.myapplication.camps.InfoFragment.java
com.example.jens.myapplication.camps.PhotoFragment.java
com.example.jens.myapplication.camps.RecyclerItemClickListener.java
com.example.jens.myapplication.camps.SquareImageView.java
com.example.jens.myapplication.camps.TabsPagerAdapter.java
com.example.jens.myapplication.domain.BookingStatus.java
com.example.jens.myapplication.domain.Booking.java
com.example.jens.myapplication.domain.Camp.java
com.example.jens.myapplication.domain.PeriodCategory.java
com.example.jens.myapplication.domain.Person.java
com.example.jens.myapplication.domain.UserRole.java
com.example.jens.myapplication.domain.User.java
com.example.jens.myapplication.domain.binding.PersonValidatorBinding.java
com.example.jens.myapplication.domain.binding.UserValidatorBinding.java
com.example.jens.myapplication.domain.binding.ValidatorBinding.java
com.example.jens.myapplication.domain.converter.ErrorConverter.java
com.example.jens.myapplication.domain.converter.MyStringParser.java
com.example.jens.myapplication.domain.converter.UnixDateTimeConverter.java
com.example.jens.myapplication.domain.validator.PersonValidator.java
com.example.jens.myapplication.domain.validator.UserValidator.java
com.example.jens.myapplication.domain.validator.Validator.java
com.example.jens.myapplication.home.AanbevolenAdapter.java
com.example.jens.myapplication.home.HomeFragment.java
com.example.jens.myapplication.home.ImageSlideAdapter.java
com.example.jens.myapplication.home.Reclame.java
com.example.jens.myapplication.lib.RangeSeekBar.java
com.example.jens.myapplication.main.MainActivity.java
com.example.jens.myapplication.main.NavDrawerAdapter.java
com.example.jens.myapplication.main.NavDrawerItem.java
com.example.jens.myapplication.main.NavMenuItem.java
com.example.jens.myapplication.main.NavMenuSection.java
com.example.jens.myapplication.sam.JoetzApplication.java
com.example.jens.myapplication.sam.MyFragment.java
com.example.jens.myapplication.sam.MySaveableFragment.java
com.example.jens.myapplication.util.AESEncryption.java
com.example.jens.myapplication.util.ActivityUtils.java
com.example.jens.myapplication.util.BindingUtils.java
com.example.jens.myapplication.util.DateTimeStringConverter.java
com.example.jens.myapplication.util.JsonUtils.java
com.example.jens.myapplication.util.MyMonths.java
com.example.jens.myapplication.util.StringUtils.java
com.example.jens.myapplication.view.MyLinearLayout.java