package com.util;

import java.awt.image.BufferedImage;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 工具类
 * 
 * @author dubaohui
 * */
public class RequestUtil {

	/**
	 * 获取自动编号
	 * 
	 * @param int
	 * @return String
	 * */
	public static String getid(int f) {
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
		String id = tempDate.format(new java.util.Date()) + getCodeint(f);
		return id;
	}

	/**
	 * 
	 * 获取当前年份
	 * 
	 * */
	public static String getLongYear() {
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String id = tempDate.format(new java.util.Date());
		return id;
	}

	/**
	 * 
	 * 获取当前年份
	 * 
	 * */
	public static String getShortYear() {
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String id = tempDate.format(new java.util.Date());
		return id.substring(2, id.length());
	}

	/**
	 * 
	 * 获取当前日期周日对应的日期
	 * 
	 * @param
	 * @return String
	 * */
	public static String getDateForSunday() {
		Calendar cal = Calendar.getInstance();
		// n为推迟的周数，1本周，-1向前推迟一周，2下周，依次类推
		int n = 1;
		cal.add(Calendar.DATE, n * 7);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		String sunday = new SimpleDateFormat("yyyy-MM-dd")
				.format(cal.getTime());
		return sunday;
	}

	/**
	 * 
	 * 获取当前日期周一对应的日期
	 * 
	 * @param
	 * @return String
	 * */
	public static String getDateForMonday() {
		Calendar cal = Calendar.getInstance();
		// n为推迟的周数，1本周，-1向前推迟一周，2下周，依次类推
		int n = 0;
		cal.add(Calendar.DATE, n * 7);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		String monday = new SimpleDateFormat("yyyy-MM-dd")
				.format(cal.getTime());

		return monday;
	}

