<commit_before>package edu.rutgers.css.Rutgers.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.androidquery.callback.AjaxStatus;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;

import edu.rutgers.css.Rutgers.R;

/**
 * General helper methods & global variables for the app
 */
public final class AppUtils {

    private static final String TAG = "AppUtils";

    private static final String INSTALLATION = "INSTALLATION";
    private static String installID = null;

    private AppUtils() {}

    /**
     * Get (or create) UUID for the installation of this app.
     * @param context App context
     * @return UUID string
     */
    public synchronized static String getUUID(@NonNull Context context) {
        if(installID == null) {
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if(!installation.exists()) {
                    FileOutputStream out = new FileOutputStream(installation);

                    // Either recover UUID from Titanium app or generate a new one
                    String uuid = recoverTitaniumID(context);
                    if(uuid == null) uuid = UUID.randomUUID().toString();

                    out.write(uuid.getBytes());
                    out.close();
                }
                installID = readInstallationFile(installation);
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
                throw new RuntimeException(e);
            }
        }
        return installID;
    }

    /**
     * Read the UUID file
     * @param installation Installation file
     * @return Contents of file in string
     * @throws IOException
     */
    private static String readInstallationFile(@NonNull File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    /**
     * Attempt to read unique ID from Titanium database, if one is leftover from an older RUMobile
     * installation.
     * @return UUID as String if successful, null if not found.
     */
    private static String recoverTitaniumID(@NonNull Context context) {
        String result = null;

        try {
            SQLiteDatabase db = SQLiteDatabase.openDatabase(context.getDatabasePath("Titanium").getPath(), null, 0);

            // SELECT value FROM platform WHERE name = 'unique_machine_id' LIMIT 1
            String[] columns = {"value"};
            Cursor dbCursor = db.query("platform", columns, "name = 'unique_machine_id'",
                    null, null, null, null, "1");

            if(dbCursor.getCount() > 0) {
                dbCursor.moveToFirst();
                result = dbCursor.getString(dbCursor.getColumnIndex("value"));
                Log.i(TAG, "Recovered Titanium UUID: " + result);
            } else {
                Log.i(TAG, "Zero results");
            }

            db.close();
        } catch (SQLiteException e) {
            Log.w(TAG, e.getMessage());
        }

        return result;
    }

    /**
     * Determine if the current device is a tablet.
     * @param context App context
     * @return True if the running device is a tablet, false if not.
     */
    public static boolean isTablet(@NonNull Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * Close soft keyboard
     * @param activity App activity
     */
    public static void closeKeyboard(Activity activity) {
        if(activity != null && activity.getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * Create custom string from Ajax Status object.
     * @param status AjaxStatus object
     * @return Custom string describing status<commit_msg>Check if Titanium db exists before opening.<commit_after>package edu.rutgers.css.Rutgers.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.androidquery.callback.AjaxStatus;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;

import edu.rutgers.css.Rutgers.R;

/**
 * General helper methods & global variables for the app
 */
public final class AppUtils {

    private static final String TAG = "AppUtils";

    private static final String INSTALLATION = "INSTALLATION";
    private static String installID = null;

    private AppUtils() {}

    /**
     * Get (or create) UUID for the installation of this app.
     * @param context App context
     * @return UUID string
     */
    public synchronized static String getUUID(@NonNull Context context) {
        if(installID == null) {
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if(!installation.exists()) {
                    FileOutputStream out = new FileOutputStream(installation);

                    // Either recover UUID from Titanium app or generate a new one
                    String uuid = recoverTitaniumID(context);
                    if(uuid == null) uuid = UUID.randomUUID().toString();

                    out.write(uuid.getBytes());
                    out.close();
                }
                installID = readInstallationFile(installation);
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
                throw new RuntimeException(e);
            }
        }
        return installID;
    }

    /**
     * Read the UUID file
     * @param installation Installation file
     * @return Contents of file in string
     * @throws IOException
     */
    private static String readInstallationFile(@NonNull File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    /**
     * Attempt to read unique ID from Titanium database, if one is leftover from an older RUMobile
     * installation.
     * @return UUID as String if successful, null if not found.
     */
    private static String recoverTitaniumID(@NonNull Context context) {
        String result = null;

        File titaniumDB = context.getDatabasePath("Titanium");
        if(titaniumDB.exists()) {
            try {
                SQLiteDatabase db = SQLiteDatabase.openDatabase(titaniumDB.getPath(), null, 0);

                // SELECT value FROM platform WHERE name = 'unique_machine_id' LIMIT 1
                Cursor dbCursor = db.query("platform", new String[]{"value"}, "name = 'unique_machine_id'",
                        null, null, null, null, "1");

                if (dbCursor.getCount() > 0) {
                    dbCursor.moveToFirst();
                    result = dbCursor.getString(dbCursor.getColumnIndex("value"));
                    Log.i(TAG, "Recovered Titanium UUID: " + result);
                } else {
                    Log.i(TAG, "Zero results");
                }

                db.close();
            } catch (SQLiteException e) {
                Log.w(TAG, e.getMessage());
            }
        } else {
            Log.i(TAG, "No Titanium database found.");
        }

        return result;
    }

    /**
     * Determine if the current device is a tablet.
     * @param context App context
     * @return True if the running device is a tablet, false if not.
     */
    public static boolean isTablet(@NonNull Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * Close soft keyboard
     * @param activity App activity
     */
    public static void closeKeyboard(Activity activity) {
        if(activity != null && activity.getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * Create custom string from Ajax Status object.
     * @param status AjaxStatus object
     * @return Custom string describing status
{'fraction_non_alphanumeric': 0.09685277209392965, 'fraction_numerical': 0.0013641235506187276, 'mean_word_length': 2.4419852448021464, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5136784', 'n_tokens_mistral': 2736, 'n_tokens_neox': 2650, 'n_words': 734}