com.albert.util.StringUtilCommon.java Source code

Java tutorial

Introduction

Here is the source code for com.albert.util.StringUtilCommon.java

Source

package com.albert.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.text.MessageFormat;
import java.text.Normalizer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * String Utility Class
 * 
 * @author
 */
public class StringUtilCommon {

    private static Log log = LogFactory.getLog(StringUtilCommon.class);

    /**
     * Check if the string is empty.
     * 
     * @param str
     * @return boolean
     */
    public static boolean isEmpty(String str) {
        boolean isEmpty = false;
        if (str == null || str.trim().equals("")) {
            isEmpty = true;
        }
        return isEmpty;
    }

    /**
     * convert string to upper case.
     * 
     * @param str
     * @return String
     */
    public static String toUpperCase(String str) {
        String outStr = null;
        if (!isEmpty(str)) {
            outStr = str.toUpperCase();
        }
        return outStr;
    }

    /**
     * convert string to Integer.
     * 
     * @param str
     * @return Integer
     */
    public static Integer toInteger(String str) {
        Integer outInteger = null;
        if (!isEmpty(str)) {
            outInteger = Integer.valueOf(str);
        }
        return outInteger;
    }

    /**
     * convert string to Long.
     * 
     * @param str
     * @return Long
     */
    public static Long toLong(String str) {
        Long outInteger = null;
        if (!isEmpty(str)) {
            outInteger = Long.valueOf(str);
        }
        return outInteger;
    }

    /**
     * convert string to Short.
     * 
     * @param str
     * @return Short
     */
    public static Short toShort(String str) {
        Short outShort = null;
        if (!isEmpty(str)) {
            outShort = Short.valueOf(str);
        }
        return outShort;
    }

    /**
     * Check if the string is empty.
     * 
     * @param str
     * @return String
     */
    public static String trim(String str) {
        String returnValue = null;
        if (!isEmpty(str)) {
            returnValue = str.trim();
        }
        return returnValue;
    }

    /**
     * Check if all characters are digits.
     * 
     * @param str
     * @return boolean
     */
    public static boolean isNumerical(String str) {
        boolean isNumerical = true;
        if (!isEmpty(str)) {
            int i = 0;
            // ensure all characters are digits
            while (i < str.length()) {
                if (!Character.isDigit(str.charAt(i))) {
                    isNumerical = false;
                    break;
                }
                i++;
            }
        }
        return isNumerical;
    }

    /**
     * Left pad string with char c.
     * 
     * @param s
     * @param n
     * @param c
     * @return String
     */
    public static String lPad(String s, int n, char c) {
        if (s == null) {
            return s;
        }
        int add = n - s.length();
        if (add <= 0) {
            return s;
        }
        StringBuffer str = new StringBuffer(s);
        char[] ch = new char[add];
        Arrays.fill(ch, c);
        str.insert(0, ch);

        return str.toString();
    }

    /**
     * right pad string with char c.
     * 
     * @param s
     * @param n
     * @param c
     * @return String
     */
    public static String rPad(String s, int n, char c) {
        if (s == null) {
            return s;
        }
        int add = n - s.length();
        if (add <= 0) {
            return s;
        }
        StringBuffer str = new StringBuffer(s);
        char[] ch = new char[add];
        Arrays.fill(ch, c);
        str.append(ch);

        return str.toString();
    }

    /**
     * Check if all characters are alpha.
     * 
     * @param str
     * @return boolean
     * @see StringUtilTest
     */
    public static boolean isAlpha(String str) {
        //Pattern p = Pattern.compile("[a-zA-Z]* ");

        //dot is a regular express matter character, suggest to use "union" in regular express
        //MUST run StringUtilTest if any change happened.
        Pattern p = Pattern.compile("[a-zA-Z' -[\\.][,]]*");
        //String regex = "[\\p{L&}]+"; 
        // Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        boolean isValid = m.matches();
        return isValid;
    }

    /**
     * Check if the email address is valid.
     * 
     * @param email
     * @return boolean
     */
    public static boolean isValidEmail(String email) {
        // Set the email pattern string
        Pattern p = Pattern.compile(
                "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z]{2,}){1}$)");

        // Match the given string with the pattern
        Matcher m = p.matcher(email);

        // check whether match is found
        boolean isValid = m.matches();

        return isValid;
    }

    /**
     * Check if the zip code is valid.
     * 
     * @param postal
     * @return boolean
     */
    public static boolean isValidZipCode(String postal) {

        Pattern p = Pattern.compile("\\d{5}(-\\d{4})?");

        // Match the given string with the pattern
        Matcher m = p.matcher(postal);

        // check whether match is found
        boolean isValid = m.matches();

        return isValid;
    }

