diff --git a/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/domain/SysFileSource.java b/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/domain/SysFileSource.java new file mode 100644 index 0000000..ef19c9a --- /dev/null +++ b/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/domain/SysFileSource.java @@ -0,0 +1,100 @@ +package com.bonus.system.api.domain; + +import com.bonus.common.core.web.domain.BaseEntity; + +public class SysFileSource extends BaseEntity{ + + private String fileName; + + private String fileSuffix; + + private String filePath; + + private int fileType; + + + private String sourceId; + + private String sourceType; + + private String createUser; + + private Long id; + + private String updateUser; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getFileSuffix() { + return fileSuffix; + } + + public void setFileSuffix(String fileSuffix) { + this.fileSuffix = fileSuffix; + } + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public int getFileType() { + return fileType; + } + + public void setFileType(int fileType) { + this.fileType = fileType; + } + + public String getSourceId() { + return sourceId; + } + + public void setSourceId(String sourceId) { + this.sourceId = sourceId; + } + + public String getSourceType() { + return sourceType; + } + + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } + + public String getCreateUser() { + return createUser; + } + + public void setCreateUser(String createUser) { + this.createUser = createUser; + } + + + + public String getUpdateUser() { + return updateUser; + } + + public void setUpdateUser(String updateUser) { + this.updateUser = updateUser; + } +} diff --git a/bonus-common/bonus-common-core/src/main/java/com/bonus/common/core/utils/BASE64DecodedMultipartFile.java b/bonus-common/bonus-common-core/src/main/java/com/bonus/common/core/utils/BASE64DecodedMultipartFile.java new file mode 100644 index 0000000..95ee01c --- /dev/null +++ b/bonus-common/bonus-common-core/src/main/java/com/bonus/common/core/utils/BASE64DecodedMultipartFile.java @@ -0,0 +1,147 @@ +package com.bonus.common.core.utils; + +import cn.hutool.core.codec.Base64; +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.multipart.MultipartFile; +import sun.misc.BASE64Decoder; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.*; + +/** + * @author:cwchen + * @date:2024-06-11 17:53-10:10 + * @version:1.0 + * @description:字节数组转文件 + */ +public class BASE64DecodedMultipartFile implements MultipartFile { + + private final byte[] imgContent; + private final String header; + private final static String IMG_PREFIX = "data:image/jpeg;base64"; + + public BASE64DecodedMultipartFile(byte[] imgContent, String header) { + this.imgContent = imgContent; + this.header = header.split(";")[0]; + } + + @Override + public String getName() { + return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; + } + + @Override + public String getOriginalFilename() { + return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1]; + } + + @Override + public String getContentType() { + return header.split(":")[1]; + } + + @Override + public boolean isEmpty() { + return imgContent == null || imgContent.length == 0; + } + + @Override + public long getSize() { + return imgContent.length; + } + + @Override + public byte[] getBytes() throws IOException { + return imgContent; + } + + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(imgContent); + } + + @Override + public void transferTo(File dest) throws IOException, IllegalStateException { + new FileOutputStream(dest).write(imgContent); + } + + public static MultipartFile base64ToMultipart(String base64) { + try { + String[] baseStrs = base64.split(","); + + BASE64Decoder decoder = new BASE64Decoder(); + byte[] b = new byte[0]; + b = decoder.decodeBuffer(baseStrs[1]); + + for (int i = 0; i < b.length; ++i) { + if (b[i] < 0) { + b[i] += 256; + } + } + + return new BASE64DecodedMultipartFile(b, baseStrs[0]); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static MultipartFile base64ToMultipart2(String base64) { + try { + if (StringUtils.isEmpty(base64)) { + return null; + } + String[] baseStrs = base64.split(","); + if (baseStrs.length == 1) { + BASE64Decoder decoder = new BASE64Decoder(); + byte[] b = new byte[0]; + b = decoder.decodeBuffer(baseStrs[0]); + + for (int i = 0; i < b.length; ++i) { + if (b[i] < 0) { + b[i] += 256; + } + } + return new BASE64DecodedMultipartFile(b, IMG_PREFIX); + } else if (baseStrs.length == 2) { + BASE64Decoder decoder = new BASE64Decoder(); + byte[] b = new byte[0]; + b = decoder.decodeBuffer(baseStrs[1]); + + for (int i = 0; i < b.length; ++i) { + if (b[i] < 0) { + b[i] += 256; + } + } + return new BASE64DecodedMultipartFile(b, baseStrs[0]); + } + return null; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + + public static String getBase64(String path) { + File file = new File(path); + String base64 = null; + try { + BufferedImage image = ImageIO.read(file); + Integer width = image.getWidth(); + Integer height = image.getHeight(); + System.out.println("宽:" + width + " 高:" + height); + + //输出流 + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + ImageIO.write(image, "png", stream); + base64 = Base64.encode(stream.toByteArray()); + System.out.println(base64); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return base64; + } +} \ No newline at end of file diff --git a/bonus-common/bonus-common-core/src/main/java/com/bonus/common/core/utils/DateTimeHelper.java b/bonus-common/bonus-common-core/src/main/java/com/bonus/common/core/utils/DateTimeHelper.java new file mode 100644 index 0000000..722d5a9 --- /dev/null +++ b/bonus-common/bonus-common-core/src/main/java/com/bonus/common/core/utils/DateTimeHelper.java @@ -0,0 +1,931 @@ +package com.bonus.common.core.utils; + +import lombok.extern.slf4j.Slf4j; + +import java.text.*; +import java.time.*; +import java.util.*; + +import static org.apache.commons.lang3.time.DateUtils.parseDate; + + +/** + * @author HeiZi + */ +@Slf4j +public class DateTimeHelper { + + + private static String[] parsePatterns = { + "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", + "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", + "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; + + public static String format(Date d, String f) { + SimpleDateFormat df = new SimpleDateFormat(f, Locale.US); + return df.format(d); + } + + public static boolean compareMonth(String time, String now) { + try { + int year = Integer.parseInt(time.split("-")[0].trim()); + int month = Integer.parseInt(time.split("-")[1].trim()); + int year1 = Integer.parseInt(now.split("-")[0].trim()); + int month1 = Integer.parseInt(now.split("-")[1].trim()); + if (year > year1) { + return false; + } + if (year == year1) { + if (month >= month1) { + return false; + } + } + return true; + + } catch (Exception e) { + log.error(e.toString(), e); + } + return false; + } + + /** + * 增加 LocalDateTime ==> Date + */ + public static Date toDate(LocalDateTime temporalAccessor) { + ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault()); + return Date.from(zdt.toInstant()); + } + + /** + * 增加 LocalDate ==> Date + */ + public static Date toDate(LocalDate temporalAccessor) { + LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0)); + ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault()); + return Date.from(zdt.toInstant()); + } + + + public static String dateTimeNow() { + return dateTimeNow("yyyyMMddHHmmss"); + } + + + public static String dateTimeNow(final String format) { + return parseDateToStr(format, new Date()); + } + + public static String parseDateToStr(final String format, final Date date) { + return new SimpleDateFormat(format).format(date); + } + + + /** + * 日期型字符串转化为日期 格式 + */ + public static Date parseDates(Object str) { + if (str == null) { + return null; + } + try { + return parseDate(str.toString(), parsePatterns); + } catch (ParseException e) { + return null; + } + } + + /** + * 获取当前时间 + * + * @return + */ + public static String getNowTime() { + return format(new Date(), "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 获取当前时间的年份 + * + * @return + */ + public static String getNowYear() { + return format(new Date(), "yyyy"); + } + + + /** + * 获取当前月份 + * + * @return + */ + public static String getNowMonths() { + return format(new Date(), "MM"); + } + + /** + * 获取当前小时 + * + * @return + */ + public static String getNowHours() { + return format(new Date(), "HH"); + } + + + public static String getNowYmd() { + return new SimpleDateFormat("yyyyMMdd").format(new Date()); + } + + + public static String getNowDay() { + return new SimpleDateFormat("yyyy-MM-dd").format(new Date()); + } + + public static String getTimesUpDown(String time) { + try { + if (StringUtils.isEmpty(time)) { + return time; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = sdf.parse(time); + // 创建Calendar对象,表示当前时间 + Calendar calendar = Calendar.getInstance(); + // 将Calendar对象设置为当前时间 + calendar.setTime(date); + // 将时间减去5分钟 + calendar.add(Calendar.MINUTE, -5); + calendar.add(Calendar.SECOND, -13); + // 获取减去5分钟后的时间 + Date newTime = calendar.getTime(); + return sdf.format(newTime); + } catch (ParseException e) { + e.printStackTrace(); + } + return time; + } + + public static String getNextDay() { + Calendar calendar = Calendar.getInstance(); + // 对日期进行加1天的操作 + calendar.add(Calendar.DAY_OF_MONTH, 1); + // 获取明天的年、月、日 + int year = calendar.get(Calendar.YEAR); + // 注意:月份从0开始计算 + int month = calendar.get(Calendar.MONTH) + 1; + int day = calendar.get(Calendar.DAY_OF_MONTH); + return year + "-" + month + "-" + day; + } + + + public static String getHouDay() { + Date date = new Date(); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(new Date()); + // 把日期往后增加一天.整数往后推,负数往前移动 + calendar.add(Calendar.DATE, 1); + // 这个时间就是日期往后推一天的结果 + date = calendar.getTime(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(date); + } + + @SuppressWarnings("static-access") + public static String getYesTodayt() { + Date date = new Date(); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(new Date()); + // 把日期往后增加一天.整数往后推,负数往前移动 + calendar.add(calendar.DATE, -1); + date = calendar.getTime(); + // 这个时间就是日期往后推一天的结果 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(date); + } + + @SuppressWarnings("static-access") + public static String getQtDay() { + Date date = new Date(); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(new Date()); + // 把日期往后增加一天.整数往后推,负数往前移动 + calendar.add(calendar.DATE, -2); + // 这个时间就是日期往后推一天的结果 + date = calendar.getTime(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(date); + } + + + public static String format(String str, String format, String disFormat) { + Date d = parse(str, format); + return format(d, disFormat); + } + + /** + * 格式化 时间 + * + * @param format + * @return + */ + public static String format(Date d, DateFormat format) { + return format.format(d); + } + + /** + * 格式化 时间 + * + * @param format + * @return Date + * @throws ParseException + */ + public static Date parse(String dateStr, String format) { + SimpleDateFormat df = new SimpleDateFormat(format); + try { + return df.parse(dateStr); + } catch (ParseException e) { + return new Date(); + } + } + + public static Date parse(String dateStr, String format, Date d) { + try { + SimpleDateFormat df = new SimpleDateFormat(format); + return df.parse(dateStr); + } catch (Exception e) { + return d; + } + } + + /** + * 解析时间 + * + * @return Date + * @throws ParseException + */ + public static Date parse(String dateStr, DateFormat format) throws ParseException { + return format.parse(dateStr); + } + + /** + * 获取当前时间的年月 + * + * @return + */ + public static String getPrevMonth() { + return minusMonth(new Date(), 1); + } + + /** + * 获取当前时间的上个年月 + * + * @return + */ + public static String getNowMonth() { + return format(new Date(), "yyyy-MM"); + } + + /** + * 获取当前时间的年月日 + * + * @return + */ + public static String getNowDate() { + return format(new Date(), "yyyy-MM-dd"); + } + + /** + * @return + */ + public static String minusMonth(Date date, int c) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM"); + try { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.MONTH, -c); + return format(cal.getTime(), df); + } catch (Exception e) { + return format(date, df); + } + } + + /** + * @param month + * @return + */ + public static String minusMonth(String month, int c) { + try { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM"); + Date date = parse(month, df); + + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.MONTH, -c); + + return format(cal.getTime(), df); + } catch (Exception e) { + return month; + } + } + + /** + * @return + */ + public static Date minus(Date d, int type, int c) { + try { + Calendar cal = Calendar.getInstance(); + cal.setTime(d); + cal.add(type, -c); + return cal.getTime(); + } catch (Exception e) { + return new Date(); + } + } + + private static String[] digits = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}; + + public static String getWeekTimes(String time) { + try { + int month = Integer.parseInt(time.split("-")[1].trim()); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + Date date = df.parse(time); + Calendar cal = Calendar.getInstance(); + cal.setFirstDayOfWeek(Calendar.MONDAY); + cal.setTime(date); + int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); + String msg = digits[weekOfMonth]; + return month + "月" + msg + "周"; + } catch (Exception e) { + log.error(e.toString(), e); + } + return null; + } + + + public static String getAddMonth(String time, int num) { + try { + Integer year = Integer.parseInt(time.split("-")[0].trim()); + Integer month = Integer.parseInt(time.split("-")[1].trim()); + YearMonth yearMonth = YearMonth.of(year, month); + YearMonth addedMonth = yearMonth.plusMonths(1); + return addedMonth.toString(); + } catch (Exception e) { + log.error(e.toString(), e); + } + return null; + + } + + /** + * 获取七周日期 + * + * @return + */ + public static List getWeekList() { + List list = new ArrayList<>(); + String time = DateTimeHelper.getNowDay(); + int max = 6; + for (int i = max; i >= 1; i--) { + String timess = getDayAddOrReduce(time, -7 * i); + list.add(timess); + } + list.add(time); + return list; + } + + + /** + * 得到前一个月 + * + * @param month + * @return + */ + public static String prevMonth(String month) { + return minusMonth(month, 1); + } + + /** + * 得到前一个月 + * + * @param month + * @return + */ + public static String prevMonth(String month, int c) { + return minusMonth(month, c); + } + + public static float duration(String startTime, String stopTime) { + Date sd = DateTimeHelper.parse(startTime, "yyyy-MM-dd HH:mm"); + long sl = sd.getTime(); + + Date ed = DateTimeHelper.parse(stopTime, "yyyy-MM-dd HH:mm"); + long el = ed.getTime(); + + float l = el - sl; + if (l <= 0) { + l = 0; + } + l = l / (1000 * 60); + return l; + } + + public static String getStartYearMonthBySeason(String year, int season) { + switch (season) { + case 1: + return getYearMonth(year, "01"); + case 2: + return getYearMonth(year, "04"); + case 3: + return getYearMonth(year, "07"); + case 4: + return getYearMonth(year, "10"); + default: + return getYearMonth(year, "01"); + } + } + + private static String getYearMonth(String year, String month) { + return year + "-" + month; + } + + public static String getEndYearMonthBySeason(String year, int season) { + switch (season) { + case 1: + return getYearMonth(year, "03"); + case 2: + return getYearMonth(year, "06"); + case 3: + return getYearMonth(year, "09"); + case 4: + return getYearMonth(year, "12"); + default: + return getYearMonth(year, "03"); + } + } + + /** + * 获取本周的时间段 本周一至本周日 + * + * @return + */ + public static String getCurrentWeekTime() { + String result = ""; + String currentDay = getNowDay(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + Date time; + try { + time = sdf.parse(currentDay); + cal.setTime(time); + System.out.println("要计算日期为:" + sdf.format(cal.getTime())); + + //判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了//获得当前日期是一个星期的第几天 + int dayWeek = cal.get(Calendar.DAY_OF_WEEK); + if (1 == dayWeek) { + cal.add(Calendar.DAY_OF_MONTH, -1); + } + //设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一 + cal.setFirstDayOfWeek(Calendar.MONDAY); + //获得当前日期是一个星期的第几天 + int day = cal.get(Calendar.DAY_OF_WEEK); + //根据日历的规则,给当前日期减去星期几与一个星期第一天的差值 + cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day); + System.out.println("所在周一的日期:" + sdf.format(cal.getTime())); + result += sdf.format(cal.getTime()); + System.out.println(cal.getFirstDayOfWeek() + "-" + day + "+6=" + (cal.getFirstDayOfWeek() - day + 6)); + + cal.add(Calendar.DATE, 6); + result += "," + sdf.format(cal.getTime()); + System.out.println("所在下周日的日期:" + sdf.format(cal.getTime())); + return result; + + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 获取下周的开始时间和结束时间 + * + * @return + */ + public static String getNextWeekTime() { + Date date = getBeginDayOfWeek(); + String time = format(date, "yyyy-MM-dd"); + Date date2 = getEndDayOfWeek(); + String time2 = format(date2, "yyyy-MM-dd"); + + return time + "," + time2; + } + + public static Date getBeginDayOfWeek() { + Date date = new Date(); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int dayofweek = cal.get(Calendar.DAY_OF_WEEK); + cal.add(Calendar.WEEK_OF_MONTH, 1); + if (dayofweek == 1) { + dayofweek += 7; + } + cal.add(Calendar.DATE, 2 - dayofweek); + return cal.getTime(); + } + + /** + * 获取前一周的开始和结束时间 + * + * @return + */ + public static String getPrevWeek() { + Date date = getBeginDayOfPrevWeek(); + String time = format(date, "yyyy-MM-dd"); + Date date2 = getEndDayOfPrevWeek(); + String time2 = format(date2, "yyyy-MM-dd"); + + return time + "," + time2; + } + + /** + * 获取前一周的开始时间 + * + * @return + */ + public static Date getBeginDayOfPrevWeek() { + Date date = new Date(); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int dayofweek = cal.get(Calendar.DAY_OF_WEEK); + cal.add(Calendar.WEEK_OF_MONTH, -1); + if (dayofweek == 1) { + dayofweek -= 7; + } + cal.add(Calendar.DATE, 2 - dayofweek); + return cal.getTime(); + } + + public static Date getEndDayOfPrevWeek() { + Calendar cal = Calendar.getInstance(); + cal.setTime(getBeginDayOfPrevWeek()); + cal.add(Calendar.DAY_OF_WEEK, 6); + Date weekEndSta = cal.getTime(); + return weekEndSta; + } + + + /** + * 获取指定时间 当前周的周一至周日的时间 + * + * @return + */ + public static List getWeekDataList(String time) { + List week = new ArrayList(); + try { + if (StringUtils.isEmpty(time)) { + time = DateTimeHelper.getNowDay(); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date dataTime = sdf.parse(time); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(dataTime); + // 如果是周日 + if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { + calendar.add(Calendar.DAY_OF_YEAR, -1); + } + // 获取当前日期是当周的第i天 + int i = calendar.get(Calendar.DAY_OF_WEEK) - 1; + // 获取当前日期所在周的第一天 + calendar.add(Calendar.DATE, -i + 1); + int max = 7; + for (int j = 0; j < max; j++) { + if (j > 0) { + calendar.add(Calendar.DATE, 1); + } + week.add(sdf.format(calendar.getTime())); + System.err.println(sdf.format(calendar.getTime())); + } + return week; + } catch (Exception e) { + log.error(e.toString(), e); + } + return week; + } + + /** + * 仁义日期加减 + * + * @return + */ + public static String getDayAddOrReduce(String time, int num) { + String returnTime = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date dataTime = sdf.parse(time); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(dataTime); + // 如果是周日 + if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { + calendar.add(Calendar.DAY_OF_YEAR, -1); + } + calendar.add(Calendar.DATE, num); + return sdf.format(calendar.getTime()); + } catch (Exception e) { + log.error(e.toString(), e); + } + return returnTime; + } + + /** + * 周开始和周结束时间 + * + * @param time + * @param isStart + * @return + */ + public static String getWeekStartOrEndTime(String time, boolean isStart) { + String returnTime = null; + try { + if (StringUtils.isEmpty(time)) { + time = DateTimeHelper.getNowDay(); + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date dataTime = sdf.parse(time); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(dataTime); + // 如果是周日 + if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { + calendar.add(Calendar.DAY_OF_YEAR, -1); + } + // 获取当前日期是当周的第i天 + int i = calendar.get(Calendar.DAY_OF_WEEK) - 1; + // 获取当前日期所在周的第一天 + calendar.add(Calendar.DATE, -i + 1); + if (isStart) { + return sdf.format(calendar.getTime()); + } else { + calendar.add(Calendar.DATE, 6); + return sdf.format(calendar.getTime()); + } + + } catch (Exception e) { + log.error(e.toString(), e); + } + + return returnTime; + } + + /** + * 获取当前日期是多少周 周 + * + * @return + */ + public static int getNowWeeks(String time) { + try { + Date date = new Date(); + if (StringUtils.isNotEmpty(time)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + date = sdf.parse(time); + } + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + // 获取一年中的第几周 + int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR); + return weekOfYear; + } catch (Exception e) { + log.error(e.toString(), e); + return 0; + } + } + + + /** + * 获取前一天的日期 + * + * @return + */ + public static String getFrontDay() { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date = new Date(); + Calendar now = Calendar.getInstance(); + now.setTime(date); + now.add(Calendar.DAY_OF_MONTH, -1); + return sdf.format(now.getTime()); + + } + + public static Date getEndDayOfWeek() { + Calendar cal = Calendar.getInstance(); + cal.setTime(getBeginDayOfWeek()); + cal.add(Calendar.DAY_OF_WEEK, 6); + Date weekEndSta = cal.getTime(); + return weekEndSta; + } + + /** + * 获取两个时间之间的所有日期 + * + * @param startTime + * @param endTime + * @return + */ + public static List getBetweenDate(String startTime, String endTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + List list = new ArrayList<>(); + try { + //转化日期类型 + Date startDate = sdf.parse(startTime); + Date endDate = sdf.parse(endTime); + //用calendar 进行日期比较判断 + Calendar calendar = Calendar.getInstance(); + while (startDate.getTime() <= endDate.getTime()) { + //把日期添加到集合中 + list.add(sdf.format(startDate)); + //设置日期 + calendar.setTime(startDate); + + //把日期加一天 + calendar.add(Calendar.DATE, 1); + + //获取增加后的日期 + startDate = calendar.getTime(); + } + + } catch (ParseException e) { + e.printStackTrace(); + } + return list; + } + + /** + * @return float + * @Author ccw + * @Description 秒换算成小时 + * @Date 14:08 2022/6/24 + * @Param [seconds] + */ + public static String getHours(int seconds) { + NumberFormat numberFormat = NumberFormat.getInstance(); + //保留几位小数填写几 + numberFormat.setMaximumFractionDigits(3); + return numberFormat.format((float) seconds / (float) 3600); + } + + /** + * @return int + * @Author ccw + * @Description 时间差 + * @Date 14:05 2022/6/24 + * @Param [startTime, endTime] + */ + public static int getTimeDifference2(String startTime, String endTime) throws ParseException { + SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = simpleFormat.parse(startTime); + long time = date.getTime(); + Date date2 = simpleFormat.parse(endTime); + long time2 = date2.getTime(); + long timestamp = time2 - time; + return (int) (timestamp / 1000); + } + + /** + * 小时差 + * + * @param endTime + * @param startTime + * @return + * @throws ParseException + */ + public static Double getTimeHours(String endTime, String startTime) throws ParseException { + try { + SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date st = simpleFormat.parse(startTime); + Date et = simpleFormat.parse(endTime); + long time = et.getTime() - st.getTime(); + DecimalFormat decimalFormat = new DecimalFormat("0.00"); + String format = decimalFormat.format(time * 1.0 / 3600000 * 1.0); + return Double.valueOf(format); + } catch (Exception e) { + return 0.0; + } + } + + /** + * 分钟差 + * + * @param endTime + * @param startTime + * @return + * @throws ParseException + */ + public static Long getTimeMine(String endTime, String startTime) throws ParseException { + try { + SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date st = simpleFormat.parse(startTime); + Date et = simpleFormat.parse(endTime); + long time = et.getTime() - st.getTime(); + double times = Double.parseDouble(time + ""); + double b = times / 1000 / 60; + return time / 1000 / 60; + } catch (Exception e) { + return 0L; + } + } + + /** + * 日期解析为时间戳 + * + * @param dateString + * @param format + * @return Long + * @description + * @author cwchen + * @date 2024/3/16 15:11 + */ + public static Long convertDateStringToTimestamp(String dateString, String format) { + Date date = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat(format); + date = sdf.parse(dateString); + } catch (ParseException e) { + log.error("日期解析为时间戳异常", e); + return null; + } + return date.getTime(); + } + + /** + * 两个日期之间的差值 + * + * @param startDate + * @param endDate + * @return Long + * @description + * @author cwchen + * @date 2024/3/28 20:38 + */ + public static Long getDayDifference(String startDate, String endDate) { + if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) { + return 0L; + } + DateFormat dft = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date star = dft.parse(startDate); + Date endDay = dft.parse(endDate); + Long starTime = star.getTime(); + Long endTime = endDay.getTime(); + Long num = endTime - starTime; + System.out.println("相差天数为:" + num / 24 / 60 / 60 / 1000); + return (num / 24 / 60 / 60 / 1000) + 1; + } catch (ParseException e) { + log.error("两个日期之间的差值", e); + return 0L; + } + } + + /** + * 获取当前月的第一天和最后一天 + */ + public static String getMonthFirstAndLastDay() { + Calendar a = Calendar.getInstance(); + //把日期设置为当月第一天 + a.set(Calendar.DATE, 1); + //日期回滚一天,也就是最后一天 + a.roll(Calendar.DATE, -1); + //当月有多少天 + int maxDate = a.get(Calendar.DATE); + SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-"); + String startTime = sdfTwo.format(new Date()) + "01"; + String endTime = sdfTwo.format(new Date()) + maxDate; + return startTime + " - " + endTime; + } + + /** + * 比较两个时间 + * @param startTime + * @param endTime + * @return boolean + * @description + * @author cwchen + * @date 2024/4/24 9:55 + */ + public static boolean compareTime(String startTime, String endTime) { + Long aLong = convertDateStringToTimestamp(startTime, "yyyy-MM-dd"); + Long bLong = convertDateStringToTimestamp(endTime, "yyyy-MM-dd"); + if (aLong > bLong) { + return false; + } + return true; + } + + /** + * 将时间戳转换为时间 + */ + public static String stampToDate(String stap) { + String time; + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + long lt = new Long(stap); + Date date = new Date(lt * 1000); + time = simpleDateFormat.format(date); + return time; + } +} diff --git a/bonus-common/bonus-common-entity/src/main/java/com/bonus/common/entity/DeviceUseVo.java b/bonus-common/bonus-common-entity/src/main/java/com/bonus/common/entity/DeviceUseVo.java new file mode 100644 index 0000000..703fc8f --- /dev/null +++ b/bonus-common/bonus-common-entity/src/main/java/com/bonus/common/entity/DeviceUseVo.java @@ -0,0 +1,56 @@ +package com.bonus.common.entity; + +import lombok.Data; + +import java.util.Date; + +/** + * @className:DeviceUseVo + * @author:cwchen + * @date:2024-08-27-15:36 + * @version:1.0 + * @description:设备领用-vo + */ +@Data +public class DeviceUseVo { + private Long id; + /**设备ID*/ + private Long devId; + + /**工程ID*/ + private Long proId; + /**班组ID*/ + private Long teamId; + /**杆塔ID*/ + private Long gtId; + /**人员身份证号*/ + private String idCard; + /**人员ID*/ + private Long userId; + /**告警内容*/ + private String warnContent; + /**告警时间*/ + private String warnTime; + /**告警类型 1 设备告警 2 违章识别 3 带电体告警*/ + private String warnType = "2"; + private Date createTime = new Date(); + /**删除状态*/ + private Integer delFlag = 0; + /**设备关联类型 0手环 1设备*/ + private Integer devType = 1; + /**人员类型 0默认 1 临时人员*/ + private Integer peopleType = 0; + + private String bidId; + /**设备ID*/ + private Integer bindDevId; + + /**设备ID*/ + private String bidTime; + + // 设备负责人 + private String deviceUser; + + + +} diff --git a/bonus-common/bonus-common-entity/src/main/java/com/bonus/common/entity/PeopleVioVo.java b/bonus-common/bonus-common-entity/src/main/java/com/bonus/common/entity/PeopleVioVo.java new file mode 100644 index 0000000..f78b3e1 --- /dev/null +++ b/bonus-common/bonus-common-entity/src/main/java/com/bonus/common/entity/PeopleVioVo.java @@ -0,0 +1,21 @@ +package com.bonus.common.entity; + +import lombok.Data; + +/** + * @className:PeopleVioVo + * @author:cwchen + * @date:2024-08-27-16:06 + * @version:1.0 + * @description:人员违章-vo + */ +@Data +public class PeopleVioVo { + + /**人员ID*/ + private Long id; + /**姓名*/ + private String name; + /**人员类别 0-班组成员 1-临时人员*/ + private Integer peopleType; +} diff --git a/bonus-modules/bonus-project/pom.xml b/bonus-modules/bonus-project/pom.xml index a451dce..55f7adb 100644 --- a/bonus-modules/bonus-project/pom.xml +++ b/bonus-modules/bonus-project/pom.xml @@ -138,7 +138,11 @@ spring-boot-starter-test test - + + dom4j + dom4j + 1.6.1 + org.junit.vintage junit-vintage-engine diff --git a/bonus-modules/bonus-project/src/main/java/com/bonus/project/controller/SmartIdentifyController.java b/bonus-modules/bonus-project/src/main/java/com/bonus/project/controller/SmartIdentifyController.java new file mode 100644 index 0000000..7254687 --- /dev/null +++ b/bonus-modules/bonus-project/src/main/java/com/bonus/project/controller/SmartIdentifyController.java @@ -0,0 +1,213 @@ +package com.bonus.project.controller; + +import com.bonus.common.core.utils.BASE64DecodedMultipartFile; +import com.bonus.common.core.utils.DateTimeHelper; +import com.bonus.common.entity.DeviceUseVo; +import com.bonus.common.redis.service.RedisService; +import com.bonus.project.service.SmartIdentifyService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +/** + * @className:SmartIdentifyController + * @author:cwchen + * @date:2024-08-27-14:26 + * @version:1.0 + * @description:球机智能识别 + */ +@Slf4j +@RestController +@RequestMapping("/ball") +public class SmartIdentifyController { + + @Autowired + private RedisService redisService; + + @Autowired + private SmartIdentifyService service; + + public static final ReentrantLock BED_LOCK = new ReentrantLock(); + + /** + * 事件id集合 + * E_IVS_HelmetNotWear :未带安全帽 + * E_IVS_Smoking :抽烟报警 + * E_IVS_NotWear3ColorVest :未穿三色马甲报警 + */ + public static List eventIds = new ArrayList<>(); + + { + eventIds.add("E_IVS_HelmetNotWear"); + eventIds.add("E_IVS_Smoking"); + eventIds.add("E_IVS_NotWear3ColorVest"); + } + + /** + * 清新互联平台事件推送接口 + * + * @param xml + * @return + */ + @PostMapping("xmlAnalysis") + public String xmlAnalysis(@RequestBody String xml) { + try { + // 设置对象锁 + boolean flag = BED_LOCK.tryLock(10L * 1000L, TimeUnit.MILLISECONDS); + if (flag) { + boolean existence = false; + //解析xml字符串为Document + Document doc = null; + //事件ID + String evenID = null; + //身份证号 + String idCard = null; + //事件时间 + String eventTime = DateTimeHelper.getNowTime(); + //解析xml内容 + doc = DocumentHelper.parseText(xml); + //获取根节点 + Element root = doc.getRootElement(); + //获取根节点下的所有M子节点 + Iterator it = root.elementIterator("E"); + //获取单个事件 + if (it != null) { + Element element = (Element) it.next(); + String id = element.attributeValue("ID"); + evenID = id; + //获取事件发生时间 + if (StringUtils.isNotBlank(element.attributeValue("Time"))) { + eventTime = DateTimeHelper.stampToDate(element.attributeValue("Time")); + } + Iterator desc2Interator = element.elementIterator("Desc2"); + if (desc2Interator != null) { + Element idCardEle = (Element) desc2Interator.next(); + idCard = idCardEle.attributeValue("IDCard"); + } + Iterator srcInterator = element.elementIterator("Src"); + String ballName = null; + if (srcInterator != null) { + Element headEle = (Element) srcInterator.next(); + String puid = headEle.attributeValue("ID"); + // 十分钟内存在该事件,直接返回 + Object cacheObject = redisService.getCacheObject(evenID + "_" + puid); + if (Objects.nonNull(cacheObject)) { + log.info("十分钟内存在该事件"); + return "error"; + } + Iterator resInterator = headEle.elementIterator("Res"); + if (resInterator != null) { + Element nameEle = (Element) resInterator.next(); + ballName = nameEle.attributeValue("Name"); + } + boolean sf = eventIds.contains(evenID); + List devices = null; + if (sf) { + devices = service.getDevices(puid); + existence = CollectionUtils.isNotEmpty(devices) ? true : false; + } + //存在该设备 + if (existence) { + switchEvent(evenID, element, eventTime, puid, ballName, idCard, devices); + // 事件推送成功后,设置缓存 + String key = evenID + "_" + puid; + log.info("redis-key:{}", key); + redisService.setCacheObject(key, puid, 10L, TimeUnit.MINUTES); + } else { + return "error"; + } + } else { + return "error"; + } + } else { + return "error"; + } + } else { + log.info("系统繁忙,请稍后重试"); + return "error"; + } + } catch (InterruptedException e) { + log.error("对象锁", e); + } catch (DocumentException e) { + throw new RuntimeException(e); + } finally { + // 确保锁被释放 + BED_LOCK.unlock(); + } + return "ok"; + } + + private void switchEvent(String eventId, Element element, String eventTime, String puid, String ballName, String idCard, List devices) { + List files = null; + DeviceUseVo deviceUseVo = devices.get(0); + deviceUseVo.setWarnTime(eventTime); + deviceUseVo.setIdCard(idCard); + switch (eventId) { + case "E_IVS_HelmetNotWear": + log.info(puid + ":违章事件:未戴安全帽"); + deviceUseVo.setWarnContent("未戴安全帽"); + files = deviceVolEvenHandler(element); + service.addEventData(deviceUseVo, files); + break; + case "E_IVS_Smoking": + log.info(puid + ":违章事件:吸烟行为"); + deviceUseVo.setWarnContent("吸烟行为"); + files = deviceVolEvenHandler(element); + service.addEventData(deviceUseVo, files); + break; + case "E_IVS_NotWear3ColorVest": + log.info(puid + ":违章事件:未穿马甲"); + deviceUseVo.setWarnContent("未穿马甲"); + files = deviceVolEvenHandler(element); + service.addEventData(deviceUseVo, files); + break; + default: + break; + } + } + + private List deviceVolEvenHandler(Element element) { + List multipartFiles = new ArrayList<>(); + Iterator silcesInterator = element.elementIterator("Slices"); + if (silcesInterator.hasNext()) { + Element silcesEle = (Element) silcesInterator.next(); + if (silcesEle != null) { + Iterator silcInterator = silcesEle.elementIterator("Slice"); + if (silcInterator.hasNext()) { + Element snapshotEle = (Element) silcInterator.next(); + if (snapshotEle != null) { + Iterator snapshotInterator = snapshotEle.elementIterator("Snapshot"); + if (snapshotInterator.hasNext()) { + Element TestEle = (Element) snapshotInterator.next(); + String photoBase64 = TestEle.getText(); + log.info("base64地址:{}", photoBase64); + MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart2(photoBase64); + if (multipartFile != null) { + multipartFiles.add(multipartFile); + } + } + } + } + } + } + return multipartFiles; + } +} diff --git a/bonus-modules/bonus-project/src/main/java/com/bonus/project/service/SmartIdentifyService.java b/bonus-modules/bonus-project/src/main/java/com/bonus/project/service/SmartIdentifyService.java new file mode 100644 index 0000000..7583c97 --- /dev/null +++ b/bonus-modules/bonus-project/src/main/java/com/bonus/project/service/SmartIdentifyService.java @@ -0,0 +1,33 @@ +package com.bonus.project.service; + +import com.bonus.common.entity.DeviceUseVo; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * @className:SmartIdentifyService + * @author:cwchen + * @date:2024-08-27-15:15 + * @version:1.0 + * @description:智能识别 + */ +public interface SmartIdentifyService { + /** + * 判断球机是否被班组领用 + * + * @param puid + * @return boolean + * @date 2024/8/27 15:22 + */ + List getDevices(String puid); + + /** + * 添加智能识别告警信息 + * @param deviceUseVo + * @param files + * @return void + * @date 2024/8/27 16:00 + */ + void addEventData(DeviceUseVo deviceUseVo, List files); +} diff --git a/bonus-modules/bonus-project/src/main/java/com/bonus/project/service/impl/SmartIdentifyServiceImpl.java b/bonus-modules/bonus-project/src/main/java/com/bonus/project/service/impl/SmartIdentifyServiceImpl.java new file mode 100644 index 0000000..6ac2099 --- /dev/null +++ b/bonus-modules/bonus-project/src/main/java/com/bonus/project/service/impl/SmartIdentifyServiceImpl.java @@ -0,0 +1,124 @@ +package com.bonus.project.service.impl; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.bonus.common.core.constant.HttpStatus; +import com.bonus.common.core.constant.SecurityConstants; +import com.bonus.common.core.domain.R; +import com.bonus.common.core.utils.encryption.Sm4Utils; +import com.bonus.common.entity.DeviceUseVo; +import com.bonus.common.entity.PeopleVioVo; +import com.bonus.project.mapper.SmartIdentifyMapper; +import com.bonus.project.service.SmartIdentifyService; +import com.bonus.system.api.RemoteFileService; +import com.bonus.system.api.domain.SysFileSource; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.interceptor.TransactionAspectSupport; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.util.List; + +/** + * @className:SmartIdentifyServiceImpl + * @author:cwchen + * @date:2024-08-27-15:15 + * @version:1.0 + * @description:智能识别 + */ +@Service +@Slf4j +public class SmartIdentifyServiceImpl implements SmartIdentifyService { + + @Resource + private SmartIdentifyMapper mapper; + + @Resource + private RemoteFileService remoteFileService; + + @Override + public List getDevices(String puid) { + List list = null; + try { + list = mapper.getDevices(puid); + } catch (Exception e) { + log.error(e.toString(), e); + } + return list; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void addEventData(DeviceUseVo deviceUseVo, List files) { + // 文件ID + String delFileId = null; + try { + if (StringUtils.isNotBlank(deviceUseVo.getIdCard())) { + /* List userIds = mapper.getUserByIdCard(Sm4Utils.encode(deviceUseVo.getIdCard())); + if (CollectionUtils.isNotEmpty(userIds)) { + deviceUseVo.setUserId(userIds.get(0).getId()); + deviceUseVo.setPeopleType(userIds.get(0).getPeopleType()); + deviceUseVo.setWarnContent(userIds.get(0).getName() + deviceUseVo.getWarnContent()); + }*/ + } + // 添加告警信息 + mapper.addWarnInfo(deviceUseVo); + // 上传智能识别图片 + if (CollectionUtils.isNotEmpty(files)) { + delFileId = uploadFile(files.get(0), deviceUseVo.getId()); + } + } catch (Exception e) { + log.error(e.toString(), e); + TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); + // 添加失败-删除文件 + /*if (delFileId != null) { + remoteFileService.delFile(delFileId, SecurityConstants.INNER); + }*/ + } + } + + public String uploadFile(MultipartFile file, Long warnId) { + if (file == null) { + return null; + } + R result = remoteFileService.singleUploadFile(file, SecurityConstants.INNER); + if (result != null && result.getCode() == HttpStatus.ERROR) { + log.error("违章照片上传失败"); + return null; + } else if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) { + String jsonString = JSON.toJSONString(result.getData()); + JSONObject item = JSON.parseObject(jsonString); + if (item != null) { + SysFileSource fileVo = setResourceFileData(item, warnId); + try { + Integer i = mapper.addFileSource(fileVo); + if (i <= 0) { + // 资源文件保存失败,删除文件 +// remoteFileService.delFile(item.getString("fileId"), SecurityConstants.INNER); + return null; + } + } catch (Exception e) { + log.error(e.toString(), e); + } + } + return item.getString("fileId"); + } + return null; + } + + public SysFileSource setResourceFileData(JSONObject item, Long warnId) { + SysFileSource fileVo = new SysFileSource(); + fileVo.setFileType(1); + fileVo.setFilePath(item.getString("fileId")); + fileVo.setFileSuffix(item.getString("suffix")); + fileVo.setFileName(item.getString("fileName")); + fileVo.setSourceId(warnId + ""); + fileVo.setSourceType("8"); + return fileVo; + } + +} diff --git a/bonus-modules/bonus-project/src/main/resources/mapper/safetycheck/ConsControlMapper.xml b/bonus-modules/bonus-project/src/main/resources/mapper/safetycheck/ConsControlMapper.xml new file mode 100644 index 0000000..006b95b --- /dev/null +++ b/bonus-modules/bonus-project/src/main/resources/mapper/safetycheck/ConsControlMapper.xml @@ -0,0 +1,59 @@ + + + + + + INSERT INTO tb_warn + + pro_id, + dev_id, + warn_content, + warn_time, + warn_type, + dev_type, + create_time, + + + #{proId}, + #{devId}, + #{warnContent}, + #{warnTime}, + #{warnType}, + #{devType}, + now(), + + + + INSERT INTO sys_file_source( + file_name, file_suffix, file_path, + file_type, source_id, source_type, + create_time,create_user,update_time, + update_user, del_flag + ) VALUE( + #{fileName},#{fileSuffix},#{filePath}, + #{fileType},#{sourceId},#{sourceType}, + now(),#{createUser},now(), + #{updateUser},0 + ) + + + + + + + \ No newline at end of file