com.project.utilities.Utilities.java Source code

Java tutorial

Introduction

Here is the source code for com.project.utilities.Utilities.java

Source

package com.project.utilities;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.StrictMode;
import android.provider.Settings.Secure;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.project.constants.Constants;
import com.project.datamodel.LicenseDataModel;
import com.project.datamodel.ViolationDataModel;

public class Utilities extends Constants {

    /**
     * Initiate all necessary folder on External Storage
     */
    public static void initiateDirectory() {
        File externalDir = new File(EXTERNAL_DIRECTORY);
        if (!externalDir.mkdirs()) {
            Log.e("Utilities", "Error creating directory");
        }
    }

    /**
     * Sends post request to sepcified URL
     * @param valuePairs
     * @param postUrl
     * @return
     */
    public static String postRequest(final List<BasicNameValuePair> valuePairs, final String postUrl) {
        String responseStr = null;

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        HttpClient httpclient = new DefaultHttpClient();
        Log.e("POST_REQUEST", "ACTION LOGIN");
        HttpPost httppost = new HttpPost(postUrl);

        try {
            // Add your data
            List<NameValuePair> postFields = new ArrayList<NameValuePair>(2);
            for (BasicNameValuePair nameValuePair : valuePairs) {
                postFields.add(nameValuePair);
            }
            httppost.setEntity(new UrlEncodedFormEntity(postFields));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            responseStr = EntityUtils.toString(response.getEntity());
            Log.e("POST_REQUEST", "RESPONSE_CODE: " + response.getStatusLine().getStatusCode() + "");
        } catch (ClientProtocolException e) {
            Log.e("ClientProtocolException", e.getMessage().toString());
        } catch (IOException e) {
            Log.e("IOException", e.getMessage().toString());
        }

        return responseStr;
    }

    /**
     * Sends get request to sepcified URL.
     * @param getUri
     * @return
     */
    public static String getRequest(final String getUrl) {
        String responseStr = null;

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        HttpClient httpclient = new DefaultHttpClient();
        Log.e("GET_REQUEST", "ACTION REQUEST");

        try {
            // Execute HTTP Post Request
            HttpGet request = new HttpGet();
            request.setURI(new URI(getUrl));
            HttpResponse response = httpclient.execute(request);
            response.getStatusLine().getStatusCode();

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) != null) {
                sb.append(l + nl);
            }
            in.close();
            responseStr = sb.toString();
            Log.e("POST_REQUEST", "RESPONSE_STR: " + responseStr);
            Log.e("POST_REQUEST", "RESPONSE_CODE: " + response.getStatusLine().getStatusCode() + "");
        } catch (ClientProtocolException e) {
            Log.e("ClientProtocolException", e.getMessage().toString());
        } catch (IOException e) {
            Log.e("IOException", e.getMessage().toString());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return responseStr;
    }

    public static LicenseDataModel requestForDriverDetail(String licenseNum) {
        Gson gson = new Gson();
        LicenseDataModel licenseInfo = null;
        try {
            JSONObject licensesJSONList = new JSONObject(Utilities.getRequest(Constants.API_LICENSES));
            ArrayList<LicenseDataModel> licensesArrayList = gson.fromJson(licensesJSONList.getString("data"),
                    new TypeToken<ArrayList<LicenseDataModel>>() {
                    }.getType());
            for (LicenseDataModel licenseDataModel : licensesArrayList) {
                if (licenseNum.equals(licenseDataModel.license_num)) {
                    licenseInfo = licenseDataModel;
                }
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return licenseInfo;
    }

    public static String getDeviceUID(Context context) {
        String uid = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
        return uid;
    }

    public static void writeToFileViolationListJSON() {
        String violationJSONList = getRequest(Constants.API_VIOLATIONS);
        File currentConfig = new File(Constants.EXTERNAL_DIRECTORY + "/" + Constants.FILENAME_VIOLATION_JSON);
        try {
            currentConfig.createNewFile();
            FileOutputStream fos = new FileOutputStream(currentConfig);
            fos.write(violationJSONList.getBytes());
            fos.close();
        } catch (IOException e) {
            Log.e("ERROR CREATING JSON FILE", e.getMessage().toString());
        }
    }

    public static ArrayList<ViolationDataModel> readViolationJSONFileToArray() {
        ArrayList<ViolationDataModel> violation = new ArrayList<ViolationDataModel>();
        Gson gson = new Gson();
        String jsonStr = "";
        try {
            File jsonFile = new File(Constants.EXTERNAL_DIRECTORY + "/" + Constants.FILENAME_VIOLATION_JSON);

            if (!jsonFile.exists()) {
                Log.e("VIOLATION_JSON_LIST", "Error reading file");
            } else {
                Log.e("readJsonFile", "File Found");
            }

            FileInputStream stream = new FileInputStream(jsonFile);
            try {
                FileChannel fc = stream.getChannel();
                MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                jsonStr = Charset.defaultCharset().decode(byteBuffer).toString();
            } finally {
                stream.close();
            }
        } catch (Exception e) {
            Log.e("readJsonFile", e.getMessage());
        }

        try {
            JSONObject jsonContent = new JSONObject(jsonStr);
            violation = gson.fromJson(jsonContent.getString("data"),
                    new TypeToken<ArrayList<ViolationDataModel>>() {
                    }.getType());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("Error GSON", e.getMessage().toString());
        }
        return violation;
    }
}