clummy.classes.DataHandlingClass.java Source code

Java tutorial

Introduction

Here is the source code for clummy.classes.DataHandlingClass.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package clummy.classes;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.text.WordUtils;
import org.paukov.combinatorics.Factory;
import org.paukov.combinatorics.Generator;
import org.paukov.combinatorics.ICombinatoricsVector;

/**
 *
 * @author Syariffudin <syariffudinsapri@gmail.com>
 */
public class DataHandlingClass {

    static int totalListFromName = 0;
    private final Random random = new Random();
    final String MALE_GENDER_LONG = "Male";
    final String FEMALE_GENDER_LONG = "Female";
    final String MALE_GENDER_SHORT = "M";
    final String FEMALE_GENDER_SHORT = "F";

    public static boolean configStored = false;
    public static boolean firstTimeSetting = true;
    public static int dateFormatSelectedConfig = -1;
    public static int dateSeperatorSelectedConfig = -1;
    public static int genderFormatSelectedConfig = -1;
    public static int minMaxScore[] = { 1, 1000 };
    public static int minMaxDOB[] = { 1910, 2010 };

    /**
     * levelScore[0]=low
     * levelScore[1]=moderate
     * levelScore[2]=High
     * levelScore[3]=Extreme
     */
    public static int levelScore[] = { 0, 0, 0, 0 };

    public static String dateFormat = "DDMMYYYY";
    public static String dateSeperator = "/";
    public static String genderFormat = "MaFe";

    DefaultList defaultList;

    public DataHandlingClass() {
        defaultList = new DefaultList();
    }

    /**
     * set the level score default
     */
    public static void setLevelToScoreDefaultValues() {
        if (DataHandlingClass.levelScore[0] == 0 & DataHandlingClass.levelScore[1] == 0
                & DataHandlingClass.levelScore[2] == 0 & DataHandlingClass.levelScore[3] == 0) {
            for (int i = 0; i < 4; i++)
                DataHandlingClass.levelScore[3 - i] = (DataHandlingClass.minMaxScore[1] / (2 + i));
        }
    }

    /**
     * get only the country name
     * @param strg
     * @return 
     */
    public String getCountryName(String strg) {
        return strg.substring(0, strg.indexOf("="));
    }

    /**
     * return the ISO3166-1-Alpha-2
     * @param strg
     * @return 
     */
    public String getISO3166_1_Alpha_2(String strg) {
        strg = strg.substring(strg.indexOf("=") + 1);
        return strg.substring(0, strg.indexOf("+"));
    }

    /**
     * return the ISO3166-1-Alpha-3
     * @param strg
     * @return 
     */
    public String getISO3166_1_Alpha_3(String strg) {
        strg = strg.substring(strg.indexOf("+") + 1);
        return strg.substring(0, strg.indexOf("|"));
    }

    /**
     * return Dial Country Number
     * @param strg
     * @return 
     */
    public String getDialCountryNumber(String strg) {
        strg = strg.substring(strg.indexOf("|") + 1);
        return strg.substring(0, strg.indexOf("~"));
    }

    /**
     * return currency_alphabetic_code
     * @param strg
     * @return 
     */
    public String getCurrencyAlphabeticCode(String strg) {
        strg = strg.substring(strg.indexOf("~") + 1);
        return strg.substring(0, strg.indexOf(":"));
    }

    /**
     * return the currency Name
     * @param strg
     * @return 
     */
    public String getCurrencyName(String strg) {
        strg = strg.substring(strg.indexOf(":") + 1);
        return strg.substring(0, strg.indexOf("*"));
    }

    /**
     * return is_independent
     * @param strg
     * @return 
     */
    public String getIsIndependent(String strg) {
        return strg.substring(strg.lastIndexOf("*") + 1);
    }

    /**
     * to compare between 2 string
     * @param str1
     * @param str2
     * @return 
     */
    public boolean compString(String str1, String str2) {
        return str1.equalsIgnoreCase(str2);
    }

