package com.winsun.tenpay.util;

import java.io.File;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.CharacterIterator;
import java.text.NumberFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    public static final String EMPTY_STRING = "";
    public static final String EMPTY_STRING_SP = "&nbsp;";

    public static String getNullToEmpty(String str) {
        if (str == null)
            return EMPTY_STRING;
        else
            return str;
    }

    public static String getNullToEmpty(Object str) {
        if (str == null)
            return EMPTY_STRING;
        else
            return str.toString();
    }

    public static String getNullToSpace(String str) {
        if (str == null)
            return EMPTY_STRING_SP;
        else
            return str;
    }

    //Replace null value to space and change '"' into String to HTML code '&quot;'
    public static String getNullToSpaceHTML(String str) {
        if (str == null)
            return EMPTY_STRING_SP;
        else {
            String strTmp = str.replaceAll("\"", "&quot;");
            strTmp = strTmp.replaceAll(">", "&gt;");
            strTmp = strTmp.replaceAll("<", "&lt;");
            return strTmp;
        }
    }

    //Replace null value to empty string and change '"' into String to HTML code '&quot;'
    public static String getNullToEmptyHTML(String str) {
        if (str == null)
            return EMPTY_STRING;
        else {
            String strTmp = str.replaceAll("\"", "&quot;");
            strTmp = strTmp.replaceAll(">", "&gt;");
            strTmp = strTmp.replaceAll("<", "&lt;");
            return strTmp;
        }
    }

    public static String getNullToEmptyHTML(Object obj) {
        if (obj == null)
            return EMPTY_STRING;
        else
            return getNullToEmptyHTML(obj.toString());
    }

    //Check the string contains numeric or not
    public static boolean isNumber(String str) {
        boolean result = true;
        try {
            Integer.parseInt(str.trim());
        } catch(NumberFormatException e) {
            result = false;
        }
        return result;
    }

    public static String[] splitString(String str) {
        if (str == null || str.length() == 0)
            return new String[0];
        Pattern p = Pattern.compile(",");
        return p.split(str);
    }

    public static String[] splitString(String str, String delim) {
        String ls_delim = ",";
        if (str == null || str.length() == 0)
            return new String[0];
        if (delim != null && delim.length() > 0)
            ls_delim = delim;
        Pattern p = Pattern.compile("[" + ls_delim + "]");
        return p.split(str);
    }

    public static String concatString(String[] str) {
        if (str == null)
            return "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            if (i > 0)
                sb.append(",");
            sb.append(str[i]);
        }
        return sb.toString();
    }
    
    public static String concatString(String[] str, String delim) {
        if (str == null)
            return "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            if (i > 0)
                sb.append(delim);
            sb.append(str[i]);
        }
        return sb.toString();
    }

    public static String padTailZero(String as_input, int ai_len) {
        String ls_result = as_input;
        if (ls_result == null)
            return ls_result;
        while (ls_result.trim().length() < ai_len) {
            ls_result = ls_result + "0";
        }
        return ls_result;
    }
    
    
    public static String padZero(String as_input, int ai_len) {
        String ls_result = as_input;
        if (ls_result == null)
            return ls_result;
        while (ls_result.trim().length() < ai_len) {
            ls_result = "0" + ls_result;
        }
        return ls_result;
    }

    public static String getStrPrefix(String aStr, int prefixPos) {
        String result = "";

        if (aStr == null || aStr.length() <= 0 || prefixPos <= 0 || prefixPos > aStr.length())
            return "";

        //Log.println("prefix str = " + aStr.substring(0, prefixPos));
        result = aStr.substring(0, prefixPos);
        return result;

    }

    public static String getStrSuffix(String aStr, int suffixPos) {
        String result = "";

        if (aStr == null || aStr.length() <= 0 || suffixPos <= 0 || suffixPos > aStr.length())
            return "";

        int pos = aStr.length() - suffixPos;
        //Log.println("suffix str = " + aStr.substring( pos ));		
        result = aStr.substring(pos);

        return result;

    }

    public static String getStrBody(String aStr, int prefixPos, int suffixPos) {
        String result = "";

        if (aStr == null || aStr.length() <= 0 || prefixPos < 0 || prefixPos > aStr.length() || suffixPos < 0 || suffixPos > aStr.length())
            return "";

        int pos = aStr.length() - suffixPos;
        //Log.println("body str = " + aStr.substring(prefixPos, pos ));		
        result = aStr.substring(prefixPos, pos);

        return result;

    }

    public static String leadZero(int innum, int size) {
        NumberFormat digitNF = NumberFormat.getInstance();
        digitNF.setMinimumIntegerDigits(size);
        digitNF.setMaximumIntegerDigits(size);
        digitNF.setGroupingUsed(false);
        return new String(digitNF.format(innum));
    }

    public static String leadZeroBigDecimal(BigDecimal innum, int size) {
        NumberFormat digitNF = NumberFormat.getInstance();
        digitNF.setMinimumIntegerDigits(size);
        digitNF.setMaximumIntegerDigits(size);
        digitNF.setGroupingUsed(false);
        return new String(digitNF.format(innum));
    }

    public static String spacePad(String instr, int size) {
        char[] pad = new char[size];
        Arrays.fill(pad, ' ');

        char[] strchar = null;
        if (instr == null)
            return new String(pad);
        else if (instr.trim().length() > size)
            strchar = instr.trim().substring(0, size).toCharArray();
        else
            strchar = instr.trim().toCharArray();

        System.arraycopy(strchar, 0, pad, 0, strchar.length);
        return new String(pad);

    }

    public static String zeroPad(String instr, int size) {
        char[] pad = new char[size];
        Arrays.fill(pad, '0');

        char[] strchar = null;
        if (instr == null)
            return new String(pad);
        else if (instr.trim().length() > size)
            strchar = instr.trim().substring(0, size).toCharArray();
        else
            strchar = instr.trim().toCharArray();

        System.arraycopy(strchar, 0, pad, 0, strchar.length);
        return new String(pad);

    }

    public static String padLeadSpace(String instr, int size) {
        char[] pad = new char[size];
        Arrays.fill(pad, ' ');

        char[] strchar = null;
        if (instr == null)
            return new String(pad);
        else if (instr.trim().length() > size)
            strchar = instr.trim().substring(0, size).toCharArray();
        else
            strchar = instr.trim().toCharArray();

        System.arraycopy(strchar, 0, pad, pad.length - strchar.length, strchar.length);
        return new String(pad);

    }

    public static String parseMsgString(String rawMessage, String replaceString) {

        StringBuffer result = new StringBuffer(rawMessage);
        int idx = 0;

        // replace %s with replaceString
        idx = result.toString().indexOf("%");
        while (idx > 0) {
            result = result.replace(idx, (idx + 1), replaceString);
            idx = result.toString().indexOf("%");
        }

        return result.toString();

    }

    public static String encode(byte[] raw) {
        StringBuffer encoded = new StringBuffer();
        for (int i = 0; i < raw.length; i += 3) {
            encoded.append(encodeBlock(raw, i));
        }
        return encoded.toString();
    }

    public static byte[] decode(String base64) {
        int pad = 0;
        for (int i = base64.length() - 1; base64.charAt(i) == '='; i--)
            pad++;
        int length = base64.length() * 6 / 8 - pad;
        byte[] raw = new byte[length];
        int rawIndex = 0;
        for (int i = 0; i < base64.length(); i += 4) {
            int block = (getValue(base64.charAt(i)) << 18) + (getValue(base64.charAt(i + 1)) << 12) + (getValue(base64.charAt(i + 2)) << 6) + (getValue(base64.charAt(i + 3)));
            for (int j = 0; j < 3 && rawIndex + j < raw.length; j++)
                raw[rawIndex + j] = (byte) ((block >> (8 * (2 - j))) & 0xff);
            rawIndex += 3;
        }
        return raw;
    }

    public static char[] encodeBlock(byte[] raw, int offset) {
        int block = 0;
        int slack = raw.length - offset - 1;
        int end = (slack >= 2) ? 2 : slack;
        for (int i = 0; i <= end; i++) {
            byte b = raw[offset + i];
            int neuter = (b < 0) ? b + 256 : b;
            block += neuter << (8 * (2 - i));
        }
        char[] base64 = new char[4];
        for (int i = 0; i < 4; i++) {
            int sixbit = (block >>> (6 * (3 - i))) & 0x3f;
            base64[i] = getChar(sixbit);
        }
        if (slack < 1)
            base64[2] = '=';
        if (slack < 2)
            base64[3] = '=';
        return base64;
    }

    public static char getChar(int sixBit) {
        if (sixBit >= 0 && sixBit <= 25)
            return (char) ('A' + sixBit);
        if (sixBit >= 26 && sixBit <= 51)
            return (char) ('a' + (sixBit - 26));
        if (sixBit >= 52 && sixBit <= 61)
            return (char) ('0' + (sixBit - 52));
        if (sixBit == 62)
            return '+';
        if (sixBit == 63)
            return '/';
        return '?';
    }

    public static int getValue(char c) {
        if (c >= 'A' && c <= 'Z')
            return c - 'A';
        if (c >= 'a' && c <= 'z')
            return c - 'a' + 26;
        if (c >= '0' && c <= '9')
            return c - '0' + 52;
        if (c == '+')
            return 62;
        if (c == '/')
            return 63;
        if (c == '=')
            return 0;
        return -1;
    }

    public static String combineString(String str1, String str2) {
        byte[] bstr1 = str1.getBytes();
        byte[] bstr2 = str2.getBytes();
        byte[] result = new byte[bstr1.length];
        for (int i = 0; i < bstr1.length; i++) {
            result[i] = (byte) (bstr1[i] | bstr2[i]);
        }
        return new String(result);
    }

    public static String addSQLEscapeCharactor(String inStr, String escapeChar) {
        StringBuffer outStrBuf = new StringBuffer();

        for (int i = 0; i < inStr.length(); i++) {
            if (inStr.charAt(i) == '\'') {
                outStrBuf.append("''");
            } else if (inStr.charAt(i) == '%') {
                outStrBuf.append(escapeChar).append("%");
            } else {
                outStrBuf.append(inStr.charAt(i));
            }
        }
        return outStrBuf.toString();
    }
    
    public static String replaceHTMLTagToSpecificString(String inStr, String replaceStr) {    	
    	StringBuffer outStrBuf = new StringBuffer();
    	for (int i = 0; i < inStr.length(); i++) {
    		//check again filterchars
    		if (inStr.substring(i, i+1).equalsIgnoreCase("<")) {
    			if (inStr.substring(i, i+3).toLowerCase().equalsIgnoreCase("<b>")) {
    				outStrBuf.append("");
    				i = i + 2;    				
    			} else if (inStr.substring(i, i+4).toLowerCase().equalsIgnoreCase("</b>")) {
    				outStrBuf.append("");
    				i = i + 3;    		
    			} else if (inStr.substring(i, i+3).toLowerCase().equalsIgnoreCase("<i>")) {
    				outStrBuf.append("");
    				i = i + 2;    		
    			} else if (inStr.substring(i, i+4).toLowerCase().equalsIgnoreCase("</i>")) {
    				outStrBuf.append("");
    				i = i + 3;    		
    			} else if (inStr.substring(i, i+4).toLowerCase().equalsIgnoreCase("<br>")) {
    				outStrBuf.append("");
    				i = i + 3;    		
    			} else if (inStr.substring(i, i+5).toLowerCase().equalsIgnoreCase("</br>")) {
    				outStrBuf.append("");
    				i = i + 4;    		
    			} else if (inStr.substring(i, i+3).toLowerCase().equalsIgnoreCase("<p>")) {
    				outStrBuf.append("");
    				i = i + 2;    		
    			} else if (inStr.substring(i, i+4).toLowerCase().equalsIgnoreCase("</p>")) {
    				outStrBuf.append("");
    				i = i + 3;    		
    			} else if (inStr.substring(i, i+3).toLowerCase().equalsIgnoreCase("<u>")) {
    				outStrBuf.append("");
    				i = i + 2;    		
    			} else if (inStr.substring(i, i+4).toLowerCase().equalsIgnoreCase("</u>")) {
    				outStrBuf.append("");
    				i = i + 3;    		
    			} else {
    				outStrBuf.append(inStr.substring(i, i+1));
    			}
    		} else {
    			outStrBuf.append(inStr.substring(i, i+1));
    		}
    	}
    	
    	return outStrBuf.toString();
    }
    

    public static String escapeNewline(String str) {
		//if use \r together, does not work properly for the input in event 
    	//detail html input
		String str1 = str;
		if ( str.indexOf( '\n' ) != -1
			 //|| str.indexOf( '\r' ) != -1  
			 ) {
			str1 = str.replaceAll("[\n]", "<br/>");
			//str1 = str.replaceAll("[\n\r]", "<br/>");
		}
		return str1;
	}

    public static String formatFilePath(String strValue) {    	
    	String strReturn = strValue;
    	if (strReturn.indexOf("/")>=0 && File.separator.equals("\\")) {
	    	while (strReturn.indexOf("/")>=0){
	    		strReturn = strReturn.replace("/", File.separator);
	    	}
    	}else if (strReturn.indexOf("\\")>=0 && File.separator.equals("/")) {
	    	while (strReturn.indexOf("\\")>=0){
	    		strReturn = strReturn.replace("\\", File.separator);
	    	}
    	}
		return strReturn;
    }
    
    public static String repeatStr(String strValue, int intRepeatCount){
    	StringBuffer bufReturn = new StringBuffer();
    	if (intRepeatCount<=0)
    		return "";
    	
    	for (int i=1;i<=intRepeatCount;i++){
    		bufReturn.append(strValue);
    	}
    	return bufReturn.toString();
    }
    
    public static String forHTML(String aText){
        final StringBuilder result = new StringBuilder();
        final StringCharacterIterator iterator = new StringCharacterIterator(aText);
        char character =  iterator.current();
        while (character != CharacterIterator.DONE ){
          if (character == '<') {
            result.append("&lt;");
          }
          else if (character == '>') {
            result.append("&gt;");
          }
          else if (character == '&') {
            result.append("&amp;");
         }
          else if (character == '\"') {
            result.append("&quot;");
          }
          else if (character == '\t') {
            addCharEntity(9, result);
          }
          else if (character == '!') {
            addCharEntity(33, result);
          }
          else if (character == '#') {
            addCharEntity(35, result);
          }
          else if (character == '$') {
            addCharEntity(36, result);
          }
          else if (character == '%') {
            addCharEntity(37, result);
          }
          else if (character == '\'') {
            addCharEntity(39, result);
          }
          else if (character == '(') {
            addCharEntity(40, result);
          }
          else if (character == ')') {
            addCharEntity(41, result);
          }
          else if (character == '*') {
            addCharEntity(42, result);
          }
          else if (character == '+') {
            addCharEntity(43, result);
          }
          else if (character == ',') {
            addCharEntity(44, result);
          }
          else if (character == '-') {
            addCharEntity(45, result);
          }
          else if (character == '.') {
            addCharEntity(46, result);
          }
          else if (character == '/') {
            addCharEntity(47, result);
          }
          else if (character == ':') {
            addCharEntity(58, result);
          }
          else if (character == ';') {
            addCharEntity(59, result);
          }
          else if (character == '=') {
            addCharEntity(61, result);
          }
          else if (character == '?') {
            addCharEntity(63, result);
          }
          else if (character == '@') {
            addCharEntity(64, result);
          }
          else if (character == '[') {
            addCharEntity(91, result);
          }
          else if (character == '\\') {
            addCharEntity(92, result);
          }
          else if (character == ']') {
            addCharEntity(93, result);
          }
          else if (character == '^') {
            addCharEntity(94, result);
          }
          else if (character == '_') {
            addCharEntity(95, result);
          }
          else if (character == '`') {
            addCharEntity(96, result);
          }
          else if (character == '{') {
            addCharEntity(123, result);
          }
          else if (character == '|') {
            addCharEntity(124, result);
          }
          else if (character == '}') {
            addCharEntity(125, result);
          }
          else if (character == '~') {
            addCharEntity(126, result);
          }
          else {
            //the char is not a special one
            //add it to the result as is
            result.append(character);
          }
          character = iterator.next();
        }
        return result.toString();
     }
    
    private static void addCharEntity(Integer aIdx, StringBuilder aBuilder){
        String padding = "";
        if( aIdx <= 9 ){
           padding = "00";
        }
        else if( aIdx <= 99 ){
          padding = "0";
        }
        else {
          //no prefix
        }
        String number = padding + aIdx.toString();
        aBuilder.append("&#" + number + ";");
      }

    public static String stripHTML(String content, int limit, String atag){
//		String temp= "<div><font size='1'><br/>1234567890><12345<br/><br/>6789012345<br/>1234567890&amp;</font></div>";

		
		  try{
			String temp=  content;

			int start = 0;
			int start2 = 0;
			int end = 0;
			int end2 = 0;
			

			String result= new String(temp);
			while (temp.indexOf(">") >-1 )
			{
				start = temp.indexOf("<");
				end += temp.indexOf(">");
				end2 = temp.indexOf(">");
				if (start>=0 && start<end2)
				{
					temp = temp.substring(end2+1, temp.length());
					end+=1;
				}
				else
				{
					result = ((0==end)?"":result.substring(0, end)) + "&gt;" + ((result.length()==end+1)?"":result.substring(end+1, result.length()));
					temp =result;
					end =0;
				}
			}
			
			
			temp = result;
			start = 0;
			start2 = 0;
			end = 0;
			end2 = 0;
			
			while (temp.indexOf("<") >-1 )
			{
				start = temp.indexOf("<");
				end = temp.indexOf(">");

				if ((start<end && (temp.substring(start+1, end).indexOf("<")>-1) ) || end==-1)
				{
					start2+=start;
					result = ((0==start2)?"":result.substring(0, start2)) + "&lt;" + ((result.length()==start2+1)?"":result.substring(start2+1, result.length()));
					temp =result;
					start2=0;
				}
				else if (start>=0 && start<end)
				{
					temp = temp.substring(end+1, temp.length());
					start2+=(end+1);
				}
			}
			
			
			temp = result;
//			System.out.println("---------------------------------result>" + result);
			
			start = 0;
			end = 0;
			int contentLength = 0;
			int totalLength = 0;

			if (!(temp.indexOf("<") >-1 && temp.indexOf(">") > -1 && temp.indexOf("<")<temp.lastIndexOf(">")))
				totalLength = result.length();
			else
			{
				while (temp.indexOf("<") >-1 && temp.indexOf(">") > -1 && temp.indexOf("<")<temp.lastIndexOf(">"))
				{
					start = temp.indexOf("<");
					end = temp.indexOf(">");
					
	
					contentLength += start;
					temp = temp.substring(end+1, temp.length());
					totalLength += start;
					
					if (contentLength > limit)
						break;
					totalLength += (end+1-start);
				}
				if (contentLength > limit)
				{
					contentLength -= start;
					totalLength -= start;
					totalLength += (limit-contentLength);
				}
				else if (temp.length()>0 && temp.length()+contentLength>limit)
					totalLength += (limit-contentLength);
			}
				
//			System.out.println("---------------------------------result>" + result.substring(0,totalLength));
			
			




			String temp2 = result.substring(0,totalLength);
			
			if (result.length() != temp2.length())
			{
				String lastChar = temp2.substring(temp2.length()-1, temp2.length());
			    Pattern regex = Pattern.compile("[a-zA-Z]");
			    Matcher regexMatcher = regex.matcher(lastChar);
			    
				while (regexMatcher.find())
				{
					lastChar = temp2.substring(temp2.length()-1, temp2.length());
					regexMatcher = regex.matcher(lastChar);
					temp2 = temp2.substring(0,temp2.length()-1);
				}
				if (lastChar.equals("&") )
					temp2 =temp2.substring(0,temp2.lastIndexOf("&"));
			}


//			System.out.println("---------------------------------temp2>" + temp2);
			
			String temp3 = temp2;
			
//			if (result.length() != temp3.length())
				temp3 += atag;

			List<String> tagList = new ArrayList<String>();
			while (temp2.indexOf("<") >-1 && temp2.indexOf(">") > -1)
			{
				start = temp2.indexOf("<");
				end = temp2.indexOf(">");
				if (temp2.substring(start, end).contains(" "))
				{
					tagList.add("</"+ temp2.substring(start+1, start+temp2.substring(start).indexOf(" ")) +">");
				}
				else
					tagList.add("</" +temp2.substring(start+1, end+1));
				temp2 = temp2.substring(end+1, temp2.length());
			}
			
			for (int i=tagList.size()-1;i>=0;i--)
			{
				if (result.contains((String)tagList.get(i)))
					temp3 += (String)tagList.get(i);
			}
			
			result = temp3;
			
//			System.out.println("---------------------------------result>" + result);
			return result;
			
			  }
		  catch(Exception e) {
//			  Log.error(e.getMessage());
			  return content;
		  }
      }

    public static boolean isBlank(String str) {
		return str == null || str.trim().length() < 1;
	}
    
    public static boolean isNotBlank(String str) {
    	return !isBlank(str);
    }
    
    public static String getBlankToNull(String str) {
    	if (isBlank(str)) {
    		return null;
    	} else {
    		return str;
    	}
    }
    
    public static String getNullToBlank(String str) {
    	if (isBlank(str)) {
    		return "";
    	} else {
    		return str;
    	}
    }

    public static String left(String string, int length) {
		if (isBlank(string) || length < 1) {
			return "";
		}
		if (string.length() <= length) {
			return string;
		}
		return string.substring(0, length);	
    }
    
    public static String right(String string, int length) {
		if (isBlank(string) || length < 1) {
			return "";
		}
		if (string.length() <= length) {
			return string;
		}
		return string.substring(string.length() - length);
	}
    
    public static boolean equal(String str1, String str2) {
    	if (str1 == null) {
    		return str2 == null;
    	} else {
    		return str1.equals(str2);
    	}
    }

	public static String toLowerCase(String str) {
		return str == null ? null : str.toLowerCase(Locale.ENGLISH);
	}
    
    public static int compareIgnoreCase(String str1, String str2) {
		return compare(toLowerCase(str1), toLowerCase(str2));
	}
    