    /**
     * Check if the postal code is valid.
     * 
     * @param postal
     * @return boolean
     */
    public static boolean isValidPostalCode(String postal) {

        // Pattern p = Pattern.compile("[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d");
        Pattern p = Pattern.compile(
                "^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$");

        // Match the given string with the pattern
        Matcher m = p.matcher(postal);

        // check whether match is found
        boolean isValid = m.matches();

        return isValid;
    }

    /**
     * Check if the postal code is valid for ontario.
     * 
     * @param postal
     * @return boolean
     */
    public static boolean isValidONPostalCode(String postal) {
        // [ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d
        Pattern p = Pattern
                .compile("[KLMNP]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$");

        // Match the given string with the pattern
        Matcher m = p.matcher(postal);

        // check whether match is found
        boolean isValid = m.matches();

        return isValid;
    }

    /**
     * Check if the phone number is valid.
     * 
     * @param phone
     * @return boolean
     */
    public static boolean isValidPhoneNumber(String phone) {

        Pattern p = Pattern.compile("[1-9]\\d{2}[1-9]\\d{2}\\d{4}");
        // Pattern p =
        // Pattern.compile("\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})");

        // Match the given string with the pattern
        Matcher m = p.matcher(phone);

        // check whether match is found
        boolean isValid = m.matches();

        return isValid;
    }

    /**
     * Check if the phone number is within ontario.
     * 
     * @param phone
     * @return boolean
     */
    public static boolean isValidOntarioPhoneNo(String phone) {
        // Set the list of valid ontario area code
        List<String> ontarioAreaCodes = Arrays.asList("905", "613", "519", "226", "249", "705", "807", "416", "647",
                "365", "343", "289", "437");

        String areaCode = phone.substring(0, 3);

        boolean isValid = false;
        if (ontarioAreaCodes.contains(areaCode)) {
            isValid = true;
        }

        return isValid;
    }

    /**
     * Validate social insurance number
     * 
     * @param value
     * @return
     */
    public static boolean isValidSin(String value) {

        boolean isValid = true;
        int save = 0;

        if (isEmpty(value) || !isNumerical(value) || value.length() != 9) {
            isValid = false;
        } else {
            String firstDigit = value.substring(0, 1);
            if ("0".equals(firstDigit) || "8".equals(firstDigit)) {
                isValid = false;
            } else {
                int tmp = Integer.parseInt(value.substring(1, 2)) * 2;
                value = firstDigit + String.valueOf(tmp) + value.substring(2, value.length());
                if (tmp >= 9)
                    save += 1;

                tmp = Integer.parseInt(value.substring(3 + save, 3 + save + 1)) * 2;
                value = value.substring(0, 3 + save) + String.valueOf(tmp)
                        + value.substring(4 + save, value.length());
                if (tmp >= 9)
                    save += 1;

                tmp = Integer.parseInt(value.substring(5 + save, 5 + save + 1)) * 2;
                value = value.substring(0, 5 + save) + String.valueOf(tmp)
                        + value.substring(6 + save, value.length());
                if (tmp >= 9)
                    save += 1;

                tmp = Integer.parseInt(value.substring(7 + save, 7 + save + 1)) * 2;
                value = value.substring(0, 7 + save) + String.valueOf(tmp)
                        + value.substring(8 + save, value.length());

                int sum = 0;
                for (int i = 0; i < value.length(); i++) {
                    tmp = Integer.parseInt(value.substring(i, i + 1));
                    sum = sum + tmp;
                }

                if ((sum % 10) != 0) {
                    isValid = false;
                }
            }
        }

        return isValid;
    }

    /**
     * Get message from resource bundle
     * 
     * @param key
     * @param locale
     * @param bundleName
     * @param params
     * @return
     */
    public static String getMessage(String key, Locale locale, String bundleName, Object params[]) {

        String text = null;

        ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale);

        try {
            text = bundle.getString(key);
        } catch (Exception e) {
            text = key;
        }

        if (params != null) {
            MessageFormat mf = new MessageFormat(text, locale);
            text = mf.format(params, new StringBuffer(), null).toString();
        }