    /**
     * get the ISO3166_1_Alpha_2 from list on matched country
     * @param CountryName
     * @return 
     */
    public String getISOAlpha2FromList(String CountryName) {
        List<String> list = defaultList.getAllCountryDetailList();
        for (int i = 0; i < list.size(); i++)
            if (compString(CountryName, getCountryName(list.get(i)))) {
                return getISO3166_1_Alpha_2(list.get(i));
            }
        return "N/A";
    }

    /**
     * get the ISO3166_1_Alpha_3 from list on matched country
     * @param CountryName
     * @return 
     */
    public String getISOAlpha3FromList(String CountryName) {
        List<String> list = defaultList.getAllCountryDetailList();
        for (int i = 0; i < list.size(); i++)
            if (compString(CountryName, getCountryName(list.get(i)))) {
                return getISO3166_1_Alpha_3(list.get(i));
            }
        return "N/A";
    }

    /**
     * get the Currency Code from list on matched country
     * @param CountryName
     * @return 
     */
    public String getCurrencyCodeFromList(String CountryName) {
        List<String> list = defaultList.getAllCountryDetailList();
        for (int i = 0; i < list.size(); i++)
            if (compString(CountryName, getCountryName(list.get(i)))) {
                return getCurrencyAlphabeticCode(list.get(i));
            }
        return "N/A";
    }

    /**
     * to get the other name from full name
     * @param fullname
     * @return 
     */
    public String getFirstNameAndLastNameInitial(String fullname) {
        fullname = fullname.substring(0, fullname.indexOf(" ") + 2);
        fullname = fullname + ".";
        return fullname;
    }

