MyUtils

我的工具类

package com.ctsi.common.util;

import com.ctsi.xtusystem.entity.CourseStatisticsDTO;
import com.ctsi.xtusystem.entity.StatisticAnalysis;
import com.ctsi.xtusystem.service.MyUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class MyUtils {

    private MyUserService userService;

    public MyUtils(){
        userService = (MyUserService) ApplicationContextUtils.getBean("myUserServiceImpl");
    }


    //文件上传
    public static String  fileUpload(CommonsMultipartFile file)  throws IOException {



        long   startTime= 0;
        long   endTime= 0;

        try {
            startTime = System.currentTimeMillis();
            System.out.println( "fileName:" +file.getOriginalFilename());
            String newName = new Date().getTime() + file.getOriginalFilename();
            String path= "E:/" + newName;

            File newFile= new  File(path);
            //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
            file.transferTo(newFile);
            endTime = System.currentTimeMillis();
            return newName;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        System.out.println( "采用file.Transto的运行时间:" +String.valueOf(endTime-startTime)+ "ms" );
        return null;
    }

    //获取音频文件的时间长度
    //需要jave包支持 手动导入
    public static long ReadVideoTimeMs(MultipartFile file) {
        Encoder encoder = new Encoder();
        long ms = 0;
        try {
            // 获取文件类型
            String fileName = file.getContentType();
            // 获取文件后缀
            String pref = fileName.indexOf("/") != -1 ? fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()) : null;
            String prefix = "." + pref;
            // 用uuid作为文件名,防止生成的临时文件重复
            final File excelFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), prefix);
            // MultipartFile to File
            file.transferTo(excelFile);
            MultimediaInfo m = encoder.getInfo(excelFile);
            ms = m.getDuration();
            //程序结束时,删除临时文件
            deleteFile(excelFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(ms != 0){
            return  ms/1000;
        }else {
            return 0;
        }
       /* int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;

        String strHour = hour < 10 ? "0" + hour : "" + hour;//小时
        String strMinute = minute < 10 ? "0" + minute : "" + minute;//分钟
        String strSecond = second < 10 ? "0" + second : "" + second;//秒
        if (strHour.equals("00")) {
            return strMinute + ":" + strSecond;
        } else {
            return strHour + ":" + strMinute + ":" + strSecond;
        }*/
    }

    private static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }



    //搭配stream 的 filter使用
    public static boolean filterData(CourseStatisticsDTO courseStatisticsDTO, String userName, String studyStatus, String startTime, String endTime){
        boolean userNameBln = true;
        boolean studyStatusBln = true;
        boolean timeBln = true;
        if (StringUtils.isNotBlank(userName)) {
            userNameBln = courseStatisticsDTO.getUserName().equals(userName);
        }
        if (StringUtils.isNotBlank(studyStatus)) {
            studyStatusBln = courseStatisticsDTO.getLearnStatus().equals(studyStatus);
        }
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            String studyTime = courseStatisticsDTO.getLastStartTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date time = null;
            Date start = null;
            Date end = null;
            try {
                time = simpleDateFormat.parse(studyTime);
                start = simpleDateFormat.parse(startTime);
                end=  simpleDateFormat.parse(endTime);
            }catch (Exception e){
                e.printStackTrace();
            }
            int s = time.compareTo(start);
            int e = time.compareTo(end);
             timeBln = s >= 0 && e <= 0? true:false;
        }
        return userNameBln && studyStatusBln && timeBln;
        }


    public static boolean filterData(StatisticAnalysis statisticDTO, String courseName, String name){
        boolean courseNameBln = true;
        boolean nameBln = true;
        if (StringUtils.isNotBlank(name)) {
            nameBln = statisticDTO.getName().equals(name);
        }
        if (StringUtils.isNotBlank(courseName)) {
            courseNameBln = statisticDTO.getCourseName().equals(courseName);
        }

        return nameBln && courseNameBln;
    }


    //对一个List进行分页处理
    public static List startPage(List list, Integer pageNum,
                                 Integer pageSize) {
        if (list == null || list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        List pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }

    //string 转 cron格式
    public static String formatDateByPattern(Date date,String dateFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTimeStr = null;
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    public static String getCron(java.util.Date  date){
        String dateFormat="ss mm HH dd MM ?";
        //String dateFormat="ss mm HH dd MM ? yyyy";
        return formatDateByPattern(date, dateFormat);
    }

    /**
     * 通过list的     subList(int fromIndex, int toIndex)方法实现
     * @param sourList 源list
     * @param batchCount 分组条数
     */
    public static List<List> dealBySubList(List sourList, int batchCount){
        List<List> rtnList = new ArrayList();
        int sourListSize = sourList.size();
        int subCount = sourListSize%batchCount==0 ? sourListSize/batchCount : sourListSize/batchCount+1;
        int startIndext = 0;
        int stopIndext = 0;
        for(int i=0;i<subCount;i++){
            stopIndext = (i==subCount-1) ? stopIndext + sourListSize%batchCount : stopIndext + batchCount;
            List tempList = new ArrayList<>(sourList.subList(startIndext, stopIndext));
            rtnList.add(tempList);
            printList(tempList);
            startIndext = stopIndext;
        }
        return rtnList;
    }

    /**
     * 通过源list数据的逐条转移实现
     * @param sourList 源list
     * @param batchCount 分组条数
     */
    public static void dealByRemove(List sourList, int batchCount){
        List<Object> tempList = new ArrayList<Object>();
        for (int i = 0; i < sourList.size(); i++) {
            tempList.add(sourList.get(i));
            if((i+1)%batchCount==0 || (i+1)==sourList.size()){
                printList(tempList);
                tempList.clear();
            }
        }
    }


    public static void printList(List<Object> sourList){
        for(int j=0;j<sourList.size();j++){
            System.out.println(sourList.get(j));
        }
        System.out.println("------------------------");
    }


    //传入 部门的Ids
    //查询出所有的用户名  封装进一个集合 然后会根据集合进行分组 每1000为一组 然后每一组循环遍历 凭借成一个大的字符串
    public List<StringBuilder> getUserAccount(String deptIds){
        List<StringBuilder> stringBuilderList = new ArrayList<>();
        List<String> idsStr = new ArrayList<>();
        if(deptIds != null){
            String[] ids = deptIds.split(",");
            idsStr = userService.getDeptsUserAccount(Arrays.asList(ids));
        }else {
            idsStr = userService.getDeptsUserAccount(null);
        }
        System.out.println("isdStr----------------------"+idsStr);
        int size = idsStr.size();
        if(size > 0 && size < 1000){
            StringBuilder rtn = new StringBuilder();
            idsStr.forEach(str->{
                rtn.append(str+",");
            });
            rtn.deleteCharAt(rtn.length()-1);
            stringBuilderList.add(rtn);
        }else if(size > 1000){
            List<List> lists = MyUtils.dealBySubList(idsStr, 1000);
            lists.forEach(list->{
                StringBuilder rtn = new StringBuilder();
                list.forEach(str->{
                    rtn.append(str+",");
                });
                if(rtn!=null && !rtn.equals("")){
                    System.out.println(rtn);
                    rtn.deleteCharAt(rtn.length()-1);
                }
                stringBuilderList.add(rtn);
            });
        }else {
            stringBuilderList.add(null);
        }

        return stringBuilderList;
    }

    public static Map<String,String> getWeekDate() {
        Map<String,String> map = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if(dayWeek==1){
            dayWeek = 8;
        }
        System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期

        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        Date mondayDate = cal.getTime();
        String weekBegin = sdf.format(mondayDate);
        System.out.println("所在周星期一的日期:" + weekBegin);


        cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
        Date sundayDate = cal.getTime();
        String weekEnd = sdf.format(sundayDate);
        System.out.println("所在周星期日的日期:" + weekEnd);

        map.put("mondayDate", weekBegin);
        map.put("sundayDate", weekEnd);
        return map;
    }

    public static File multipartFileToFile(MultipartFile file) throws IOException {
        // 获取文件类型
        String fileName = file.getContentType();
        // 获取文件后缀
        String pref = fileName.indexOf("/") != -1 ? fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()) : null;
        String prefix = "." + pref;
        // 用uuid作为文件名,防止生成的临时文件重复
        final File excelFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), prefix);
        // MultipartFile to File
        file.transferTo(excelFile);
        return excelFile;
    }

    public static String dislodgeHTML(String s){
        return s.replaceAll("<[^>]*>", "\n\t");
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值