        return text;
    }

    /**
     * convert null to space
     * 
     * @param str
     * @return
     */
    public static String nullToSpace(String str) {
        String value = "";
        if (str != null && str.trim().length() > 0) {
            value = str.trim();
        }

        return value;
    }

    /**
     * Check if a string is a integer
     * 
     * @param string
     * @return boolean
     */
    public static boolean isInteger(String str) {
        return Pattern.matches("^\\d*$", str);
    }

    /**
     * Check if a string is a valid driver license
     * 
     * @param string
     *            -- 15 long licnese characters
     * @param aDate
     *            -- dob of driver
     * @return boolean
     */
    public static boolean isValidDriverLicense(Date aDate, String str) {
        boolean valid = false;
        valid = Pattern.matches("[a-zA-Z]\\d{12}(0[1-9]|[12][0-9]|3[01])", str);
        if (valid) {
            String strDate = DateUtilCommon.getDate(aDate);
            String str1011 = str.substring(9, 11); // 10th and 11th characters
            // -- year of driver's dob
            String str1415 = str.substring(13, 15);// 14th and 15th characters
            // -- day of driver's dob
            String dobdd = strDate.substring(3, 5);
            String dobyy = strDate.substring(8, 10);
            if (!dobdd.equals(str1415) || !dobyy.equals(str1011)) {
                valid = false;
            }
        }
        return valid;
    }

    /**
     * Check if characters are alpha and numeric only
     * 
     * @param str
     * @return boolean
     */
    public static boolean hasSpecialChars(String str) {
        Pattern p = Pattern.compile("[\\'?\\s-a-zA-Z0-9]*");
        Matcher m = p.matcher(str);
        boolean isValid = m.matches();
        return !isValid;
    }

    /**
     * PASSWORD MUST CONTAIN AT LEAST ONE DOGIT, ONE LOWER CASE LETTER AND ONE
     * UPPERCASE LETTER AND 8 OR MORE CHARACTERS
     * 
     * @param str
     * @return boolean
     */
    public static boolean isValidPwdChars(String str) {
        Pattern p = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$");
        Matcher m = p.matcher(str);
        boolean isValid = m.matches();

        return isValid;
    }

    public static boolean isZero(String str) {
        int zeroCount = 0;
        String tmp;
        // get ride of .
        tmp = str.replace(".", "");

        for (int i = 0; i < tmp.length(); i++) {
            if (tmp.charAt(i) == '0')
                zeroCount++;
        }
        if (zeroCount == tmp.length()) {
            return true;
        }
        return false;
    }

    /**
     * Convert current academic year. ex. 0910 => 2009-2010
     * 
     * @param academicYr
     * @return
     */
    public static String formatAcademicYear(String academicYr) {
        String rtnValue = null;
        String century1 = null;
        String century2 = null;

        if (!StringUtilCommon.isEmpty(academicYr) && academicYr.trim().length() == 4) {
            if (academicYr.compareTo("9091") >= 0) {
                century1 = "19";
                if ("9900".equals(academicYr)) {
                    century2 = "19";
                } else {
                    century2 = "19";
                }
            } else {
                century1 = "20";
                century2 = "20";
            }

            rtnValue = century1 + academicYr.substring(0, 2) + "-" + century2 + academicYr.substring(2);
        }

        return rtnValue;
    }

    /**
     * i.e  
     *    academicYr = 1112, offsetYears = 1  => return 1213
     *    academicYr = 1112, offsetYears = -4 => return 0708
     *   academicYr = "", offsetYears = 1     => return ""
     *   academicYr = null, offsetYears = 1  => return "" 
     * 
     * @param academicYr
     * @param offsetYears
     * @return
     */
    public static String calcAcademicYear(String academicYr, int offsetYears) {

        String rtnValue = null;
        String century1 = null;
        String century2 = null;

        if (StringUtilCommon.isEmpty(academicYr))
            return "";

        if (!StringUtilCommon.isEmpty(academicYr) && academicYr.trim().length() == 4) {
            if (academicYr.compareTo("9091") >= 0) {
                century1 = "19";
                if ("9900".equals(academicYr)) {
                    century2 = "19";
                } else {
                    century2 = "19";
                }
            } else {
                century1 = "20";
                century2 = "20";
            }

            String year1 = century1 + academicYr.substring(0, 2);
            String year2 = century2 + academicYr.substring(2);

            SimpleDateFormat df1 = new SimpleDateFormat("yyyy");
            SimpleDateFormat df2 = new SimpleDateFormat("yy");

            try {
                rtnValue = df2.format(DateUtilCommon.addYear(df1.parse(year1), offsetYears))
                        + df2.format(DateUtilCommon.addYear(df1.parse(year2), offsetYears));

                return rtnValue;
            } catch (ParseException e) {
                //should never happen
                throw new RuntimeException(e);
            }

        }

        return "";
    }

    public static String maskSin(String sin) {
        if (isEmpty(sin) || isEmpty(sin.trim()) || sin.equals("0")) {
            return null;
        } else {
            String last3Digit = sin.substring(6);
            String mask = "******";
            String maskedSin = mask.concat(last3Digit);
            return maskedSin;
        }

    }

    public static String maskDriverLicence(String dl) {
        if (isEmpty(dl) || isEmpty(dl.trim())) {
            return dl;
        } else {
            String last4Digit = dl.substring(11);
            String mask = "***********";
            String maskedDl = mask.concat(last4Digit);
            return maskedDl;
        }

    }

    /**
     * Check whether a given URL is internal to this application.
     * 
     * @param url
     * @return
     */
    // TODO: Current implementation is preliminary.
    public static boolean isInternalURL(String url) {

        return (!isEmpty(url) && url.indexOf(":") < 0);

    }

    /**
     * Convert string with accent to non accent one.
     * @param s
     * @return
     */
    public static String toStringSansAccent(String s) {

        if (isEmpty(s.trim())) {
            return s;
        }
        s = s.replaceAll("[]", "A");
        s = s.replaceAll("[]", "C");
        s = s.replaceAll("[]", "E");
        s = s.replaceAll("[]", "I");
        s = s.replaceAll("[]", "N");
        s = s.replaceAll("[]", "O");
        s = s.replaceAll("[]", "U");
        s = s.replaceAll("[]", "Y");
        s = s.replaceAll("[]", "a");
        s = s.replaceAll("[]", "c");
        s = s.replaceAll("[]", "e");
        s = s.replaceAll("[]", "i");
        s = s.replaceAll("[]", "n");
        s = s.replaceAll("[]", "o");
        s = s.replaceAll("[]", "u");
        s = s.replaceAll("[]", "y");
        return s;

    }

    /**
     * Convert string  to ascii .it returns ? for
     * non ascii characters
     * @param s
     * @return ascii format of s
     */
    public static String toAscii(String s) {

        String s1 = Normalizer.normalize(s, Normalizer.Form.NFKD);
        String regex = "[\\p{InCombiningDiacriticalMarks}]+";
        String s2 = "";
        try {
            s2 = new String(s1.replaceAll(regex, "").getBytes("ascii"), "ascii");
        } catch (UnsupportedEncodingException e) {
            log.error("toAscii failed: " + s, e);
            return s1;
        }

        return s2;

    }

    public static boolean isISO88593(String v) {
        if (v == null || v.length() == 0) {
            return true;
        }
        CharsetEncoder d = Charset.forName("ISO-8859-3").newEncoder();
        d.onMalformedInput(CodingErrorAction.REPORT);
        d.onUnmappableCharacter(CodingErrorAction.REPORT);
        try {
            ByteBuffer bb = d.encode(CharBuffer.wrap(v.toCharArray()));
            bb.toString();
        } catch (CharacterCodingException e) {
            return false;
        }
        return true;
    }

    public static String stackToString(Throwable cause) {
        if (cause == null)
            return "";
        try {
            //cause.printStackTrace();
            StringWriter sw = new StringWriter();
            cause.printStackTrace(new PrintWriter(sw));
            String stackTrace = sw.toString();
            return stackTrace;
        } catch (Exception e) {
            return cause.toString();
        }
    }

    /**
     * Determine if the given OEN passed the OEN verification rule.
     * @param oen
     * @return boolean
     */
    public static boolean isValidOenFormat(String oen) {
        String OEN_MASK = "0246813579135792468024680357913579146802468025791357913680246802479135791358024680246913579135702468";
        int MIN_OEN = 60000000;

        if (isEmpty(oen) || !isNumerical(oen) || oen.length() != 9 || Integer.parseInt(oen) < MIN_OEN) {
            return false;
        }

        int maskValue = 0;
        int checkDigit = 0;
        String oenNumber = oen;
        String[] oenGroup = null;

        oenGroup = oenNumber.split("(?<=\\G.{2})");

        for (int i = 0; i < 4; i++) {
            maskValue = maskValue
                    + Integer.parseInt(Character.toString(OEN_MASK.charAt((Integer.parseInt(oenGroup[i])))));
        }
        checkDigit = ((maskValue / 10 + 1) * 10) - maskValue;

        if (checkDigit == 10) {
            checkDigit = 0;
        }

        return (Integer.parseInt(oenGroup[oenGroup.length - 1]) == checkDigit);
    }
}