package com.ajb.common.utils.string;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	private static final String EMAIL_REGEX="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";//邮箱正则表达式
	/* 
	 * 日期格式：http://blog.csdn.net/linghu_java/article/details/38379603
	 *	yyyy-MM-dd HH:mm:ss:SSS 24小时制
	 *  yyyy-MM-dd hh:mm:ss:SSS	12小时制
	 */
	
	/**
	 * 日期转换成字符串
	 * @param source
	 * @param pattern 例如 yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String dateParseString(Date source,String pattern){
		if(source == null){
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(source);
	}
	
	/**
	 * 字符串转换成日期
	 * @param source
	 * @param pattern 例如 yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static Date stringParseDate(String source,String pattern){
		if(isNullOrBlank(source) || isNullOrBlank(pattern)){
			return null;
		}
		Date date = null;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			date = sdf.parse(source);
		} catch (ParseException e) {
			return null;
		}
		return date;
	}
	
	public static double doubleFormat(Double source,int num){
		if(source == null){
			source = 0d;
		}
		BigDecimal bd = new BigDecimal(source);  
		double result = bd.setScale(num,BigDecimal.ROUND_HALF_UP).doubleValue();
		return result;
	}
	
	public static String doubleParseString(Double source,String parten){
		if(source == null){
			source = 0d;
		}
		if(parten == null){
			parten = "##,###,###,##0.00";
		}
		DecimalFormat fmt = new DecimalFormat(parten);
		return fmt.format(source);
	}

	public static String longParseString(Long source,String parten){
		if(source == null){
			source = 0L;
		}
		if(parten == null){
			parten = "##,###,###,###";
		}
		DecimalFormat fmt = new DecimalFormat(parten);
		return fmt.format(source);
	}
	/**
	 * 空字符串付默认值
	 * @param source
	 * @param defaultValue
	 * @return
	 */
	public static String nullStringToDefault(String source,String defaultValue){
		String result = source;
		if(isNullOrBlank(source)){
			result = defaultValue;
		}
		return result;
	}
	public static Integer stringParseInt(String source){
		Integer result = null;
		if(isNullOrBlank(source)){
			return null;
		}else{
			try{
				result = Integer.parseInt(source);
			}catch(Exception e){}
		}
		return result;
	}
	public static Long stringParseLong(String source){
		Long result = null;
		if(isNullOrBlank(source)){
			return null;
		}else{
			try{
				result = Long.parseLong(source);
			}catch(Exception e){}
		}
		return result;
	}
	public static Double stringParseDouble(String source){
		Double result = null;
		if(isNullOrBlank(source)){
			return null;
		}else{
			try{
				result = Double.parseDouble(source);
			}catch(Exception e){}
		}
		return result;
	}
	
	public static boolean isNullOrBlank(String source){
		boolean result = false;
		if(source == null){
			result = true;
		}else if("".equals(source.trim())){
			result = true;
		}
		return result ;
	}
	public static String getClassType(Object source){
		String classType = "Integer";
		if(source == null){
			return null;
		}
		String className = source.getClass().getName();
		if(className.contains("java.lang.Integer")){
			classType = "Integer";
		}else if(className.contains("java.lang.Long")){
			classType = "Long";
		}else if(className.contains("java.lang.Double")){
			classType = "Double";
		}else if(className.contains("java.math.BigInteger")){
			classType = "BigInteger";
		}else if(className.contains("java.math.BigDecimal")){
			classType = "BigDecimal";
		}
		return classType;
	}
	
	public static Integer intValue(Object source){
		Integer result = null;
		if(source == null){
			return 0;
		}
		try{
			if("Integer".equals(getClassType(source))){
				result = ((Integer)source).intValue();
			}else if("BigInteger".equals(getClassType(source))){
				result = ((BigInteger)source).intValue();
			}else if("BigDecimal".equals(getClassType(source))){
				result = ((BigDecimal)source).intValue();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	
	public static boolean isNullOrZero(Object source){
		boolean result = false;
		if(source == null){
			result = true;
		}else{
			if("Integer".equals(getClassType(source))){
				int value = ((Integer)source).intValue();
				if(value == 0){
					result = true;
				}
			}else if("Long".equals(getClassType(source))){
				long value = ((Long)source).longValue();
				if(value == 0){
					result = true;
				}
			}else if("Double".equals(getClassType(source))){
				double value = ((Double)source).doubleValue();
				if(value == 0){
					result = true;
				}
			}else if("BigInteger".equals(getClassType(source))){
				double value = ((BigInteger)source).doubleValue();
				if(value == 0){
					result = true;
				}
			}else if("BigDecimal".equals(getClassType(source))){
				double value = ((BigDecimal)source).doubleValue();
				if(value == 0){
					result = true;
				}
			}
			
		}
		return result ;
	}

	/**
	 * 求时间差
	 * @param source 终止时间
	 * @param target 开始时间
	 * @param unit D天 H小时 M分 S秒 MS毫秒
	 * @return
	 */
	public static long getDatePeriod(Date source,Date target,String unit){
		long result = 0;
		long nd = 1000 * 24 * 60 * 60;
	    long nh = 1000 * 60 * 60;
	    long nm = 1000 * 60;
	    long ns = 1000;
	    long ms = 1;
	    // 获得两个时间的毫秒时间差异
	    long diff = source.getTime() - target.getTime();
	    /*
	    // 计算差多少天
	    long day = diff / nd;
	    // 计算差多少小时
	    long hour = diff % nd / nh;
	    // 计算差多少分钟
	    long min = diff % nd % nh / nm;
	    // 计算差多少秒//输出结果
	    long sec = diff % nd % nh % nm / ns;
	    //return day + "天" + hour + "小时" + min + "分钟";
		*/
	    if("D".equals(unit)){
	    	result = diff / nd;
	    }else if("H".equals(unit)){
	    	result = diff / nh;
	    }else if("M".equals(unit)){
	    	result = diff / nm;
	    }else if("S".equals(unit)){
	    	result = diff / ns;
	    }else if("MS".equals(unit)){
	    	result = diff / ms;
	    }
		return result;
	}
	/**
	 * 
	 * @param source
	 * @param operation	ADD或SUB
	 * @param unit	S秒 M分钟 H小时 D天 W周 Mon月 Y年
	 * @param number
	 * @return
	 */
	public static Date dateOperation(Date source,String operation,String unit,int number){
		Date result = null;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(source);
		int field = Calendar.SECOND;
		if("S".equals(unit)){
			field = Calendar.SECOND;
		}else if("M".equals(unit)){
			field = Calendar.MINUTE;
		}else if("H".equals(unit)){
			field = Calendar.HOUR_OF_DAY;
		}else if("D".equals(unit)){
			field = Calendar.DATE;
		}else if("W".equals(unit)){
			field = Calendar.WEEK_OF_MONTH;
		}else if("Mon".equals(unit)){
			field = Calendar.MONTH;
		}else if("Y".equals(unit)){
			field = Calendar.YEAR;
		}
		
		if("SUB".equals(operation)){
			calendar.add(field, -number);	
		}else{
			calendar.add(field, number);
		}
		result = calendar.getTime();
		return result;
	}

	/**
	 * 由出生日期获得年龄
	 * @param birthDay
	 * @return
	 * @throws Exception
	 */
    public static int getAge(Date birthDay){
    	int age = 0;
    	if(birthDay == null){
    		return 0;
    	}
    	try{
    		Calendar cal = Calendar.getInstance();
            if (cal.before(birthDay)) {
//                throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
            	return -1;
            }
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH);
            int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
            cal.setTime(birthDay);

            int yearBirth = cal.get(Calendar.YEAR);
            int monthBirth = cal.get(Calendar.MONTH);
            int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

            age = yearNow - yearBirth;
            if (monthNow <= monthBirth) {
                if (monthNow == monthBirth) {
                    if (dayOfMonthNow < dayOfMonthBirth){
                    	age--;
                    } 
                }else{
                    age--;
                }
            }
    	}catch(Exception e){}
        return age;
    }

	/**
	 * 根据异常对象获取异常堆栈字符串
	 * @param e
	 * @return
	 */
	public static String parseExceptionStack(Exception e){
		String exceptionStack = null;
		/*StringBuffer sbf = new StringBuffer();
		StackTraceElement[] stack = e.getStackTrace();
		StackTraceElement element = null;
		String message = e.toString();
		sbf.append(message+"\n");
		for(int i=0;i<stack.length;i++){
			element = stack[i];
			String fileName = element.getFileName();
			String methodName = element.getMethodName();
			String className = element.getClassName();
			int lineNumber = element.getLineNumber();
			String append = fileName+":"+lineNumber;
			boolean isNativeMethod = element.isNativeMethod();
			if(isNativeMethod){
				append = "Native Method";
			}
			sbf.append("	at "+className+"."+methodName+"("+append+")\n");
		}
		exceptionStack = sbf.toString();*/
		
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		
		exceptionStack = sw.toString();
		
		return exceptionStack;
	}
	
	public static boolean isValidDate(String source,String pattern) {
		boolean convertSuccess = true;
		if(isNullOrBlank(source)){
			return false;
		}
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		try {
			format.setLenient(false);
			format.parse(source);
		}catch(Exception e) {
			convertSuccess=false;
		} 
		return convertSuccess;
	}
	
	public static boolean  checkEmail(String email){
    	return Pattern.matches(EMAIL_REGEX, email.trim());  
	}
    
	/**
	 * 
	 * @param area 省份名、城市名、县名
	 * @param birthDay 出生日期，格式(19891019)
	 * @param gender 性别(范围：1-9，男：奇数，女：偶数)
	 * @param age 
	 * @return
	 */
	public static String createID(String area,String birthDay,String gender,Integer age){
		String idNo = null;
		String areaCode = null;
		String seqNo = getRandomNum(2)+"";		// (两位)顺序号，格式(00-99)
		Random random = new Random();

		String areaCodeFile = StringUtil.class.getResource("").getPath()+File.separator+"areaCode.txt";
		List<String> areaList = readFile(areaCodeFile, "UTF-8");
		
		if(area == null || "".equals(area)){
			String item = areaList.get(random.nextInt(areaList.size()) -1);
			areaCode = item.split("	")[0];
		}else{
			for(String item : areaList){
				if(item.contains(area)){
					areaCode = item.split("	")[0];
					break;
				}
			}
		}
		if(areaCode == null){areaCode = "110101";}
		if(birthDay == null || "".equals(birthDay)){
			if(age == null || age <= 0){
				int[] arr = new int[]{1,2,3,4};
				int a = arr[random.nextInt(4)];
				String ageStr = a+getRandomNum(1);
				age = Integer.parseInt(ageStr);
			}
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.YEAR, -age);

			int randomDay = 1+(int)(Math.random()*360);
			calendar.add(Calendar.DAY_OF_YEAR, -randomDay);

			birthDay = dateParseString(calendar.getTime(), "yyyyMMdd");
		}
		if(gender == null || "".equals(gender)){
			gender = getRandomNum(1)+"";
		}
        // 前17位要除以的数：7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
        int finalAreaCode = Integer.parseInt(areaCode.substring(0, 1)) * 7
                + Integer.parseInt(areaCode.substring(1, 2)) * 9
                + Integer.parseInt(areaCode.substring(2, 3)) * 10
                + Integer.parseInt(areaCode.substring(3, 4)) * 5
                + Integer.parseInt(areaCode.substring(4, 5)) * 8
                + Integer.parseInt(areaCode.substring(5, 6)) * 4;
        int finalBirthday = Integer.parseInt(birthDay.substring(0, 1)) * 2
                + Integer.parseInt(birthDay.substring(1, 2)) * 1
                + Integer.parseInt(birthDay.substring(2, 3)) * 6
                + Integer.parseInt(birthDay.substring(3, 4)) * 3
                + Integer.parseInt(birthDay.substring(4, 5)) * 7
                + Integer.parseInt(birthDay.substring(5, 6)) * 9
                + Integer.parseInt(birthDay.substring(6, 7)) * 10
                + Integer.parseInt(birthDay.substring(7, 8)) * 5;
        int NoIs = (Integer.parseInt(seqNo.substring(0, 1))) * 8
                + (Integer.parseInt(seqNo.substring(1, 2))) * 4;
        int sexNo = (Integer.parseInt(gender.substring(0, 1))) * 2;
        int checkCode = (finalAreaCode + finalBirthday + NoIs + sexNo) % 11;
        int finalCheckCode = 0;
        // 余数范围： 0 1 2 3 4 5 6 7 8 9 10
        // 余数对应的数：1 0 X 9 8 7 6 5 4 3 2
        // 计算出最终的校验码：finalCheckCode
        switch (checkCode) {
        case 0:
            finalCheckCode = 1;
            break;
        case 1:
            finalCheckCode = 0;
            break;
        case 2:
            finalCheckCode = -3;
            break;
        case 3:
            finalCheckCode = 9;
            break;
        case 4:
            finalCheckCode = 8;
            break;
        case 5:
            finalCheckCode = 7;
            break;
        case 6:
            finalCheckCode = 6;
            break;
        case 7:
            finalCheckCode = 5;
            break;
        case 8:
            finalCheckCode = 4;
            break;
        case 9:
            finalCheckCode = 3;
            break;
        case 10:
            finalCheckCode = 2;
            break;
        default:
            break;
        }
        // 区域编号(6位数)+出生日期(8位数)+顺序编号(2位数)+性别号(1位数)+校验码(1位数)=身份证号(18位数)
        String checkInd = null;
        if(finalCheckCode == -3){
        	checkInd = "X";
        }else{
        	checkInd = finalCheckCode+"";
        }
        idNo = areaCode + birthDay + seqNo + gender + checkInd;
		return idNo;
	}
	public static String createMail(){
		String mail = getRandomString(5)+"@163.com";
		return mail;
	}
	public static String createPhoneNo(){
		return "139"+getRandomNum(8);
	}
	
	public static String getRandomString(int length) { //length表示生成字符串的长度
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	}
	public static String getRandomNum(int length) { //length表示生成字符串的长度
	    String base = "0123456789";   
	    Random random = new Random();
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	 }
	public static String createName(){
		Random random=new Random(System.currentTimeMillis());
		/* 598 百家姓 */
		String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
				  "何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
				  "鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
				  "罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
				  "穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
				  "屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
				  "徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
				  "宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
				  "羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
				  "谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
				  "詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
				  "蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
				  "璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
				  "宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
				  "阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
				  "曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
				  "督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
				  "哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
				  "疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
				  "木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
				  "闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
				  "濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
				  "南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
				  "梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
				  "毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
		
		int index=random.nextInt(Surname.length-1);		
		String name = Surname[index]; //获得一个随机的姓氏
		
		/* 从常用字中选取一个或两个字作为名 */
		if(random.nextBoolean()){
			name+=getChinese()+getChinese();
		}else {
			name+=getChinese();
		}
//		System.out.println(name);
		return name;
	}
	
	public static String getChinese() {
		String str = null;
		int highPos, lowPos;
		Random random = new Random();
		highPos = (176 + Math.abs(random.nextInt(71)));//区码，0xA0打头，从第16区开始，即0xB0=11*16=176,16~55一级汉字，56~87二级汉字
		random=new Random();
		lowPos = 161 + Math.abs(random.nextInt(94));//位码，0xA0打头，范围第1~94列

		byte[] bArr = new byte[2];
		bArr[0] = (new Integer(highPos)).byteValue();
		bArr[1] = (new Integer(lowPos)).byteValue();
		try {
			str = new String(bArr, "GB2312");	//区位码组合成汉字
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
			return str;
	}
	
	public static void main(String[] args){
//		String idNo = createID("南部县", "19940929", "1", null);
		String idNo = createID("长丰县", null, "1", 31);
		System.out.println(idNo);
		System.out.println(IDcardValidator.isIdcardValid(idNo));
	}

    @SuppressWarnings("rawtypes")
	public static String currentIP(){
    	String currentIP = null;
		try {
			Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
	    	while (allNetInterfaces.hasMoreElements()){
	    		NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
	    		//System.out.println(netInterface.getName());
	    		Enumeration addresses = netInterface.getInetAddresses();
	    		while (addresses.hasMoreElements()){
	    			ip = (InetAddress) addresses.nextElement();
	    			if(ip != null && ip instanceof Inet4Address){
	    				if(currentIP == null){
	    					currentIP = "";
	    				}
	    				currentIP += ip.getHostAddress()+";";
//	    				System.out.println("本机的IP = " + currentIP);
	    			}
	    			if(ip != null && ip instanceof Inet6Address){
	    				if(currentIP == null){
	    					currentIP = "";
	    				}
	    				currentIP += ip.getHostAddress()+":";
	    			}
	    		}
	    	}
		} catch (SocketException e) {
			e.printStackTrace();
		}
    	return currentIP;
    }
    
    /**
     * 获取HttpServletRequest请求IP
     * @param request
     * @return
     */
	/*public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}*/
	
	@SuppressWarnings("rawtypes")
	public static void simpleObjectCopy(Object source,Object target){
    	if(source == null || target == null){	return;	}
    	
    	try {
	    	Method[] sourceMethods = source.getClass().getDeclaredMethods();
	    	for(Method smethod : sourceMethods){
	    		Class returnType = smethod.getReturnType();
	    		String sourceMethodName = smethod.getName();
	    		if(!returnType.getTypeName().equals("void") && sourceMethodName.startsWith("get")){
	    			Object[] paramArr = null;
	    			Object getValue = smethod.invoke(source,paramArr);
					if(getValue != null){
//						System.out.println("--------------in simpleObjectCopy returnType : "+returnType.getTypeName()+"	sourceMethodName="+sourceMethodName);
						Method[] targetMethods = target.getClass().getDeclaredMethods();
						for(Method tmethod : targetMethods){
							String targetMethodName = tmethod.getName();
							if(targetMethodName.equals("set"+sourceMethodName.substring(3))){
								Class[] parameterTypes = tmethod.getParameterTypes();
								if(parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].getTypeName().equals(returnType.getTypeName())){
//									System.out.println("--------------in simpleObjectCopy targetMethodName:"+targetMethodName);
									tmethod.invoke(target,getValue);
								}//set value
								break;
							}//set
						}//for targetMethod
					}//get value != null
	    		}//get
	    	}//for sourceMethod
    	} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    		e.printStackTrace();
		}
    }

	public static String getInputStreamContent(InputStream inputStream,String charset)throws Exception{
		String content = null;
		if(inputStream == null){
			return null;
		}
		if(charset == null ){
			charset = "UTF-8";
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,charset));// 为了进行一行读取操作
		StringBuilder buffer = new StringBuilder();
		String line = "";
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
		}
		content = buffer.toString();
	
		return content;
	}
	
	public static List<String> readFile(String fileName,String encoding){
		List<String> contents = new ArrayList<String>();
		File file = new File(fileName);
		FileInputStream fi = null;
		InputStreamReader ir = null;
		BufferedReader br = null;
		try {
			fi = new FileInputStream(file);
			ir = new InputStreamReader(fi,encoding);
			br = new BufferedReader(ir);
			while(br.ready()){
				String line = br.readLine();
				contents.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				fi.close();
				ir.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return contents;
	}

	public static void writeFile(List<String> contents,String fileName,boolean appending,String encoding){
		File file = new File(fileName);
		FileOutputStream fo = null;
		OutputStreamWriter or = null;
		BufferedWriter bw = null;
		try {
			fo = new FileOutputStream(file,appending);
			or = new OutputStreamWriter(fo,encoding);
			bw = new BufferedWriter(or);
			for(String line : contents){
				bw.write(line);
				bw.newLine();
			}
			bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				fo.close();
				or.close();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 判断是否是数字
	 */
	private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]*");
	public static boolean isNumeric(String str){ 
//		   Pattern pattern = Pattern.compile("[0-9]*"); 
//		   Matcher isNum = pattern.matcher(str);
		   Matcher numMatcher = NUMBER_PATTERN.matcher(str);
		   if( !numMatcher.matches() ){
		       return false; 
		   } 
		   return true; 
	}
	
	// 根据Unicode编码完美的判断中文汉字和符号
	 public static boolean isChinese(char c) {
	     Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
	     if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
	             || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
	             || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
	             || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
	         return true;
	     }
	     return false;
	 }
	 
	 public static Double calcuPersonalTAX(Double amount){
		 Double tax = 0d;
			if(amount <= 800){
				tax = 0.0d;
			}else if(800 < amount && amount <= 4000){
				tax = (amount - 800 ) * 0.2 ;
			}else if(4000 < amount && amount <= 25000){
				tax = amount * (1-0.2) * 0.2 ;
			}else if(25000 < amount && amount <= 62500){
				tax = amount * (1-0.2) * 0.3 -2000 ;
			}else if(62500 < amount){
				tax = amount * (1-0.2) * 0.4 - 7000 ;
			}
		 return tax;
	 }
	 
	 /**
	  * 判断字符串中是否含有数字
	  * @param content
	  * @return
	  */
	public static boolean hasDigit(String content) {
		boolean flag = false;
		Pattern pattern = Pattern.compile(".*\\d+.*");
		Matcher m = pattern.matcher(content);
		if (m.matches()) {
			flag = true;
		}
		return flag;
	}
}