package com.yd.util;

/*import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
*/
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.*;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {
	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);
	}
	/**
	 * n年后
	 * @param current
	 * @param year
	 * @return
	 */
	public static Date afterYear(Date current,int year)
	{
		Calendar cal = Calendar.getInstance();
		cal.setTime(current);
		cal.add(Calendar.YEAR, year);//增加一年
		return cal.getTime();
	}
	/**
	 * 字符串转换成日期
	 * @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.toString());
		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 birthDay
	 * @return
	 * @throws Exception
	 */
    public static int getAge(Date birthDay,Date endDate){
    	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;
            }
            cal.setTime(endDate);
            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 = CommonUtil.class.getResource("").getPath()+File.separator+"areaCode.txt";
		System.out.println(areaCodeFile);
		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;
	}

    @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;
	 }
	 
	 /**
	  * 判断字符串中是否含有数字
	  * @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;
	}
	
	/**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
	public static final String DEFAULT_QUERY_REGEX = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
    public static boolean isSpecialCharacter(String str) {
        Pattern p = Pattern.compile(DEFAULT_QUERY_REGEX);
        Matcher m = p.matcher(str);
        return m.find();
    }
    /**
     * 通过ip地址获取该ip的实际地理地址
     * @param ip
     * @return
     *//*
    public static String getAddressByIP(String ip){ 
		String address = null;
		try{
		    URL url = new URL( "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip); 
		    URLConnection conn = url.openConnection(); 
		    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); 
		    String line = null; 
		    StringBuffer result = new StringBuffer(); 
		    while((line = reader.readLine()) != null){ 
		        result.append(line); 
		    } 
		    reader.close(); 
		    String ipInfo = result.toString();
		    IpToAddress ipToAddress = (IpToAddress) JsonUtil.jsonToObj(ipInfo, IpToAddress.class);
		    if (ipToAddress != null) {
		    	if("0".equals(ipToAddress.getCode())){
		    		String area = ipToAddress.getData().getCountry();
					if (area == null && "".equals(area)) {
						area = ipToAddress.getData().getArea();
					}
					String region = ipToAddress.getData().getRegion();
					String city = ipToAddress.getData().getCity();
					String isp = ipToAddress.getData().getIsp();
					address = area+"_"+region+"_"+city+"_"+isp;
		    	}
			}
		}
	    catch( IOException e){ 
           System.out.println( "获取失败！！！！");
        }
	   return address;
	}*/
    /**
     * 判断姓名(中文姓名和英文姓名)
     * @param idType 
     */
	public static boolean isConSpeCharacters(String str, Long idType) {
		if (idType==9) {
			if (str.replaceAll("^[\u3400-\u9fa5A-Za-z]+[\\s·/.,(（)）\u3400-\u9fa5A-Za-z]*[\u3400-\u9fa5A-Za-z）)]+$", "").length() == 0) {
				return false;
			}
		}else{
			if (str.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*[\\s·.]*", "").length() == 0) {
				return false;
			}
		}
		return true;
	}
	
	
	/**
     * 通过身份证号码获取出生日期、性别、年龄
     * @param certificateNo
     * @return 返回的出生日期格式：1990-01-01   性别格式：F-女，M-男
     */
	
	
	/**
	 * 通过身份证号码获取出生日期、性别、年龄
	 * @param certificateNo 身份证号码
	 * @param type  birthday -- 出生年月日     age--年龄   sex--性别
	 * @return 结果    sex--性别  1-男 2-女
	 */
    public static String getBirAgeSex(String certificateNo,String type) {
        String birthday = "";
        String age = "";
        String sexCode = "";
        String result = "";
        
        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag) return null;
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag) return null;
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {
            birthday = "19" + certificateNo.substring(6, 8) + "-"
                    + certificateNo.substring(8, 10) + "-"
                    + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
        } else if (flag && certificateNo.length() == 18) {
            birthday = certificateNo.substring(6, 10) + "-"
                    + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sexCode", sexCode);
        
        if ("birthday".equals(type)) {
			result = birthday;
		}else if("age".equals(type)){
			result = age;
		}else if("sex".equals(type)){
			if("F".equals(sexCode)){
				sexCode = "2";
			}else if ("M".equals(sexCode)) {
				sexCode = "1";
			}
			result = sexCode;
		}
        return result;
    }
    /**
	 * 根据属性，获取get方法
	 * @param ob 对象
	 * @param name 属性名
	 * @return
	 * @throws Exception
	 */
	public static Object getGetMethod(Object ob , String name){
		try {
			Method[] m = ob.getClass().getMethods();
			for(int i = 0;i < m.length;i++){
				if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
					return m[i].invoke(ob);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 根据属性，拿到set方法，并把值set到对象中
	 * @param obj 对象
	 * @param filedName 对象的class
	 * @param value 需要设置值得属性
	 */
	public static void setValue(Object obj,String filedName,Object value){
		filedName = getString(filedName);
		String methodName = "set" + filedName.substring(0,1).toUpperCase()+filedName.substring(1);
		try{
			Method method =  obj.getClass().getDeclaredMethod(methodName, new Class[]{obj.getClass().getDeclaredField(filedName).getType()});
			method.invoke(obj, new Object[]{getClassTypeValue(obj.getClass().getDeclaredField(filedName).getType(), value)});
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	/**
     * 通过class类型获取获取对应类型的值
     * @param typeClass class类型
     * @param value 值
     * @return Object
     */
	private static Object getClassTypeValue(Class<?> typeClass, Object value){
        if(typeClass == int.class  || value instanceof Integer){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == short.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == byte.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == double.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == long.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == String.class){
            if(null == value){
                return "";
            }
            return value;
        }else if(typeClass == boolean.class){
            if(null == value){
                return true;
            }
            return value;
        }else if(typeClass == BigDecimal.class){
            if(null == value){
                return new BigDecimal(0);
            }
            return new BigDecimal(value+"");
        }else {
            return typeClass.cast(value);
        }
    }
    /**
     * 处理字符串  如：  abc_dex ---> abcDex
     * @param str
     * @return
     */
    public static  String getString(String str){
    	if(str != null){
    		while(str.contains("_") || str.contains(" ")){
    			if(str.contains("_")){
    				int i = str.indexOf("_");
        			String str1 = str.charAt(i+1)+"";
        			str = str.substring(0, i)+str1.toUpperCase()+str.substring(i+2);
    			}
    			if(str.contains(" ")){
    				int i = str.indexOf(" ");
    				String str1 = str.charAt(i+1)+"";
        			str = str.substring(0, i)+str1.toUpperCase()+str.substring(i+2);
    			}
    		}
    	}
		if(str.endsWith("?") || str.endsWith("#")){
			str = str.substring(0, str.length()-2);
		}
		return str;
	}

    /**
	 * 姓名如果是英文，就全部转换为大写
	 * @param name
	 * @return
	 */
    public static String enNameToUp(String name) {
		String rightName = name;
		Pattern p = Pattern.compile(".*[a-zA-z].*");
		Matcher m = p.matcher(name);
		boolean isValid = m.matches();
		if(isValid){
			rightName = name.toUpperCase();
		}
		return rightName;
	}

    
    public static String getUTF8StringFromGBKString(String gbkStr) {  
        try {  
            return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");  
        } catch (UnsupportedEncodingException e) {  
            throw new InternalError();  
        }  
    }  
      
    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {  
        int n = gbkStr.length();  
        byte[] utfBytes = new byte[3 * n];  
        int k = 0;  
        for (int i = 0; i < n; i++) {  
            int m = gbkStr.charAt(i);  
            if (m < 128 && m >= 0) {  
                utfBytes[k++] = (byte) m;  
                continue;  
            }  
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));  
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));  
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));  
        }  
        if (k < utfBytes.length) {  
            byte[] tmp = new byte[k];  
            System.arraycopy(utfBytes, 0, tmp, 0, k);  
            return tmp;  
        }  
        return utfBytes;  
    }   
    /**
     * 获取最惠比平台的错误信息
     * @param insurerId	保险公司id，微信999，支付宝998，非第三方平台传null
     * @param errorCode	错误编码，如果传入insurerId，则为第三方的错误编码，相反，则为自定义的错误编码
     * @param insurerErrorMessage	错误信息，为第三方平台的错误信息，非第三方平台，传null
     * @param paramStr	参数信息
     * @return	list.get(0)=errorCode;list.get(1)=errorMessage
     */
    public static List<String> getZHBErrorInfo(Long insurerId,String errorCode,String insurerErrorMessage,String[] paramStr){
    	List<String> errorList = new ArrayList<String>();
    	String zhbErrorCode = null;
		String zhbErrorMessage = null;
    	if(!isNullOrBlank(errorCode)){
    		if(insurerId == null){
    			zhbErrorCode = errorCode;
    		}else {
    			zhbErrorCode = createZHBErrorCode(insurerId,errorCode);
    		}
    		zhbErrorMessage = readProperties("errortest.properties",zhbErrorCode);
    		if(!isNullOrBlank(zhbErrorMessage)){
    			if(zhbErrorMessage.contains("}{")){
    				String[] errorMessageInfoArr = zhbErrorMessage.split("\\}\\{");
    				zhbErrorMessage = errorMessageInfoArr[0];
    			}
    			if(paramStr.length > 0){
    				for (int i = 0; i < paramStr.length; i++) {
    					zhbErrorMessage = zhbErrorMessage.replace("{"+i+"}", paramStr[i]);
    				}
    			}
    		}else{
    			if(!isNullOrBlank(insurerErrorMessage)){
    				zhbErrorMessage = "错误信息待配置！！！！";
        			writeProperties("errortest.properties",zhbErrorCode,zhbErrorMessage+"}{"+insurerErrorMessage);
    			}
    		}
    	}else{
    		try {
				throw new Exception("errorCode不能为空！");
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	errorList.add(zhbErrorCode);
    	errorList.add(zhbErrorMessage);
    	return errorList;
    }
   
	/**
	 * 写properties文件
	 * @param fileName
	 * @param key
	 * @param value
	 * @throws Exception 
	 */
	public static void writeProperties(String fileName,String key,String value){
		FileInputStream fis = null;
		String file = null;
		BufferedReader bf = null;
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		Properties properties = new Properties();
		if(!isNullOrBlank(fileName)){
			file = "src\\main\\resources\\"+fileName;
			try {
				fis = new FileInputStream(file);
				bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
				properties.load(bf);
				properties.setProperty(key, value);
				fos = new FileOutputStream(file);
				bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
				properties.store(bw, "update");
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				if(bw != null){
					try {
						bw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(bf != null){
					try {
						bf.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(fis != null){
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(fos!= null){
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			try {
				throw new Exception("Properties的文件名不能为空！");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 读取properties文件
	 * @param fileName	文件名 （目录为{src\main\resources\fileName}）
	 * @param zhbErrorCode	properties的key值
	 * @return	properties的value值
	 * @throws Exception 
	 */
	public static String readProperties(String fileName,String zhbErrorCode){
		String errorMessage = null;
		FileInputStream fis = null;
		Properties properties = null;
		BufferedReader bf= null;
		String file = null;
		if(!isNullOrBlank(fileName)){
			file = "src\\main\\resources\\"+fileName;
			try {
				properties = new Properties();
				fis = new FileInputStream(file);
				bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
				properties.load(bf);
				errorMessage = properties.getProperty(zhbErrorCode);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(properties != null){
					properties = null;
				}
				if(fis != null){
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(bf != null){
					try {
						bf.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			try {
				throw new Exception("Properties的文件名不能为空！");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return errorMessage;
	}
	/**
	 * 生成最惠比的errorCode
	 * @param insurerId 保险公司id，微信999，支付宝998
	 * @param insurerCode 保险公errorCode
	 * @return 最惠比平台 errorCode
	 */
	private static String createZHBErrorCode(Long insurerId, String insurerCode) {
		String zhbErrorCode = null;
		if (insurerId<10) {
			zhbErrorCode = "900"+insurerId;
		}else if(insurerId<100){
			zhbErrorCode = "90"+insurerId;
		}else {
			zhbErrorCode = "9"+insurerId;
		}
		zhbErrorCode = zhbErrorCode+insurerCode;
		return zhbErrorCode;
	}
	/**
	 * 给手机加密
	 * @param mobileNo
	 * @return
	 */
	public static String encryptMobile(String mobileNo) {
		if (!isNullOrBlank(mobileNo) && mobileNo.length() == 11) {
			mobileNo = mobileNo.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
		}
		return mobileNo;
	}
	
	/**
	 * 用GET方法打开URL
	 * @param url
	 * @return
	 */
/*
	public static String transactionGet(String url) {
		String result = null;
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			*//**
             * 创建HttpClient对象
             *//*
			client = HttpClients.createDefault();
			*//**
			 * 创建URIBuilder
			 *//*
			URIBuilder uriBuilder = new URIBuilder(url);
			*//**
			 * 设置参数
			 *//*
//			List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
//			nameValuePairList.add(new BasicNameValuePair("param1", "value1"));
//			uriBuilder.addParameters(nameValuePairList);
			*//**
			 * 创建HttpGet
			 *//*
			HttpGet httpGet = new HttpGet(uriBuilder.build());
			*//**
			 * 设置请求头部编码
			 *//*
			httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
			*//**
			 * 设置返回编码
			 *//*
			httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
			*//**
			 * 请求服务
			 *//*
			response = client.execute(httpGet);
			*//**
			 * 获取响应吗
			 *//*
			int statusCode = response.getStatusLine().getStatusCode();
			if(200 == statusCode){
				*//**
				 * 获取返回对象
				 *//*
				HttpEntity entity = response.getEntity();
				*//**
				 * 通过EntityUitls获取返回内容
				 *//*
				result = EntityUtils.toString(entity,"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
*/


	//判断选择的日期是否是本周
	public static boolean isThisWeek(String time)
	{
		Calendar calendar = Calendar.getInstance();
		int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
		calendar.setTime(stringParseDate(time,"yyyy-MM-dd"));
		int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
		if(paramWeek==currentWeek){
			return true;
		}
		return false;
	}
	//判断选择的日期是否是今天
	public static boolean isToday(String time)
	{
		return isThisTime(time,"yyyy-MM-dd");
	}
	//判断选择的日期是否是本月
	public static boolean isThisMonth(String time)
	{
		return isThisTime(time,"yyyy-MM");
	}
	public static boolean isThisYear(String time)
	{
		return isThisTime(time,"yyyy");
	}
	private static boolean isThisTime(String time,String pattern) {
		Date date = stringParseDate(time,"yyyy-MM-dd");
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		String param = sdf.format(date);//参数时间
		String now = sdf.format(new Date());//当前时间
		if(param.equals(now)){
			return true;
		}
		return false;
	}
	/**
	 * 根据日期获得星期
	 * @param date
	 * @return
	 */
	public static String getWeekOfDate(Date date) {
		String[] weekDaysName = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
		String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		return weekDaysCode[intWeek];
	}

	/**
	 * 给定时间段和星期几，计算该时间段内共有多少个给定的星期几
	 * @param start 开始时间
	 * @param end 结束时间
	 * @param a 星期几，从星期一到星期天，分别用数字1-7表示
	 * @return 星期几统计数
	 */
	public static long weekDayCount(Date start, Date end, int a){
		long sumDay = 0;//计数
		try{
			Calendar startDate = Calendar.getInstance(); //开始时间
			startDate.setTime(start);

			Calendar endDate = Calendar.getInstance();//结束时间
			endDate.setTime(end);

			int SW = startDate.get(Calendar.DAY_OF_WEEK)-1;//开始日期是星期几
			int EW = endDate.get(Calendar.DAY_OF_WEEK)-1;//结束日期是星期几

			long diff = endDate.getTimeInMillis()-startDate.getTimeInMillis();
			long days = diff / (1000 * 60 * 60 * 24);//给定时间段内一共有多少天
			long w = Math.round(Math.ceil(((days+SW+(7-EW))/7.0)));//给定时间内，共有多少个星期
			sumDay = w;//总的星期几统计数
			if (a<SW) {
				//给定的星期几小于起始日期的星期几，需要减少一天
				sumDay--;
			}
			if (a>EW) {
				//给定的星期几大于结束日期的星期几，需要减少一天
				sumDay--;
			}
		}catch(Exception se){
			se.printStackTrace();
		}
		return sumDay;
	}

	public static String readFileTxt(String filePath) {
		String line = null;
		try
		{
			FileReader fr=new FileReader(filePath);

			//为了提高效率，加入缓冲技术，将字符读取流对象作为参数传递给缓冲对象的构造函数
			BufferedReader bufr=new BufferedReader(fr);

			while((line=bufr.readLine())!=null)
			{
				System.out.println(line);
				break;
			}
			bufr.close();//close()中已经包含了flush
		} catch (IOException e) {
			e.printStackTrace();
		}

		return line;
	}

	/**
	 * 获取本月开始日期
	 * @return
	 */
	public static String getBeginDayOfMonth() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, 0);
		int actualMinimum = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONDAY), actualMinimum, 00, 00, 00);

		System.out.println("本月开始时间------"+dateParseString(calendar.getTime(), "yyyy-MM-dd"));
		return dateParseString(calendar.getTime(), "yyyy-MM-dd");
	}

	/**
	 * 获取本月结束日期
	 * @return
	 */
	public static String getEndDayOfMonth() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));

		System.out.println("本月结束时间------"+dateParseString(calendar.getTime(), "yyyy-MM-dd"));
		return dateParseString(calendar.getTime(), "yyyy-MM-dd");
	}

	/**
	 * 获取当前日期所在季度的开始日期和结束日期
	 * 季度一年四季， 第一季度：1月-3月， 第二季度：4月-6月， 第三季度：7月-9月， 第四季度：10月-12月
	 * @param isFirst  true表示查询本季度开始日期  false表示查询本季度结束日期
	 * @return
	 */
	public static String getStartOrEndDayOfQuarter(Boolean isFirst) {
		LocalDate today = LocalDate.now();
		LocalDate resDate = LocalDate.now();
		if (today == null) {
			today = resDate;
		}
		Month month = today.getMonth();
		Month firstMonthOfQuarter = month.firstMonthOfQuarter();
		Month endMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
		if (isFirst) {
			resDate = LocalDate.of(today.getYear(), firstMonthOfQuarter, 1);
		} else {
			resDate = LocalDate.of(today.getYear(), endMonthOfQuarter, endMonthOfQuarter.length(today.isLeapYear()));
		}
		System.out.println("本季度时间------"+resDate.toString());
		return resDate.toString();
	}

	//获取本年的开始时间
	public static String getBeginDayOfYear() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.MONTH, 0);
		c.set(Calendar.DATE, 1);

		System.out.println("本年开始时间------"+dateParseString(c.getTime(), "yyyy-MM-dd"));
		return dateParseString(c.getTime(), "yyyy-MM-dd");
	}
	//获取本年的结束时间
	public static String getEndDayOfYear() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.MONTH, 11);
		c.set(Calendar.DATE, 31);

		System.out.println("本年结束时间------"+dateParseString(c.getTime(), "yyyy-MM-dd"));
		return dateParseString(c.getTime(), "yyyy-MM-dd");
	}

	/**
	 * 获得指定日期的前一天
	 *
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static String getSpecifiedDayBefore(String specifiedDay) {

		// SimpleDateFormat simpleDateFormat = new
		// SimpleDateFormat("yyyy-MM-dd");

		Calendar c = Calendar.getInstance();
		Date date = null;
		try {

			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);

		} catch (ParseException e) {

			e.printStackTrace();

		}

		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - 1);

		String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());

		return dayBefore;
	}

}