	/**
	 * 
	 * 获取随即数字
	 * 
	 * @param code_len
	 * @reutrn String
	 * 
	 * */
	public static String getCodeint(int code_len) {
		int count = 0;
		char str[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < code_len) {
			int i = Math.abs(r.nextInt(10));
			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}

	/**
	 * 获取随即数
	 * 
	 * @param code_len
	 * @return String
	 * */
	public static String getCodechar(int codelen) {
		int count = 0;
		char str[] = { 'a', '1', 'b', 'c', '2', 'd', 'e', '4', 'f', 'j', 'h',
				'3', 'i', 'j', '6', 'k', 'l', '9', 'm', 'n', 'p', 'q', 'r',
				's', 't', '7', 'u', 'v', 'w', '8', 'x', 'y', '5', 'z' };
		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < codelen) {
			int i = Math.abs(r.nextInt(10));
			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}

	/**
	 * 获取当前时间
	 * 
	 * @param
	 * @return String yyyy-MM-dd HH:mm:ss
	 * 
	 * */
	public static String getDateTime() {
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return tempDate.format(new java.util.Date());
	}

	/**
	 * 获取当前时间
	 * 
	 * @param
	 * @return String HH:mm
	 * 
	 * */
	public static String getHHmmTime() {
		SimpleDateFormat tempDate = new SimpleDateFormat("HH:mm");
		return tempDate.format(new java.util.Date());
	}

	/**
	 * 
	 * 获取日期 YYYY-MM-DD
	 * */
	public static String getShortDate() {
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
		return tempDate.format(new java.util.Date());
	}

	/**
	 * 
	 * 根据起止日期获取范围内的每一天
	 * 
	 * @param start
	 * @param end
	 * @return String[]
	 * 
	 * */
	public static String[] getEveryDateForDay(String start, String end) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String strs = "";
		try {
			Date dBegin = sdf.parse(start);
			Date dEnd = sdf.parse(end);
			List<Date> lDate = findDates(dBegin, dEnd);

			for (Date date : lDate) {
				// System.out.println(sdf.format(date));
				strs += sdf.format(date) + ",";
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (!"".equals(strs)) {
			strs = strs.substring(0, strs.length() - 1);
		}
		String str[] = strs.split(",");
		return str;
	}

	
	
	public static List<Date> findDates(Date dBegin, Date dEnd) {
		List lDate = new ArrayList();
		lDate.add(dBegin);
		Calendar calBegin = Calendar.getInstance();
		// 使用给定的 Date 设置此 Calendar 的时间
		calBegin.setTime(dBegin);
		Calendar calEnd = Calendar.getInstance();
		// 使用给定的 Date 设置此 Calendar 的时间
		calEnd.setTime(dEnd);
		// 测试此日期是否在指定日期之后
		while (dEnd.after(calBegin.getTime())) {
			// 根据日历的规则，为给定的日历字段添加或减去指定的时间量
			calBegin.add(Calendar.DAY_OF_MONTH, 1);
			lDate.add(calBegin.getTime());
		}
		return lDate;
	}

	/**
	 * 
	 * 计算时间差
	 * 
	 * @param dateStart
	 * @param dateStop
	 * @return String
	 * 
	 * */
	public static String TimeDifference(String dateStart, String dateStop) {
		String returnvalue = "0天0时0分0秒";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d1 = format.parse(dateStart);
			Date d2 = format.parse(dateStop);
			// 毫秒ms
			long diff = d2.getTime() - d1.getTime();
			System.out.println(diff);
			long diffSeconds = diff / 1000 % 60;
			long diffMinutes = diff / (60 * 1000) % 60;
			long diffHours = diff / (60 * 60 * 1000) % 24;
			long diffDays = diff / (24 * 60 * 60 * 1000);
			returnvalue = diffDays + "天" + diffHours + "小时" + diffMinutes
					+ "分钟" + diffSeconds + "秒";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnvalue;
	}
	
	
	/**
	 * 
	 * 计算间隔天数
	 * 
	 * @param dateStart
	 * @param dateStop
	 * @return String
	 * 
	 * */
	public static Integer DateDifference(String dateStart, String dateStop) {
		int returnvalue = 0;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date d1 = format.parse(dateStart);
			Date d2 = format.parse(dateStop);
			// 毫秒ms
			long diff = d2.getTime() - d1.getTime();
			long diffDays = diff / (24 * 60 * 60 * 1000);
			returnvalue = Integer.parseInt(String.valueOf(diffDays));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnvalue;
	}
	/**
	 * 
	 * 计算间隔天数
	 * 
	 * @param dateStart
	 * @param dateStop
	 * @return String
	 * 
	 * */
	public static Integer DateDifference(String dateStart, String dateStop,String dataformat) throws Exception{
		int returnvalue = 0;
		SimpleDateFormat format = new SimpleDateFormat(dataformat);
		try {
			Date d1 = format.parse(dateStart);
			Date d2 = format.parse(dateStop);
			// 毫秒ms
			long diff = d2.getTime() - d1.getTime();
			long diffDays = diff / (24 * 60 * 60 * 1000);
			returnvalue = Integer.parseInt(String.valueOf(diffDays));
		} catch (Exception e) {
			throw e;
		}
		return returnvalue;
	}
	/**
	 * 
	 * 根据日期获取分钟
	 * 
	 * @param dateStart
	 * @param dateStop
	 * @return String
	 * */
	public static String getMinutes(String dateStart, String dateStop) {

		String returnvalue = "0";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d1 = format.parse(dateStart);
			Date d2 = format.parse(dateStop);
			// 毫秒ms
			long diff = d2.getTime() - d1.getTime();
			long minut = diff / (1000 * 60);
			returnvalue = minut + "";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnvalue;
	}

	
	/**
	 * 获取服务路径
	 * 
	 * @param HttpServletRequest
	 * @return String
	 * */
	public static String getPath(HttpServletRequest request) {
		return request.getContextPath();

	}
	
	/**
	 * 获取文件路径
	 * @param String
	 * @return String
	 * 
	 * */
	public static String getFilePath(String filename,HttpServletRequest request){
		return request.getSession().getServletContext().getRealPath(filename);
	}
	
	/**
	 * 读取实体文件转成二进制字符串
	 * 
	 * @param path
	 * @return String
	 * @throws IOException
	 * */
	public static String GetHexStringbyImg(String path, String type)
			throws IOException {

		String info = "";
		File f = new File(path);
		InputStream input = new FileInputStream(f);
		BufferedInputStream bis = new BufferedInputStream(input);
		BufferedImage bm = ImageIO.read(bis);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(bm, type, bos);
		bos.flush();
		byte[] data = bos.toByteArray();
		info = byte2hex(data);
		// System.out.println(info);
		bos.close();
		return info;
	}

	/**
	 * @title 根据二进制字符串生成图片
	 * @param data
	 *            生成图片的二进制字符串
	 * @param fileName
	 *            图片名称(完整路径)
	 * @param type
	 *            图片类型
	 * @return
	 */
	public static void saveImage(String data, String fileName, String type) {

		BufferedImage image = new BufferedImage(300, 300,
				BufferedImage.TYPE_BYTE_BINARY);
		ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, type, byteOutputStream);
			// byte[] date = byteOutputStream.toByteArray();
			byte[] bytes = hex2byte(data);
			// System.out.println("path:" + fileName);
			RandomAccessFile file = new RandomAccessFile(fileName, "rw");
			file.write(bytes);
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 反格式化byte
	 * 
	 * @param s
	 * @return
	 */
	public static byte[] hex2byte(String s) {
		byte[] src = s.toLowerCase().getBytes();
		byte[] ret = new byte[src.length / 2];
		for (int i = 0; i < src.length; i += 2) {
			byte hi = src[i];
			byte low = src[i + 1];
			hi = (byte) ((hi >= 'a' && hi <= 'f') ? 0x0a + (hi - 'a')
					: hi - '0');
			low = (byte) ((low >= 'a' && low <= 'f') ? 0x0a + (low - 'a')
					: low - '0');
			ret[i / 2] = (byte) (hi << 4 | low);
		}
		return ret;
	}

	/**
	 * 格式化byte
	 * 
	 * @param b
	 * @return
	 */
	public static String byte2hex(byte[] b) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] out = new char[b.length * 2];
		for (int i = 0; i < b.length; i++) {
			byte c = b[i];
			out[i * 2] = Digit[(c >>> 4) & 0X0F];
			out[i * 2 + 1] = Digit[c & 0X0F];
		}

		return new String(out);
	}