//    public static int compareIgnoreCaseFirst(String str1, String str2) {
//		return CommonUtil.getFirstNonZero(compareIgnoreCase(str1, str2),
//				compare(toLowerCase(str1), toLowerCase(str2)));
//	}
    
    public static int compare(String str1, String str2) {
    	if (equal(str1, str2)) {
    		return 0;
    	} else if (str1 == null) {
    		return -1;
    	} else if (str2 == null) {
    		return 1;
    	} else {
    		// Both non-null
    		return str1.compareTo(str2);
    	}
    }
    
    public static String trimToEmpty(String str) {
		if (str == null) {
			return "";
		} else {
			return str.trim();
		}
	}

	public static List<String> splitAsList(String str, String pattern) {
		String[] strings = getNullToEmpty(str).split(pattern);
		if (strings == null) {
			strings = new String[0];
		}
		return Arrays.asList(strings);
	}
	
	public static List<String> splitAsListByCommas(String str) {
		return StringUtil.splitAsList(str, "\\s*,\\s*");
	}

	public static String join(Collection<String> strings, String delimiter) {
		StringBuilder builder = new StringBuilder();
		for (Iterator<String> it = strings.iterator(); it.hasNext();) {
			builder.append(it.next());
			if (it.hasNext()) {
				builder.append(delimiter);
			}
		}
		return builder.toString();
	}
    
    public static boolean isEmpty(String str) {
    	return str == null || str.length() < 1;
    }
    
    public static boolean isNotEmpty(String str) {
    	return !isEmpty(str);
    }
    
    public static String getBlankOrNullLiteralToEmpty(String str) {
    	if (isNullLiteral(str)) {
    		return "";
    	} else {
    		return trimToEmpty(str);
    	}
    }

	public static boolean isNullLiteral(String str) {
		return compareIgnoreCase(trimToEmpty(str), "null") == 0;
	}
    
    public static boolean isBlankOrNullLiteral(String str) {
    	return isBlank(str) || isNullLiteral(str);
    }
    
    public static boolean isNotBlankOrNullLiteral(String str) {
    	return !isBlankOrNullLiteral(str);
    }

    public static String randomString(int pwdLength) {
        StringBuffer scode = new StringBuffer();
        for (int i = 0; i < pwdLength; i++) {
            scode.append(randAChar(false, false, false));
        }
        return scode.toString();
    }
    
    public static String randomString_UpperOnly(int pwdLength) {
        StringBuffer scode = new StringBuffer();
        for (int i = 0; i < pwdLength; i++) {
            scode.append(randAChar(false, false, true));
        }
        return scode.toString();
    }
    
    public static String randNumberOnly(int pwdLength){
        StringBuffer scode = new StringBuffer();
        for (int i = 0; i < pwdLength; i++) {
            scode.append(randAChar(true, false, false));
        }
        return scode.toString();
    }
    
    private static char randAChar(boolean isNumberOnly, boolean isCharOnly, boolean isUpperOnly){
    	SecureRandom rd = new SecureRandom();
    	// 0-9	48-57
    	// A-Z	65-90
    	// a-z	97-122
    	int temp = -1;
    	
    	// number only
    	if(isNumberOnly){
    		temp = rd.nextInt(10)+48;
	    	
    	// char only
    	} else if(isCharOnly){
    		if(isUpperOnly){
	    		temp = rd.nextInt(26)+65;
    		}else{
            	temp = rd.nextInt(58)+65;
            	while(temp > 90 && temp < 97){
                	temp = rd.nextInt(58)+65;
            	}
	    	}
	    	
	    // number & char
    	} else {
    		if(isUpperOnly){
	        	temp = rd.nextInt(43)+48;
	        	while(temp > 57 && temp < 65){
		        	temp = rd.nextInt(43)+48;
	        	}
    		} else {
	        	temp = rd.nextInt(75)+48;
	        	while(temp > 57 && temp < 65 || temp > 90 && temp < 97){
	            	temp = rd.nextInt(75)+48;
	        	}
    		}
    	}
    	
    	return (char) temp;
    }
    
    public static List<String> removeStringFromList (List<String> list, List<String> toBeRemoved) {
    	if (toBeRemoved == null) 
    		return list;
    	for (int i=0; i<toBeRemoved.size(); i++) {
    		list.remove(toBeRemoved.get(i));
    	}
    	return list;
    }

	public static String searchReplace(String data, String find, String replace){
		StringBuffer sb = new StringBuffer();
		int a = 0,b;
		int findLength = find.length();
		while((b = data.indexOf(find,a)) != -1) {
			sb.append(data.substring(a,b));
			sb.append(replace);
			a = b + findLength;
		}
		if(a < data.length()) {
			sb.append(data.substring(a));
		}
		return sb.toString();
	}

}