    /**
     * return different name from fullname by changing the vowels
     * @param fullname
     * @return 
     */
    public String getDifferentNameFromFullName(String fullname) {
        String str = fullname.toLowerCase();
        char[] vowel = { 'a', 'e', 'i', 'o', 'u', 'y' };
        char[] alphabetWithoutVowel = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's',
                't', 'v', 'w', 'x', 'z' };
        for (int i = 0; i < str.length(); i++) {
            str = str.replace(vowel[randBetween(0, (vowel.length) - 1)], vowel[randBetween(0, (vowel.length) - 1)]);
            //if(random.nextBoolean()){
            try {
                str = str.replace(alphabetWithoutVowel[randBetween(0, (alphabetWithoutVowel.length) - 1)],
                        alphabetWithoutVowel[randBetween(0, (alphabetWithoutVowel.length) - 1)]);
            } catch (Exception e) {
            }
        }
        //}
        return WordUtils.capitalize(str);
    }

    /**
     * get the Currency Name from list on matched country
     * @param CountryName
     * @return 
     */
    public String getCurrencyNameFromList(String CountryName) {
        List<String> list = defaultList.getAllCountryDetailList();
        for (int i = 0; i < list.size(); i++)
            if (compString(CountryName, getCountryName(list.get(i)))) {
                return getCurrencyName(list.get(i));
            }
        return "N/A";
    }

    /**
     * get the Independent from list on matched country
     * @param CountryName
     * @return 
     */
    public String getInDependentFromList(String CountryName) {
        List<String> list = defaultList.getAllCountryDetailList();
        for (int i = 0; i < list.size(); i++)
            if (compString(CountryName, getCountryName(list.get(i)))) {
                return getIsIndependent(list.get(i));
            }
        return "N/A";
    }

    /**
     * get and generate phone number base on country
     * @param countryName
     * @return 
     */
    public String getRandomPhoneNumberByCountry(String countryName) {
        List<String> list = defaultList.getAllCountryDetailList();
        String phone = null;
        DecimalFormat df3 = new DecimalFormat("000"); // 3 zeros
        DecimalFormat df4 = new DecimalFormat("0000");
        int num1 = 0, num2 = 0, num3 = 0;
        for (int i = 0; i < list.size(); i++) {
            if (countryName.equalsIgnoreCase((getCountryName(list.get(i))))) {
                phone = getDialCountryNumber(list.get(i));
                num1 = randBetween(0, 999);
                num2 = randBetween(0, 9999);
                num3 = randBetween(0, 9999);
                phone = phone + "-" + df3.format(num1) + df4.format(num2) + df4.format(num3);
                break;
            }
        }
        if (phone != null)
            return phone;
        else
            return "N/A";
    }

    /**
     * to permutate the list into unique combination of list
     * @param filesToRead
     * @return 
     */
    public List<String> getPermutationOfNames(String filesToRead) {
        List<String> listNames = new ArrayList<>();
        ICombinatoricsVector<String> initialVector = Factory.createVector(readFile(filesToRead));
        // Create a simple combination generator to generate 3-combinations of the initial vector
        Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 2);

        // Print all possible combinations in vector
        for (ICombinatoricsVector<String> combination : gen) {
            //transfer vector to list and trim unessacry characters
            listNames.add(
                    combination.getVector().toString().replace(",", "").replace("[", "").replace("]", "").trim());

        }
        //shuffle the list
        Collections.shuffle(listNames);
        Collections.shuffle(listNames);
        totalListFromName = listNames.size();
        System.out.println(listNames);
        return listNames;
    }

    /**
     * get level by comparing with score
     * @param score
     * @return 
     */
    public String getScoreCompareLevel(int score) {
        if (score <= DataHandlingClass.levelScore[0])
            return "Low";
        else if (score > DataHandlingClass.levelScore[0] & score <= DataHandlingClass.levelScore[1])
            return "Moderate";
        else if (score > DataHandlingClass.levelScore[1] & score <= DataHandlingClass.levelScore[2])
            return "High";
        else
            return "Extreme";
    }

    /**
     * return list of domain names in string
     * @param firstname
     * @param lastname
     * @return 
     */
    public String getEmailAddress(String firstname, String lastname) {
        firstname.replaceAll("\\s+", "");
        lastname.replaceAll("\\s+", "");
        String divider = null;
        List<String> listDomainNames = defaultList.getListOfEmailDomain();
        Collections.shuffle(listDomainNames);
        Collections.shuffle(listDomainNames);
        switch (randBetween(1, 3)) {
        case 1:
            divider = ".";
            break;
        case 2:
            divider = "_";
            break;
        case 3:
            divider = "";
            break;
        case 4:
            if (random.nextBoolean())
                divider = randBetween(0, 999) + "";
            break;
        }
        if (random.nextBoolean())
            if (random.nextBoolean())
                if (random.nextBoolean())
                    lastname = lastname + randBetween(0, 999);
        return (firstname + divider + lastname + "@"
                + listDomainNames.get(randBetween(0, listDomainNames.size() - 1))).toLowerCase().replaceAll("\\s+",
                        "");
    }

    /**
     * get shuffle list of occupation
     * @param age
     * @return 
     */
    public String getShuffledOccupation(int age) {
        List<String> listOccupation = readFile(AllFileList.OCCUPATIONLIST);
        Collections.shuffle(listOccupation);
        Collections.shuffle(listOccupation);
        if (age < 6)
            return "Unemployed";
        else if (age >= 7 && age <= 17) {
            return "Student";
        } else
            return listOccupation.get(randBetween(0, listOccupation.size() - 1));
    }

    /**
     * get shuffle list file 1
     * @param fileName
     * @return 
     */
    public String getShuffleListFile(String fileName) {
        List<String> listShuffle1 = readFile(fileName);
        if (!listShuffle1.isEmpty()) {
            Collections.shuffle(listShuffle1);
            Collections.shuffle(listShuffle1);
            return listShuffle1.get(randBetween(0, listShuffle1.size() - 1));
        } else
            return null;
    }

    /**
     * get shuffled marital status from list
     * @param age
     * @return 
     */
    public String getShuffledMaritalString(int age) {
        List<String> maritalList = defaultList.getMaritalStatusList();
        Collections.shuffle(maritalList);
        Collections.shuffle(maritalList);
        if (age <= 17)
            return "Single";
        else {
            //this is to reduce people who are age and above to be single haha
            if (age > 65) {
                if (maritalList.get(randBetween(0, maritalList.size() - 1)).equalsIgnoreCase("Single")) {
                    if (random.nextBoolean())
                        if (random.nextBoolean())
                            if (random.nextBoolean())
                                if (random.nextBoolean())
                                    if (random.nextBoolean())
                                        if (random.nextBoolean())
                                            return maritalList.get(randBetween(0, maritalList.size() - 1));
                }
            }
            Collections.shuffle(defaultList.getMaritalStatusListWitoutSingle());
            return defaultList.getMaritalStatusListWitoutSingle()
                    .get(randBetween(0, defaultList.getMaritalStatusListWitoutSingle().size() - 1));
        }
    }

    /**
     * a random yes or no
     * @return 
     */
    public String getYesNo() {
        if (random.nextBoolean())
            return "Yes";
        else
            return "No";
    }

    /**
     * the the blood type string shuffled
     * @return 
     */
    public String getShuffledBloodType() {
        List<String> bloodType = defaultList.getBloodTypeList();
        Collections.shuffle(bloodType);
        Collections.shuffle(bloodType);
        return bloodType.get(randBetween(0, bloodType.size() - 1));
    }

    /**
     * shuffle the list of address
     * @param filesToRead
     * @return 
     */
    public List<String> getShuffledListOfAddress(String filesToRead) {
        String temp;
        List<String> countries = readFile(AllFileList.ADDRESSLIST);
        Collections.shuffle(countries);
        while (countries.size() < totalListFromName) {
            temp = countries.get(randBetween(0, countries.size() - 1));
            if (temp.startsWith("[\\D]"))
                temp = temp.replaceFirst("[\\D]", String.valueOf(randBetween(100, 991)) + " ");
            else {
                switch (randBetween(1, 5)) {
                case 1:
                    if (temp.contains("Apartment"))
                        break;
                    else {
                        temp = "Apartment " + randBetween(1, 69) + " " + temp;
                        break;
                    }
                case 2:
                    temp = "Road " + randBetween(1, 69) + " " + temp;
                    break;
                case 3:
                    if (temp.contains("Level"))
                        break;
                    else {
                        temp = "Level " + randBetween(1, 234) + " " + temp;
                        break;
                    }
                case 4:
                    temp = "Street " + randBetween(1, 4244) + " " + temp;
                    break;
                case 5:
                    temp = "Highway " + randBetween(1, 69) + " " + temp;
                    break;
                }
            }
            countries.add(temp);
        }
        Collections.shuffle(countries);
        System.out.println(countries);
        return countries;
    }

    /**
     * get the list of race
     * @return 
     */
    public List<String> getListofRace() {
        String temp;
        List<String> racelist = readFile(AllFileList.RACELIST);
        while (racelist.size() < totalListFromName) {
            Collections.shuffle(racelist);
            Collections.shuffle(racelist);
            temp = racelist.get(randBetween(0, racelist.size() - 1));
            racelist.add(temp);
        }
        return racelist;
    }

    /**
     * get shuffle level
     * @return 
     */
    public String getShuffledLevel() {
        List<String> levelList = defaultList.getLevelList();
        Collections.shuffle(levelList);
        Collections.shuffle(levelList);
        return levelList.get(randBetween(0, levelList.size() - 1));
    }

    /**
     * get the list of gender
     * @return 
     */
    public List<String> getListOfGender() {
        ArrayList<String> genderList = new ArrayList<>();
        if (genderFormat.equalsIgnoreCase("MaFe")) {
            for (int i = 0; genderList.size() < totalListFromName; i++) {
                if (random.nextBoolean())
                    genderList.add(MALE_GENDER_LONG);
                else
                    genderList.add(FEMALE_GENDER_LONG);
            }
        } else {
            for (int i = 0; genderList.size() < totalListFromName; i++) {
                if (random.nextBoolean())
                    genderList.add(MALE_GENDER_SHORT);
                else
                    genderList.add(FEMALE_GENDER_SHORT);
            }
        }
        Collections.shuffle(genderList);
        return genderList;
    }

    /**
     * to read file by line and pass each line to arraylist
     * only read starting at the third line
     * @param fileName String
     * @return ArrayList
     */
    public static ArrayList<String> readFile(String fileName) {
        ArrayList<String> readList = new ArrayList<>();

        Scanner scan;
        try {
            scan = new Scanner(new FileReader(fileName));
            int lineCount = 0;
            while (scan.hasNextLine()) {
                lineCount++;
                if (lineCount <= 3)
                    scan.nextLine();
                if (lineCount >= 4)
                    readList.add(scan.nextLine());
            }
            scan.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
        }
        return readList;
    }

    /**
     * generate random date of birth
     * @return 
     */
    public String getDateOfBirth() {
        GregorianCalendar gc = new GregorianCalendar();

        int year = randBetween(DataHandlingClass.minMaxDOB[0], DataHandlingClass.minMaxDOB[1] - 1);

        gc.set(gc.YEAR, year);

        int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR));

        gc.set(gc.DAY_OF_YEAR, dayOfYear);

        int month = gc.get(gc.MONTH);
        if (month == 0)
            month = 1;
        if (dateSeperator.equals(" "))
            dateSeperator = "";
        if (dateFormat.equalsIgnoreCase("DDMMYYYY"))
            return String.format("%02d", gc.get(gc.DAY_OF_MONTH)) + dateSeperator + String.format("%02d", month)
                    + dateSeperator + gc.get(gc.YEAR);
        else if (dateFormat.equalsIgnoreCase("MMDDYYYY"))
            return String.format("%02d", month) + dateSeperator + String.format("%02d", gc.get(gc.DAY_OF_MONTH))
                    + dateSeperator + gc.get(gc.YEAR);
        else if (dateFormat.equalsIgnoreCase("YYYYDDMM"))
            return gc.get(gc.YEAR) + dateSeperator + String.format("%02d", gc.get(gc.DAY_OF_MONTH)) + dateSeperator
                    + String.format("%02d", month);
        else
            return gc.get(gc.YEAR) + dateSeperator + String.format("%02d", month) + dateSeperator
                    + String.format("%02d", gc.get(gc.DAY_OF_MONTH));
    }

    /**
     * return the age of received year
     * @param dobString
     * @return 
     * @throws java.lang.Exception 
     */
    public int getAgeOfDobOfReceivedYear(String dobString) throws Exception {
        DateFormat dateFormater;
        Date date;
        if (dateFormat.equalsIgnoreCase("DDMMYYYY")) {
            dateFormater = new SimpleDateFormat("dd" + dateSeperator + "MM" + dateSeperator + "yyyy");
        } else if (dateFormat.equalsIgnoreCase("MMDDYYYY")) {
            dateFormater = new SimpleDateFormat("MM" + dateSeperator + "dd" + dateSeperator + "yyyy");
        } else if (dateFormat.equalsIgnoreCase("YYYYDDMM")) {
            dateFormater = new SimpleDateFormat("yyyy" + dateSeperator + "dd" + dateSeperator + "MM");
        } else
            dateFormater = new SimpleDateFormat("yyyy" + dateSeperator + "MM" + dateSeperator + "dd");
        date = dateFormater.parse(dobString);
        Calendar dob = Calendar.getInstance();
        dob.setTime(date);
        Calendar today = Calendar.getInstance();
        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
        if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
            age--;
        } else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) {
            age--;
        }
        return age;
    }

    /**
     * generate list of DOB
     * @return 
     */
    public ArrayList<String> getListOfDateOfBirth() {
        ArrayList<String> dobList = new ArrayList<>();
        for (int i = 0; dobList.size() < totalListFromName; i++)
            dobList.add(getDateOfBirth());
        System.out.println("dob generated: " + dobList);
        return dobList;
    }

    /**
     * random between generator
     * @param start
     * @param end
     * @return 
     */
    public static int randBetween(int start, int end) {
        return start + (int) Math.round(Math.random() * (end - start));
    }

    /**
     * get the total generated data for list in names files.
     * @return 
     */
    public static int getTotalPossibility() {

        List<String> listNames = new ArrayList<>();
        ;
        ICombinatoricsVector<String> initialVector = Factory.createVector(readFile(AllFileList.NAMELIST));
        // Create a simple combination generator to generate 3-combinations of the initial vector
        Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 2);

        // Print all possible combinations in vector
        for (ICombinatoricsVector<String> combination : gen) {
            //transfer vector to list and trim unessacry characters
            listNames.add(
                    combination.getVector().toString().replace(",", "").replace("[", "").replace("]", "").trim());

        }
        //shuffle the list
        Collections.shuffle(listNames);
        return listNames.size();
    }
}