palamarchuk.fraudguide.utils.QueryMaster.java Source code

Java tutorial

Introduction

Here is the source code for palamarchuk.fraudguide.utils.QueryMaster.java

Source

package palamarchuk.fraudguide.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import palamarchuk.fraudguide.R;

public class QueryMaster extends Thread {

    /**
     *   ?,   ? 
     */
    //    public static final String ERROR_MESSAGE = "  ?,   ? ";

    /**
     *   ?  ?
     */
    //    public static final String SERVER_RETURN_INVALID_DATA = "  ?  ?";

    public static final int QUERY_MASTER_COMPLETE = 1;
    public static final int QUERY_MASTER_ERROR = 2;
    public static final int QUERY_MASTER_NETWORK_ERROR = 3;

    public static final int QUERY_GET = 23;
    public static final int QUERY_POST = 24;

    public void setProgressDialog() {
        String downloading = context.getString(R.string.downloading);
        this.progressDialog = ProgressDialog.show(context, null, downloading);
    }

    private ProgressDialog progressDialog;

    private OnCompleteListener onCompleteListener;
    private Handler handler;

    /**
     * android {
     * compileSdkVersion 19
     * buildToolsVersion "19.1.0"
     * <p/>
     * defaultConfig {
     * minSdkVersion 11
     * targetSdkVersion 19
     * versionCode 1
     * versionName "1.0"
     * }
     * buildTypes {
     * release {
     * runProguard false
     * proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
     * }
     * }
     * <p/>
     * <p/>
     * <p style="color:red; font-weight:bold;">
     * packagingOptions{
     * exclude 'META-INF/NOTICE'
     * exclude 'META-INF/LICENSE'
     * exclude 'META-INF/*'
     * exclude 'META-INF/LICENSE.txt'
     * }
     * </p>
     * <p/>
     * <p/>
     * }
     * <p/>
     * dependencies {
     * compile 'com.android.support:appcompat-v7:19.+'
     * compile 'com.google.android.gms:play-services:4.4.52'
     * compile fileTree(dir: 'libs', include: ['*.jar'])
     * }
     */
    private MultipartEntity entity;
    private Context context;

    private String serverResponse;
    private String url;

    private int queryType;

    public static int timeoutConnection = 10000;

    /**
     * @param context
     * @param url
     * @param queryType QueryMaster.QUERY_GET or QueryMaster.QUERY_POST
     * @param entity
     */
    public QueryMaster(Context context, String url, int queryType, MultipartEntity entity) {
        this(context, url, queryType);
        this.entity = entity;
    }

    public QueryMaster(Context context, String url, int queryType) {
        this.context = context;
        this.url = url;
        this.queryType = queryType;
        initHandler();
    }

    @Override
    public void run() {
        super.run();

        if (!isNetworkConnected()) {
            handler.sendEmptyMessage(QUERY_MASTER_NETWORK_ERROR);
            return;
        }
        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeoutConnection);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
        //        httpclient.setParams(httpParams);

        HttpPost httpPost;
        HttpGet httpGet;

        HttpResponse response = null;

        try {

            if (queryType == QUERY_GET) {
                httpGet = new HttpGet(url);

                response = httpclient.execute(httpGet);

            } else if (queryType == QUERY_POST) {

                httpPost = new HttpPost(url);
                if (entity != null) {
                    httpPost.setEntity(entity);
                }
                response = httpclient.execute(httpPost);
            }

            serverResponse = EntityUtils.toString(response.getEntity());

            handler.sendEmptyMessage(QUERY_MASTER_COMPLETE);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            handler.sendEmptyMessage(QUERY_MASTER_ERROR);
        } catch (IOException e) {
            e.printStackTrace();
            handler.sendEmptyMessage(QUERY_MASTER_ERROR);
        } catch (NullPointerException e) {
            e.printStackTrace();
            handler.sendEmptyMessage(QUERY_MASTER_ERROR);
        }
    }

    public void setOnCompleteListener(OnCompleteListener onCompleteListener) {
        this.onCompleteListener = onCompleteListener;
    }

    public static boolean isSuccess(JSONObject jsonObject) throws JSONException {
        return jsonObject.getString("status").equalsIgnoreCase("success");
    }

    public interface OnCompleteListener {
        public void complete(String serverResponse);

        public void error(int errorCode);
    }

    private void initHandler() {
        this.setPriority(MIN_PRIORITY);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (onCompleteListener != null) {
                    if (msg.what == QUERY_MASTER_COMPLETE) {
                        onCompleteListener.complete(serverResponse);
                    }
                    if (msg.what == QUERY_MASTER_ERROR) {
                        onCompleteListener.error(QUERY_MASTER_ERROR);
                    }
                    if (msg.what == QUERY_MASTER_NETWORK_ERROR) {
                        onCompleteListener.error(QUERY_MASTER_NETWORK_ERROR);
                    }
                }
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }

            }
        };
    }

    private boolean isNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public Context getContext() {
        return context;
    }

    public static AlertDialog alert(Context context, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message);
        //        builder.setTitle("");

        builder.setPositiveButton("Ok", null);
        return builder.show();
    }

    public static AlertDialog.Builder alertBuilder(Context context, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message);
        //        builder.setTitle("");

        return builder;
    }

    public static void toast(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
}