	/**
	 * MD5加密
	 * 
	 * @param String
	 * @param String
	 * */

	public static String getMD5Message(String strs) {
		String returnValue = "";
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = strs.getBytes();
			// 使用MD5创建MessageDigest对象
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte b = md[i];
				// 将每个数(int)b进行双字节加密
				str[k++] = hexDigits[b >> 4 & 0xf];
				str[k++] = hexDigits[b & 0xf];
			}
			returnValue = new String(str);
		} catch (Exception e) {
			return null;
		}
		return returnValue;
	}

	/**
	 * 获取某年 某月的第一天
	 * 
	 * @param year
	 * @param month
	 * @reutrn String
	 * */
	public static String getFirstDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
		return new SimpleDateFormat("yyyyMMdd ").format(cal.getTime());
	}

	/**
	 * 获取某月的最后一天
	 * 
	 * @param year
	 * @param month
	 * @return String
	 * */
	public static String getLastDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
		return new SimpleDateFormat("yyyyMMdd ").format(cal.getTime());
	}

	/**
	 * 获取某年 某月的第一天
	 * 
	 * @param year
	 * @param month
	 * @reutrn String
	 * */
	public static String getFirstDayOfMonthformat(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
		return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
	}

	/**
	 * 获取某月的最后一天
	 * 
	 * @param year
	 * @param month
	 * @return String
	 * */
	public static String getLastDayOfMonthformat(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
		return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
	}

	/**
	 * 根据年月获取周的起止日期
	 * 
	 * @param year
	 * @param month
	 * return String
	 * */
	public static String getWeekStartandEnd(String year, String month) {

		String info = "";
		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.set(Calendar.YEAR, Integer.parseInt(year));
		cal.set(Calendar.MONTH, Integer.parseInt(month) - 1);
		int index = 1;
		String start = null;
		if (Integer.parseInt(month) < 10) {
			start = year +"-"+ "0" + month +"-"+ "0" + 1;
		} else {
			start = year +"-"+ month +"-"+ 1;
		}
		String end = null;
		for (int i = 1; i <= cal.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
			cal.set(Calendar.DAY_OF_MONTH, i);
			int week = cal.get(Calendar.DAY_OF_WEEK);
			if (Integer.parseInt(month) < 10) {
				if (i < 10) {
					end = year +"-"+ "0" + month +"-"+ "0" + i;
				} else {
					end = year +"-"+ "0" + month+"-" + i;
				}
			} else {
				if (i < 10) {
					end = year +"-"+ month +"-"+ "0" + i;
				} else {
					end = year +"-"+ month +"-"+ i;
				}
			}
			if (week - 1 == 6) {
				info += start + "&" + end + ",";
				if (Integer.parseInt(month) < 10) {
					if ((i + 1) < 10) {
						start = year +"-"+ "0" + month +"-"+ "0" + (i + 1);
					} else {
						start = year +"-"+ "0" + month +"-"+ (i + 1);
					}

				} else {
					if ((i + 1) < 10) {
						start = year +"-"+ month +"-"+ "0" + (i + 1);
					} else {
						start = year +"-"+ month +"-"+ (i + 1);
					}
				}
				index++;
			}
		}
		info += start + "&" + end;
		return info;
	}
	
	
	/**
	 * 得到本周和上周的起止日期
	 * */
	public static String ReWeek(int n) {
		Calendar cal = Calendar.getInstance();
		// n为推迟的周数，1本周，-1向前推迟一周，2下周，依次类推
		// 上周起止时间 n=-1 n=0 上周 n=-1<= date <n=0 本周 n=0 <=date< n=1
		cal.add(Calendar.DATE, n * 7);
		// 想周几，这里就传几Calendar.MONDAY（TUESDAY...）
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		String monday = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
		return monday;
	}

	/**
	 * 获取指定周的时间段
	 * 
	 * @param Year
	 * @param Month
	 * @param int
	 * @return String
	 * */
	public static String getweekdate(String year, String month, int f) {
		String info = "";
		if (Integer.parseInt(month) > 9) {
		} else {
			if (month.length() == 2) {
				month = month.substring(1, month.length());
			}
		}
		String str = getWeekStartandEnd(year, month);
		String st[] = str.split(",");
		info = st[f - 1].toString();
		return info;
	}

	/**
	 * 计算时间段间隔多少分钟
	 * 
	 * @param String
	 * @param String
	 * @return String
	 * */
	public static String TimeLock(Date t11, Date t22) {
		long l1 = 0;
		long l2 = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd   HH:mm");
		String t1 = sdf.format(t11);
		String t2 = sdf.format(t22);
		try {
			l1 = sdf.parse(t1).getTime();
			l2 = sdf.parse(t2).getTime();
		} catch (java.text.ParseException pe) {
			pe.printStackTrace();
		}
		return String.valueOf((l2 - l1) / 1000 / 60);
	}

	/**
	 * 
	 * 对象数组[]转化成string
	 * */
	public static String ReturnObjStr(Object obj) {
		if (obj != null) {
			return obj.toString();
		} else {
			return "";
		}
	}

	/**
	 * 返回 空值
	 * */
	public static String IsNULL(String str) {
		if (str == null) {
			str = "";
		}
		return str;
	}

	/**
	 * 判断当前日期是星期几<br>
	 * <br>
	 * 
	 * @param pTime
	 *            修要判断的时间<br>
	 * @return dayForWeek 判断结果<br>
	 * @Exception 发生异常<br>
	 */
	public static int dayForWeekInt(String pTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(format.parse(pTime));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int dayForWeek = 0;
		if (c.get(Calendar.DAY_OF_WEEK) == 1) {
			dayForWeek = 7;
		} else {
			dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
		}
		return dayForWeek;
	}

	/***
	 * 
	 * 根据日期获取今天是周几中文
	 * 
	 * */
	public static String dayForWeekString(String pTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(format.parse(pTime));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int dayForWeek = 0;
		if (c.get(Calendar.DAY_OF_WEEK) == 1) {
			dayForWeek = 7;
		} else {
			dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
		}
		String[] weeks = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };
		return weeks[dayForWeek - 1];

	}


	/**
	 * 获取当前年月第几周
	 * 
	 * */
	public static String getYearMonthWeek() {

		Calendar cal = Calendar.getInstance();
		int month = cal.get(Calendar.MONTH) + 1;// 月
		int year = cal.get(Calendar.YEAR); // 年
		Map map = new HashMap();
		map.put(1, "一");
		map.put(2, "二");
		map.put(3, "三");
		map.put(4, "四");
		map.put(5, "五");
		map.put(6, "六");
		map.put(7, "七");
		map.put(8, "八");
		map.put(9, "九");
		int week = cal.get(Calendar.WEEK_OF_MONTH);// 获取是本月的第几周
		return year + "年" + month + "月" + " 第" + map.get(week) + "周";
	}

	public static void main(String[] args) throws ParseException {
		String str = "201506151234";
		String co = str.substring(0, str.length()-4);
		String newstr = str.substring(str.length()-4, str.length());
		int c = Integer.parseInt(newstr)+1;
		String c1 = String.valueOf(c);
		String code = "";
		if(c1.length()==1){
			code = co+"000"+c1;
		}else if(c1.length()==2){
			code = co+"00"+c1;
		}else if(c1.length()==3){
			code = co+"0"+c1;
		}else{
			code=co+c1;
		}
		System.out.println(code);
	}
	
	
	
	public static String GetCodeByCode(String jcode,String beforecode){
		String code  = "";
		String between = UtilTools.getTime("YYYYMMdd");
		if(RequestUtil.checkisnull(beforecode) && beforecode.length()>8){
			String lastcode = beforecode.substring(beforecode.length()-4, beforecode.length());
			String  newlastcode = String.valueOf(Integer.parseInt(lastcode)+1);
			if(newlastcode.length()==1){
				code = jcode+between+"000"+newlastcode;
			}else if(newlastcode.length()==2){
				code = jcode+between+"00"+newlastcode;
			}else if(newlastcode.length()==3){
				code = jcode+between+"0"+newlastcode;
			}else{
				code = jcode+between+newlastcode;
			}
		}else{
			code = jcode+between+"0001";
		}
		return code;
	}

	/***
	 * 根据年月获取月份的最后一天
	 * 
	 * @param year
	 * @param month
	 * @param String
	 *            yyyy-mm-dd
	 * */
	// 需要注意的是：月份是从0开始的，比如说如果输入5的话，实际上显示的是4月份的最后一天，千万不要搞错了哦
	public static String getLastDayOfYearMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
		return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
	}

	/***
	 * 根据年月获取月份的第一天
	 * 
	 * @param year
	 * @param month
	 * @param String
	 * yyyy-mm-dd
	 * */
	public static String getFirstDayOfYearMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
		return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
	}

	/**
	 * 
	 * double转int实现四舍五入
	 * */
	public static int DoubletoInt(double value) {
		int yvalue = Integer.parseInt(new java.text.DecimalFormat("0")
				.format(value));
		return yvalue;
	}

	/**
	 * Object转换成JSON
	 * 
	 * @param javaObj
	 * @return
	 */
	public static String ObjecttoJsonString(Object javaObj) {
		JSONObject json;
		json = JSONObject.fromObject(javaObj);
		return json.toString();

	}


	/**
	 * list转换成JSON
	 * 
	 * @param javaObj
	 * @return
	 */
	public static String ListtoJsonString(List list) {
		JSONArray json;
		if (list != null && list.size() > 0) {
			json = JSONArray.fromObject(list);
			return json.toString();
		} else {
			return "";
		}

	}


	/**
	 * 数据写入缓存操作
	 * 
	 * @param HttpServletResponse
	 * @param jsonResult
	 * @return
	 * @author dubaohui
	 * */

	public static void responseResult4Json(HttpServletResponse response,
			String jsonResult) {
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.println(jsonResult);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * JSON参数格式错误
	 * 
	 * @param HttpServletResponse
	 * @param jsonResult
	 * @return
	 * @author dubaohui
	 * */

	public static void responseResult4JsonError(HttpServletResponse response,
			String param) {
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			String jsonResult = "error:错误的JSON格式:" + param + "，请认真检查您的JSON格式。";
			out.println(jsonResult);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 获取List.size()
	 * 
	 * @param List
	 * @return int
	 * @author dubaohui
	 * */
	public static int IfList(List list) {
		if (list != null && list.size() > 0) {
			return list.size();
		} else {
			return 0;
		}
	}

	/**
	 * 数据删除提示
	 * 
	 * @param boolean
	 * @param HttpServletResponse
	 * @return String
	 * @author dubaohui
	 * */
	public static void Delete(boolean sign, HttpServletResponse response) {
		if (sign) {
			responseResult4Json(response, Configmessage.DELECESUCC);
		} else {
			responseResult4Json(response, Configmessage.DELECEFINAL);
		}
	}

	/**
	 * 数据修改提示
	 * 
	 * @param boolean
	 * @param HttpServletResponse
	 * @return String
	 * @author dubaohui
	 * */
	public static void Update(boolean sign, HttpServletResponse response) {
		if (sign) {
			responseResult4Json(response, Configmessage.UPDATESUCC);
		} else {
			responseResult4Json(response, Configmessage.UPDATEFINAL);
		}
	}

	/**
	 * 数据新增提示
	 * 
	 * @param boolean
	 * @param HttpServletResponse
	 * @return String
	 * @author dubaohui
	 * */
	public static void Save(boolean sign, HttpServletResponse response) {
		if (sign) {
			responseResult4Json(response, Configmessage.SAVESUCC);
		} else {
			responseResult4Json(response, Configmessage.SAVEFINAL);
		}
	}


	/**
	 * 
	 * 数据操作提示
	 * 
	 * @param boolean
	 * @return String
	 * @author dubaohui
	 * 
	 * */
	public static void CAOZ(boolean sign, HttpServletResponse response) {
		if (sign) {
			responseResult4Json(response, Configmessage.CAOZYES);
		} else {
			responseResult4Json(response, Configmessage.CAOZNO);
		}
	}
	/**
	 * 
	 * 数据设置提示
	 * 
	 * @param boolean
	 * @return String
	 * @author dubaohui
	 * 
	 * */
	public static void Setting(boolean sign, HttpServletResponse response) {
		if (sign) {
			responseResult4Json(response, Configmessage.SETINGSUCC);
		} else {
			responseResult4Json(response, Configmessage.SETINGFINAL);
		}
	}

	/**
	 * 
	 * 数据调动提示
	 * 
	 * @param boolean
	 * @return String
	 * @author dubaohui
	 * 
	 * */
	public static void Redeploy(boolean sign, HttpServletResponse response) {
		if (sign) {
			responseResult4Json(response, Configmessage.REDSUCC);
		} else {
			responseResult4Json(response, Configmessage.REDFINAL);
		}
	}
	
	/**
	 * 
	 * 数据初始化提示
	 * 
	 * @param boolean
	 * @return String
	 * @author dubaohui
	 * 
	 * */
	public static void Init(boolean sign, HttpServletResponse response) {
		if (sign) {
			responseResult4Json(response, Configmessage.INITSUCC);
		} else {
			responseResult4Json(response, Configmessage.INITFINAL);
		}
	}
	/**
	 * 
	 * 判断是否为int
	 * 
	 * */
	public static boolean isInt(String value) {
		boolean flg = false;
		try {
			Integer.parseInt(value);
			flg = true;
		} catch (Exception ex) {
			flg = false;
		}
		return flg;
	}

	/**
	 * 
	 * 返回List结果集的记录条数
	 * 
	 * */
	public static int ListCount(List listcount) {

		int count = 0;
		if (listcount != null && listcount.size() > 0) {
			count = listcount.size();
		}
		return count;
	}

	// 返回序号
	public static int checkabc(String value) {
		int j = 0;
		String convert[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
				"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
				"W", "X", "Y", "Z" };
		for (int i = 0; i < convert.length; i++) {
			if (value.equals(convert[i])) {
				j = i + 1;
				break;
			}
		}
		return j;
	}

	/***
	 * @param List
	 *            <Object[]>
	 * @param String
	 *            [] JSON标识
	 * @return JSONArray
	 * @author dubaohui
	 * */
	public static JSONArray listTojsonArray(List list, String[] names) {
		JSONArray jarry = new JSONArray();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Object[] obj = (Object[]) list.get(i);
				JSONObject object = new JSONObject();
				for (int j = 0; j < names.length; j++) {
					object.put(names[j],
							null == obj[j] ? "" : obj[j].toString());
				}
				jarry.add(object);
			}
		}
		return jarry;
	}

	/**
	 * 
	 * 读取properties配置文件中的数据
	 * 
	 * @param key
	 * @return value
	 * */
	public static String getpropertiesvalue(String key) {
		ResourceBundle resourceBundle=ResourceBundle.getBundle("com/dubh/sysconfig/group");
		if (key == null || key.equals("") || key.equals("null")) {
            return "";
        }
        String result = "";
        try {
            result = resourceBundle.getString(key);
        } catch (MissingResourceException e) {
            e.printStackTrace();
        }
        return result;
	}
	
	
	/**
	 * 
	 * 获取访问者IP地址
	 * 
	 * */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		// ipAddress = this.getRequest().getRemoteAddr();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")
					|| ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}

		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
	
	
	/**
	 * 如果文件为NULL 返回””
	 * 
	 * */
	public static String stringIsNull(String objstr) {
		if (null == objstr) {
			return "";
		} else {
			return objstr;
		}
	}
	
	
	
	/**
	  * 
	  * 获取文件后缀名
	  * 
	  * */
	 public static String getExtensionName(String filename) {   
	        if ((filename != null) && (filename.length() > 0)) {   
	            int dot = filename.lastIndexOf('.');   
	            if ((dot >-1) && (dot < (filename.length() - 1))) {   
	                return filename.substring(dot + 1);   
	            }   
	        }   
	        return filename;   
	    }
	 
	 
	 
	 /**
		 * 
		 * 去除固定标示
		 * 
		 * @param String
		 * @return String
		 * */
		public static String SplitString(String flg){
			String info="";
			if(flg !=null && !"".equals(flg)){
			if(flg.indexOf("_")>0){
				
				info= flg.replace("_", "");
			}else{
				
				info= flg;
			}
		  }
			return info;
		}
		
		
		/**
		 * 
		 * 判断是否为空
		 * @param String 
		 * @return boolean
		 * */
		public static boolean checkisnull(String str){
			if(null != str && !"".equals(str)){
				return true;
			}else{
				return false;
			}
		}
		
		
		
		/***
		 * 
		 * 字符串转成万元
		 * 
		 * */
		public static String getMoneytoWan(String money){
			String wanmoney = "0.0万";
			if(checkisnull(money)){
				double moneys = Double.parseDouble(money);
				double n = (double) moneys / 10000;
				wanmoney = n+"万";
			}
			return wanmoney;
		}
		
		
		/**
		 * 获取某一周内的所有日期及星期
		 * @param int  0:本周 1：下一周 -1：上一周 可一次递增或递减
		 * */
		public static org.json.JSONArray getEveryDayforWeek(int n) {
			org.json.JSONArray array = new org.json.JSONArray();
			try{
			 Calendar cal = Calendar.getInstance();
			 cal.add(Calendar.DATE, n * 7);
			 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
			 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			 Calendar callast = Calendar.getInstance();
			 //获取中国周日日期
			 int f=n+1;
			 callast.add(Calendar.DATE, f * 7);
			 callast.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
			 //获取本周内所有日期
			 String monday = dateFormat.format(cal.getTime());
			 String sunday = dateFormat.format(callast.getTime());
			 Date dBegin = dateFormat.parse(monday);
		     Date dEnd = dateFormat.parse(sunday);
			 List<Date> lDate = findDates(dBegin, dEnd);
			 for (Date date : lDate) {
				 org.json.JSONObject object = new org.json.JSONObject();
				 object.put("date", dateFormat.format(date));
				 object.put("weekcn",dayForWeekInt(dateFormat.format(date)));
				 object.put("weeken",dayForWeekString(dateFormat.format(date)));
				 array.put(object);
			 }
			}catch(Exception ex){
				ex.printStackTrace();
			}
			return array;
		}
		
		
		/**
		 * 
		 * 根据日期获取日期属于第几周
		 * @param date
		 * @return int
		 * */
		public static int getWeekforNum(String date){
			Calendar ca = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				ca.setTime(dateFormat.parse(date));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int weeknum = ca.get(Calendar.WEEK_OF_YEAR);
			return weeknum;
		}
		
		
		/**
		 * 获取对象编号
		 * */
		public String getwebkeys(String webkey){
			StringBuffer sb = new StringBuffer("");
			if(RequestUtil.checkisnull(webkey)){
				if(webkey.indexOf(":")>-1){
					String webkeys[] = webkey.split(":");
					if(webkeys.length>0){
						for(int i=0;i<webkeys.length;i++){
							if("".equals(sb.toString())){
								sb.append("'"+webkeys[i]+"'");
							}else{
								sb.append(",'"+webkeys[i]+"'");
							}
						}
					}
				}else{
					sb.append("'"+webkey+"'");
				}
			}
			return sb.toString();
		}
		
		//获取数组
		public String[] getwebkeyarray(String webkey){
			String webkeys[] = null;
			if(RequestUtil.checkisnull(webkey)){
				if(webkey.indexOf(":")>-1){
					String student[] = webkey.split(":");
					if(student.length>0){
						webkeys= new String[student.length];
						for(int i=0;i<student.length;i++){
							webkeys[i] = student[i];
						}
					}
				}else{
					webkeys= new String[1];
					webkeys[0] = webkey;
				}
			}
			return webkeys;
		}
		/**
		 * 
		 * 计算时间差
		 * @param bigdate
		 * @return long 秒
		 * 
		 * */
		public static String getSecondtime(String nowdatime,String bigdatatime){
			if(!UtilTools.strNotNull(nowdatime) || !UtilTools.strNotNull(bigdatatime)){
				return "0";
			}
			long times = 0;
			try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = format.parse(nowdatime);
			Date d2 = format.parse(bigdatatime);
			//毫秒ms
			 long diff = d2.getTime() - d1.getTime();
			 times =diff / 1000;
			}catch(Exception e){
				e.printStackTrace();
				times =0;
			}
			return times+"";
		}
}
