whycxzp
1 天以前 aa52854f0a413e153efeea76a952dcf66d76c94a
src/main/java/com/whyc/util/CommonUtil.java
@@ -1,594 +1,101 @@
package com.whyc.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.whyc.constant.YamlProperties;
import com.whyc.pojo.db_user.User;
import org.apache.commons.codec.digest.DigestUtils;
import com.whyc.service.UserLogService;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import org.springframework.stereotype.Component;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.io.File;
import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;
/**
 * 通用工具列
 */
@Component
public class CommonUtil {
   public static Object objectNull = null;
    public static Object nullObject = null;
    private static UserLogService userLogService;
   public static String time_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
   public static String time_yyyyMMdd = "yyyy-MM-dd";
   public static String time_yyyyMMdd_HH_mm_ss = "yyyy-MM-dd_HH_mm_ss";
   public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   public static SimpleDateFormat sdfwithOutday = new SimpleDateFormat("yyyy_MM");
   public static SimpleDateFormat sdfwithday = new SimpleDateFormat("yyyy-MM-dd");
   public static SimpleDateFormat sdfwithtime = new SimpleDateFormat("HH:mm:ss");
   public static SimpleDateFormat sdfwithtime_yyyyMMdd_HH_mm_ss = new SimpleDateFormat(time_yyyyMMdd_HH_mm_ss);
   public static SimpleDateFormat sdfwithALL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   public static String classesPath(){
      ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class);
      File jarFile = applicationHome.getDir();
      return jarFile.toString();
   }
   /**
    * 获取存放文件的根路径
    * @return 返回存放文件的根路径
    */
   public static String getRootFile(){
      ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class);
      File jarFile = applicationHome.getDir();
      String baseDirPath;
      if(YamlProperties.runModel == 1) {
         //开发路径
         baseDirPath = jarFile.getParentFile().toString()+File.separator+"battery_gwm_file"+File.separator;
      }else {
         //打包路径
         baseDirPath = jarFile.toString()+File.separator+"battery_gwm_file"+File.separator;
      }
      return baseDirPath;
   }
   /**
    * 获取项目所在文件夹路径
    * @return 获取项目所在文件夹路径
    */
   public static String getProjectDir(){
      ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class);
      File jarFile = applicationHome.getDir();
      String baseDirPath;
      if(YamlProperties.runModel == 1) {
         //开发路径
         baseDirPath = jarFile.getParentFile().toString();
      }else {
         //打包路径
         baseDirPath = jarFile.toString();
      }
      return baseDirPath;
   }
   /*
    * 获取HttpServletRequest
    */
   public static HttpServletRequest getRequest(){
      ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      HttpServletRequest request = requestAttributes.getRequest();
      return request;
   }
   /*
    * 获取HttpServletResponse
    */
   public static HttpServletResponse getResponse(){
      ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      HttpServletResponse response = requestAttributes.getResponse();
      return response;
   }
   /*
    * 获取HttpSession
    */
   public static HttpSession getSession(){
      return getRequest().getSession();
   }
   /**
    *
    * @return   返回application
    */
   public static ServletContext getApplication(){
      return getSession().getServletContext();
   }
   public static User getUser(){
      User principal = (User) SecurityUtils.getSubject().getPrincipal();
      if(principal == null){
         User user = new User();
         user.setName("unLogged-in user");
         user.setId(0);
         return user;
      }else {
         return principal;
      }
   }
   //获取application中互斥上传的标志位flag
   public static int getFlag(){
      ServletContext app=getApplication();
      int flag=(Integer) app.getAttribute("flag");
      return flag;
   }
   ////给application中互斥上传的标志位flag设置值
   public static void setFlag(int flag){
      ServletContext app=getApplication();
      app.setAttribute("flag", flag);
   }
   /*
    * 获取将对象转换成json格式
    */
   public static String tojson(Object obj){
      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
      return gson.toJson(obj);
   }
   public static String chageDateToString(Date time,String type){
      String msg = "";
      SimpleDateFormat sdf = new SimpleDateFormat(type);
      msg = sdf.format(time);
      return msg;
   }
   /**
    *
    * @param datetype   需要解析的日期的格式如:"yyyy-MM-dd HH:mm:ss"
    * @return   得到对应的gson对象
    */
   public static Gson getGson(String datetype){
      return new  GsonBuilder().setDateFormat(datetype).create();
   }
   /**
    * 获取默认的gson对象
    * @return
    */
   public static Gson getGson(){
      return new Gson();
   }
   public static <T> T getObject(String jsonstring,Type listtype){
      Gson gson=new Gson();
      T t=null;
      try {
         t=gson.fromJson(jsonstring, listtype);
      } catch (JsonSyntaxException e) {
         e.printStackTrace();
      }
      return t;
   }
   /**
    *
    * @return 获取输出流
    */
   public static PrintWriter getOut(){
      PrintWriter out =null;
      try {
         out=getResponse().getWriter();
      } catch (IOException e) {
         e.printStackTrace();
      }
      return out;
   }
   /**
    *
    * @param time   java.util包中的时间
    * @return      java.sql时间
    */
   public static Date getSimpDate(Date time){
      //System.out.println(time);
      return new java.sql.Date(time.getTime());
   }
   //使用Base64加密
   public static Object EncryptionBase64(Object obj){
      String base64=null;
      if(obj!=null && obj.toString().length()>0){
         base64=new BASE64Encoder().encode(obj.toString().getBytes());
         base64 = base64.replaceAll("[\\s*\t\n\r]", "");       //替换加密后不换行
      }
      return base64;
   }
   //使用Base64解密
   public static Object DecryptionBase64(Object obj){
      String base64=null;
      if(obj!=null && obj.toString().length()>0){
         try {
            base64 = new String(new BASE64Decoder().decodeBuffer(obj.toString()));
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      return base64;
   }
   //获取指定年月的天数
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    @Autowired
    public void setUserLogService(UserLogService userLogService) {
        CommonUtil.userLogService = userLogService;
    }
    //获取某年某月的起始和结束时间
    //需要注意的是:月份是从0开始的,比如说如果输入5的话,实际上显示的是4月份的最后一天,千万不要搞错了哦
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DATE));
       return  new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"23:59:59";
    }
    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH,cal.getMinimum(Calendar.DATE));
       return   new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"00:00:00";
    }
    //获取当前时间的年份
    public static int getNowYear(){
       Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
      ca.setTime(new Date()); //设置时间为当前时间
      int year = ca.get(Calendar.YEAR);
      //System.out.println(month);
      return year;
    }
    //获取当前时间的月份
    public static int getNowMonth(){
       Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
      ca.setTime(new Date()); //设置时间为当前时间
      int month = ca.get(Calendar.MONTH) + 1;
      //System.out.println(month);
      return month;
    }
    //获取当前时间的日期
    public static int getNowday(){
       Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
      ca.setTime(new Date()); //设置时间为当前时间
      int day = ca.get(Calendar.DAY_OF_MONTH);
      //System.out.println(month);
      return day;
    }
   //当前时间加上x小时
    public static String getDateAdd(int minute){
    Date date = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.MINUTE, minute);
    return new   SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(c.getTime());
    /**获取当前Session中的属性user*/
    public static User getUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute("user");
    }
   //使用MD5加密
   public static Object EncryptionMD5(Object obj){
      String md5=null;
      if(obj!=null && obj.toString().length()>0){
         md5= DigestUtils.md5Hex(obj.toString());
      }
      return md5;
   }
    //获取时间的年份
    public static int getDateYear(Date date){
       Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
      ca.setTime(date); //设置时间为当前时间
      int year = ca.get(Calendar.YEAR);
      //System.out.println(month);
      return year;
    }
    //获取时间的月份
    public static int getDateMonth(Date date){
       Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
      ca.setTime(date); //设置时间为当前时间
      int month = ca.get(Calendar.MONTH) + 1;
      //System.out.println(month);
      return month;
    }
    //获取时间的日期
    public static int getDateday(Date date){
       Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
      ca.setTime(date); //设置时间为当前时间
      int day = ca.get(Calendar.DAY_OF_MONTH);
      //System.out.println(month);
      return day;
    }
    //当前时间加上x小时
    public static Date getDateAdd(Date date,int minute){
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.MINUTE, minute);
    return c.getTime();
    }
    //给定时间判断与当前时间相比是否为老电池(numYear为时间期限几年)
    public static int judgeBatt(Date inUseDate,Date date,int numYear){
       int judge=0;
       inUseDate.setYear(CommonUtil.getDateYear(inUseDate)+numYear-1900);
       //System.out.println("inUseDate: "+inUseDate);
       if(inUseDate.after(date)){
          judge=1;
       }else{
          judge=0;
       }
      return judge;
    }
    //获取某年某月某日内的时间<date为执行时间的时分秒设置为提醒时间段的时分秒>
    public static Date getWorkDay(Date date,Date noticeTime) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date); //设置时间为执行日期
        int year = cal.get(Calendar.YEAR);//年
      int month = cal.get(Calendar.MONTH);//月
      int day = cal.get(Calendar.DAY_OF_MONTH);//日
      cal.setTime(noticeTime);//设置时间为提醒时间段
      /*int hour=cal.get(Calendar.HOUR_OF_DAY);//时
      int minute=cal.get(Calendar.MINUTE);//分
      int second=cal.get(Calendar.SECOND);//秒*/
      cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH,day);
        return  cal.getTime();
       }
    //获取某年某月某日起始时间/结束时间
    public static String getDayTime(int year, int month,int day,int type) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH,day);
        if(type==1){
           return   new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"00:00:00";
        } else if(type==2){
           return   new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"09:00:00";
        }else if(type==3){
           return   new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"17:00:00";
        }else if(type==4){
           return   new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"23:59:59";
        }
       return   new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
    }
    //计算电池使用了多少个月
    public static int battInuseMonth(Date inUseDate){
       int useDay=0;
       Date nowd=new Date();//当前时间
       int inuseY= CommonUtil.getDateYear(inUseDate);
       int inuseM= CommonUtil.getDateMonth(inUseDate);
       int nowY= CommonUtil.getDateYear(nowd);
       int nowM= CommonUtil.getDateMonth(nowd);
       if(inuseY==nowY){
          useDay=nowM-inuseM;
       }else{
          useDay=(nowY-inuseY)*12+nowM-inuseM;
       }
      return useDay;
    }
    //计算日期之间相差的天数
    public static int daysBetween(Date smdate,Date bdate)
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
      try {
         smdate=sdf.parse(sdf.format(smdate));
         bdate=sdf.parse(sdf.format(bdate));
      } catch (ParseException e) {
         e.printStackTrace();
      }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
       return Math.abs(Integer.parseInt(String.valueOf(between_days)));
    }
    //计算日期之间相差的小时
    public static int HoursBetween(Date smdate,Date bdate)
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
         smdate=sdf.parse(sdf.format(smdate));
         bdate=sdf.parse(sdf.format(bdate));
      } catch (ParseException e) {
         e.printStackTrace();
      }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_hours=(time2-time1)/(1000*3600);
        //System.out.println("between_hours:"+between_hours);
        return (int) Math.abs(between_hours);
    }
    //比较两个时间的大小
    public static int compareDate(Date d1,Date d2){
        if (d1.getTime() > d2.getTime()) {
            return 1;
        } else if (d1.getTime() < d2.getTime()) {
            return -1;
        } else {//相等
            return 0;
        }
        }
    /**
     * @Description: 根据图片地址转换为base64编码字符串
     * @Author:
     * @CreateTime:
     * Shiro框架下的用户获取
     * @return
     */
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
    public static User getUser() {
        User user;
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser!=null && currentUser.isAuthenticated()){
            user = (User) currentUser.getPrincipal();
        }else{
            user = new User();
            user.setName("unlogged_user");
            user.setId(0);
            user.setRole(1);
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
        return user;
    }
    /**
     * @Description: 将base64编码字符串转换为图片
     * @Author:
     * @CreateTime:
     * @param imgStr base64编码字符串
     * @param path 图片路径-具体到文件
     * @return
    */
    public static boolean generateImage(String imgStr, String path) {
       if (imgStr == null) {
         return false;
      }
       BASE64Decoder decoder = new BASE64Decoder();
       try {
          // 解密
          byte[] b = decoder.decodeBuffer(imgStr);
          // 处理数据
          for (int i = 0; i < b.length; ++i) {
             if (b[i] < 0) {
                b[i] += 256;
             }
          }
          OutputStream out = new FileOutputStream(path);
          out.write(b);
          out.flush();
          out.close();
          return true;
       } catch (Exception e) {
          return false;
       }
    public static String classesPath(){
        ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class);
        File jarFile = applicationHome.getDir();
        return jarFile.toString();
    }
    public static String getRootFile(){
        ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class);
        File jarFile = applicationHome.getDir();
        String baseDirPath;
        if(YamlProperties.runModel == 1) {
            //开发路径
            baseDirPath = jarFile.getParentFile().toString()+File.separator+"pis_file"+File.separator;
        }else {
            //打包路径
            baseDirPath = jarFile.toString()+File.separator+"pis_file"+File.separator;
        }
        return baseDirPath;
    }
    /**
     * 将输入流中的数据读到字节数组中
     * @param is
     * @return
     * 获取项目所在文件夹路径
     * @return 获取项目所在文件夹路径
     */
    public static byte[] IStoByteArr(InputStream is){
       byte[] b = null;
      try {
         b = new byte[is.available()];
         is.read(b);
      } catch (IOException e) {
         e.printStackTrace();
      } finally{
         if(is != null){
            try {
               is.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
       return b;
    public static String getProjectDir(){
        ApplicationHome applicationHome = new ApplicationHome(CommonUtil.class);
        File jarFile = applicationHome.getDir();
        String baseDirPath;
        if (YamlProperties.runModel == 1) {
            //开发路径
            baseDirPath = jarFile.getParentFile().toString();
        } else {
            //打包路径
            baseDirPath = jarFile.toString();
        }
        return baseDirPath;
    }
    /**
    * 创建指定的文件文件,若不存在则先创建指定的文件夹再创建指定的文件
    * @param filePath
    */
   public static void createFilefolderIFNotExist(String filePath){
      File f = new File(filePath);
       if(!f.exists()){
          if(!f.getParentFile().exists()){
             f.getParentFile().mkdirs();
          }
       }
   }
   /**
    * 秒转换小时-分-秒analytics/util/DateUtil.java
    *
    * @param seconds 秒为单位 比如..600秒
    * @return 比如...2小时3分钟52秒
    */
   public static String secToTime(int seconds) {
      int hour = seconds / 3600;
      int minute = (seconds - hour * 3600) / 60;
      int second = (seconds - hour * 3600 - minute * 60);
     * 手动记录特定日志
     */
    public static void record(int category, int type, String message,String messageDetail) {
        userLogService.add(category, type, message, messageDetail);
    }
      StringBuffer sb = new StringBuffer();
      if (hour > 0) {
         if(hour<10){
            sb.append("0"+hour + ":");
         }else{
            sb.append(hour + ":");
         }
      }else{
         sb.append("00"+ ":");
      }
      if (minute > 0) {
         if(minute<10){
            sb.append("0"+minute + ":");
         }else{
            sb.append(minute + ":");
         }
      }else{
         sb.append("00" + ":");
      }
      if (second > 0) {
         if(second<10){
            sb.append("0"+second);
         }else{
            sb.append(second);
         }
      }else{
         sb.append("00");
      }
      return sb.toString();
   }
   //获取当前系统的语言环境
   public static String getLang() {
      Locale locale = Locale.getDefault();//对Locale类实例化定义
      String lang = locale.getLanguage();
      String str = (String) CommonUtil.getSession().getAttribute("lang");
      if (str != null) {
         lang = str;
      }
      return lang;
   }
}