Prechádzať zdrojové kódy

定尺项目添加常用工具类

lingpeng.li 4 mesiacov pred
rodič
commit
da6462b613

+ 5 - 0
zgztBus/jeecg-module-scale/pom.xml

@@ -15,6 +15,11 @@
             <groupId>org.jeecgframework.boot</groupId>
             <artifactId>jeecg-boot-base-core</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.belerweb</groupId>
+            <artifactId>pinyin4j</artifactId>
+            <version>2.5.1</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 21 - 0
zgztBus/jeecg-module-scale/src/main/java/org/jeecg/modules/exception/FileNameLengthLimitExceededException.java

@@ -0,0 +1,21 @@
+package org.jeecg.modules.exception;
+
+/**
+ * @Author: llp
+ * Date: 2025-01-17 14:35
+ * @Description: 文件超出限制异常类
+ */
+public class FileNameLengthLimitExceededException extends RuntimeException {
+
+    public FileNameLengthLimitExceededException() {
+        super();
+    }
+
+    /**
+     * 定义有参构造方法
+     */
+    public FileNameLengthLimitExceededException(String message) {
+        super(message);
+    }
+
+}

+ 19 - 0
zgztBus/jeecg-module-scale/src/main/java/org/jeecg/modules/exception/FileSizeLimitExceededException.java

@@ -0,0 +1,19 @@
+package org.jeecg.modules.exception;
+
+/**
+ * @Author: llp
+ * Date: 2025-01-17 14:38
+ * @Description:
+ */
+public class FileSizeLimitExceededException extends RuntimeException {
+    public FileSizeLimitExceededException() {
+        super();
+    }
+
+    /**
+     * 定义有参构造方法
+     */
+    public FileSizeLimitExceededException(String message) {
+        super(message);
+    }
+}

+ 20 - 0
zgztBus/jeecg-module-scale/src/main/java/org/jeecg/modules/exception/FileUploadTypeException.java

@@ -0,0 +1,20 @@
+package org.jeecg.modules.exception;
+
+/**
+ * @Author: llp
+ * Date: 2025-01-17 14:47
+ * @Description:
+ */
+public class FileUploadTypeException extends RuntimeException {
+
+    public FileUploadTypeException() {
+        super();
+    }
+
+    /**
+     * 定义有参构造方法
+     */
+    public FileUploadTypeException(String message) {
+        super(message);
+    }
+}

+ 191 - 0
zgztBus/jeecg-module-scale/src/main/java/org/jeecg/modules/utils/DateUtils.java

@@ -0,0 +1,191 @@
+package org.jeecg.modules.utils;
+
+import org.apache.commons.lang3.time.DateFormatUtils;
+
+import java.lang.management.ManagementFactory;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+
+/**
+ * @author llp
+ * date: 2025/01/17 16:15
+ * description: 时间工具类
+ */
+public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
+    public static String YYYY = "yyyy";
+
+    public static String YYYY_MM = "yyyy-MM";
+
+    public static String YYYY_MM_DD = "yyyy-MM-dd";
+
+    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
+
+    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
+
+    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"};
+
+    /**
+     * 获取当前Date型日期
+     *
+     * @return Date() 当前日期
+     */
+    public static Date getNowDate() {
+        return new Date();
+    }
+
+    /**
+     * 获取当前日期, 默认格式为yyyy-MM-dd
+     *
+     * @return String
+     */
+    public static String getDate() {
+        return dateTimeNow(YYYY_MM_DD);
+    }
+
+    public static final String getTime() {
+        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
+    }
+
+    public static final String dateTimeNow() {
+        return dateTimeNow(YYYYMMDDHHMMSS);
+    }
+
+    public static final String dateTimeNow(final String format) {
+        return parseDateToStr(format, new Date());
+    }
+
+    public static final String dateTime(final Date date) {
+        return parseDateToStr(YYYY_MM_DD, date);
+    }
+
+    public static final String parseDateToStr(final String format, final Date date) {
+        if (null == date) {
+            return null;
+        }
+        return new SimpleDateFormat(format).format(date);
+    }
+
+    public static final Date dateTime(final String format, final String ts) {
+        try {
+            return new SimpleDateFormat(format).parse(ts);
+        } catch (ParseException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 日期路径 即年/月/日 如2018/08/08
+     */
+    public static final String datePath() {
+        Date now = new Date();
+        return DateFormatUtils.format(now, "yyyy/MM/dd");
+    }
+
+    /**
+     * 日期路径 即年/月/日 如20180808
+     */
+    public static final String dateTime() {
+        Date now = new Date();
+        return DateFormatUtils.format(now, "yyyyMMdd");
+    }
+
+    public static final String dateYYYYMMDDHHMMSS() {
+        Date now = new Date();
+        return DateFormatUtils.format(now, DateUtils.YYYYMMDDHHMMSS);
+    }
+
+    /**
+     * 日期型字符串转化为日期 格式
+     */
+    public static Date parseDate(Object str) {
+        if (str == null) {
+            return null;
+        }
+        try {
+            return parseDate(str.toString(), parsePatterns);
+        } catch (ParseException e) {
+            return null;
+        }
+    }
+
+    /**
+     * 获取服务器启动时间
+     */
+    public static Date getServerStartDate() {
+        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
+        return new Date(time);
+    }
+
+    /**
+     * 计算两个时间差
+     */
+    public static String getDatePoor(Date endDate, Date nowDate) {
+        long nd = 1000 * 24 * 60 * 60;
+        long nh = 1000 * 60 * 60;
+        long nm = 1000 * 60;
+        // long ns = 1000;
+        // 获得两个时间的毫秒时间差异
+        long diff = endDate.getTime() - nowDate.getTime();
+        // 计算差多少天
+        long day = diff / nd;
+        // 计算差多少小时
+        long hour = diff % nd / nh;
+        // 计算差多少分钟
+        long min = diff % nd % nh / nm;
+        // 计算差多少秒//输出结果
+        // long sec = diff % nd % nh % nm / ns;
+        return day + "天" + hour + "小时" + min + "分钟";
+    }
+
+    public static long getDateHour(Date endDate, Date nowDate) {
+        long nd = 1000 * 24 * 60 * 60;
+        long nh = 1000 * 60 * 60;
+        long nm = 1000 * 60;
+        // long ns = 1000;
+        // 获得两个时间的毫秒时间差异
+        long diff = endDate.getTime() - nowDate.getTime();
+        // 计算差多少天
+
+        // 计算差多少小时
+        long hour = diff % nd / nh;
+        // 计算差多少分钟
+
+        return hour;
+    }
+
+    /***
+     * 根据出生日期计算年龄
+     */
+
+    public static int getAgeByBirth(Date birthday) {
+        //Calendar:日历
+        /*从Calendar对象中或得一个Date对象*/
+        Calendar cal = Calendar.getInstance();
+        /*把出生日期放入Calendar类型的bir对象中,进行Calendar和Date类型进行转换*/
+        Calendar bir = Calendar.getInstance();
+        bir.setTime(birthday);/*如果生日大于当前日期,则抛出异常:出生日期不能大于当前日期*/
+        if (cal.before(birthday)) {
+            return 0;
+        }
+        /*取出当前年月日*/
+        int yearNow = cal.get(Calendar.YEAR);
+        int monthNow = cal.get(Calendar.MONTH);
+        int dayNow = cal.get(Calendar.DAY_OF_MONTH);
+        /*取出出生年月日*/
+        int yearBirth = bir.get(Calendar.YEAR);
+        int monthBirth = bir.get(Calendar.MONTH);
+        int dayBirth = bir.get(Calendar.DAY_OF_MONTH);
+        /*大概年龄是当前年减去出生年*/
+        int age = yearNow - yearBirth;
+        /*如果出当前月小与出生月,或者当前月等于出生月但是当前日小于出生日,那么年龄age就减一岁*/
+        if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
+            age--;
+        }
+        return age;
+    }
+}

+ 203 - 0
zgztBus/jeecg-module-scale/src/main/java/org/jeecg/modules/utils/FileUploadUtils.java

@@ -0,0 +1,203 @@
+package org.jeecg.modules.utils;
+
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FilenameUtils;
+import org.jeecg.modules.exception.FileNameLengthLimitExceededException;
+import org.jeecg.modules.exception.FileSizeLimitExceededException;
+import org.jeecg.modules.exception.FileUploadTypeException;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.util.StringUtils;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Random;
+import java.util.UUID;
+
+
+/**
+ * @author llp
+ * Date: 2025-01-17 14:22
+ * @Description:文件上传工具类
+ */
+@Slf4j
+public class FileUploadUtils {
+    /**
+     * 默认最大 大小 50M
+     */
+    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
+
+    /**
+     * 默认的文件名最大长度 200
+     */
+    public static final int DEFAULT_FILE_NAME_LENGTH = 200;
+
+    /**
+     * 资源映射路径 前缀
+     */
+    @Value("${file.prefix}")
+    public String localFilePrefix;
+
+
+    /**
+     * 根据文件路径上传
+     *
+     * @param baseDir 相对应用的基目录
+     * @param file    上传的文件
+     * @return 文件名称
+     * @throws IOException
+     */
+    public static String upload(String baseDir, MultipartFile file) throws IOException {
+
+        try {
+            return upload(baseDir, file, MimeTypeUtils.IMAGE_EXTENSION);
+        } catch (Exception e) {
+            throw new IOException(e.getMessage(), e);
+        }
+
+    }
+
+    public static String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws IOException {
+
+
+        int fileNameLength = file.getOriginalFilename().length();
+        if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
+            throw new FileNameLengthLimitExceededException("文件名字超出长度,最大长度为" + FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
+        }
+
+        assertAllowed(file, allowedExtension);
+        String fileName = extractFilename(file);
+        File desc = getAbsoluteFile(baseDir, fileName);
+        file.transferTo(desc);
+        String pathFileName = getPathFileName(fileName);
+        return pathFileName;
+    }
+
+
+    public static String upload(String baseDir, String name, ByteArrayOutputStream byteArrayOutputStream) throws IOException {
+
+        FileOutputStream outputStream = null;
+        try {
+            name = DateUtils.datePath() + "/" + name;
+            File desc = getAbsoluteFile(baseDir, name);
+            outputStream = new FileOutputStream(desc);
+            outputStream.write(byteArrayOutputStream.toByteArray());
+            return getPathFileName(name);
+        } finally {
+            if (outputStream != null) {
+                outputStream.close();
+            }
+
+        }
+
+
+    }
+
+
+    private static String getPathFileName(String fileName) throws IOException {
+        String pathFileName = "/" + fileName;
+        return pathFileName;
+    }
+
+    private static File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
+        File desc = new File(uploadDir + File.separator + fileName);
+
+        if (!desc.exists()) {
+            if (!desc.getParentFile().exists()) {
+                boolean mkdirs = desc.getParentFile().mkdirs();
+                log.info("文件是否创建" + mkdirs);
+            }
+        }
+        return desc;
+    }
+
+    /**
+     * 编码文件名
+     */
+    public static final String extractFilename(MultipartFile file) {
+        String fileName = file.getOriginalFilename();
+        String extension = getExtension(file);
+        fileName = DateUtils.datePath() + "/" + UUID.randomUUID().toString().substring(1, 10) + "." + extension;
+        return fileName;
+    }
+
+
+    /**
+     * 文件大小校验
+     *
+     * @param file 上传的文件
+     * @return
+     */
+
+    public static final void assertAllowed(MultipartFile file, String[] allowedExtension) {
+        long size = file.getSize();
+        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
+            throw new FileSizeLimitExceededException("文件超出最大长度" + DEFAULT_MAX_SIZE / 1024 / 1024 + "M");
+        }
+        String fileName = file.getOriginalFilename();
+        //后缀名
+        String extension = getExtension(file);
+
+        //判断上传的附件是否符合文件类型
+        if (!isAllowedExtension(extension, allowedExtension)) {
+            String join = String.join(",", allowedExtension);
+            throw new FileUploadTypeException("文件名字为:" + fileName + ",上传的文件格式不正确,正确格式包含" + join);
+
+        }
+    }
+
+    public static String getRandomFileName() {
+
+        SimpleDateFormat simpleDateFormat;
+
+        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
+
+        Date date = new Date();
+
+        String str = simpleDateFormat.format(date);
+
+        Random random = new Random();
+
+        // 获取5位随机数
+        int ranNum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
+        // 当前时间
+        return ranNum + str;
+    }
+
+
+    /**
+     * 获取文件名的后缀
+     *
+     * @param file 表单文件
+     * @return 后缀名
+     */
+    public static final String getExtension(MultipartFile file) {
+        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
+        if (StringUtils.isEmpty(extension)) {
+            extension = MimeTypeUtils.getExtension(file.getContentType());
+        }
+        return extension;
+    }
+
+    /**
+     * 判断MIME类型是否是允许的MIME类型
+     *
+     * @param extension
+     * @param allowedExtension
+     * @return
+     */
+    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
+        for (String str : allowedExtension) {
+            if (str.equalsIgnoreCase(extension)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+}

+ 75 - 0
zgztBus/jeecg-module-scale/src/main/java/org/jeecg/modules/utils/GetPinyinUtil.java

@@ -0,0 +1,75 @@
+package org.jeecg.modules.utils;
+
+import net.sourceforge.pinyin4j.PinyinHelper;
+import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
+import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
+import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
+import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
+import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
+
+/**
+ * @Author: llp
+ * @Descripiton: 拼音助记码工具类
+ * @Date: 2025-01-17  11:11
+ */
+public class GetPinyinUtil {
+    /**
+     * 得到全拼
+     *
+     * @param str
+     * @return 全拼(小写)
+     */
+    public static String getPinYin(String str) {
+        char t1[] = null;
+        t1 = str.toCharArray();
+        String[] t2 = new String[t1.length];
+        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
+        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
+        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
+        t3.setVCharType(HanyuPinyinVCharType.WITH_V);
+        String t4 = "";
+        int t0 = t1.length;
+        try {
+            for (int i = 0; i < t0; i++) {
+                //是用来判断是不是中文的一个条件,采用的是unicode编码
+                if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
+                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
+                    t4 += t2[0];
+                } else {
+                    t4 += Character.toString(t1[i]);
+                }
+            }
+            return t4;
+        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
+            badHanyuPinyinOutputFormatCombination.printStackTrace();
+        }
+        return t4;
+    }
+
+    /**
+     * 得到汉字首字母的拼音
+     *
+     * @param str
+     * @return 拼音首字母(大写)
+     */
+    public static String getPinYinHeaderChar(String str) {
+        String convert = "";
+        for (int i = 0; i < str.length(); i++) {
+            char word = str.charAt(i);
+            String[] pinYinArray = PinyinHelper.toHanyuPinyinStringArray(word);
+            if (pinYinArray != null) {
+                convert += pinYinArray[0].charAt(0);
+            } else {
+                convert += word;
+            }
+        }
+        return convert.toUpperCase();
+    }
+
+    //测试
+    public static void main(String[] args) {
+        System.out.println(getPinYin("火影忍者Marydon"));
+        System.out.println(getPinYinHeaderChar("火影印象"));
+
+    }
+}

+ 57 - 0
zgztBus/jeecg-module-scale/src/main/java/org/jeecg/modules/utils/MimeTypeUtils.java

@@ -0,0 +1,57 @@
+package org.jeecg.modules.utils;
+
+
+/**
+ * @author llp
+ * Date: 2025-01-17 15:11
+ * @Description:媒体类型工具类
+ */
+public class MimeTypeUtils {
+    public static final String IMAGE_PNG = "image/png";
+
+    public static final String IMAGE_JPG = "image/jpg";
+
+    public static final String IMAGE_JPEG = "image/jpeg";
+
+    public static final String IMAGE_BMP = "image/bmp";
+
+    public static final String IMAGE_GIF = "image/gif";
+
+    public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
+
+    public static final String[] FLASH_EXTENSION = {"swf", "flv"};
+
+    public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
+            "asf", "rm", "rmvb"};
+
+    public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"};
+
+    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
+            // 图片
+            "bmp", "gif", "jpg", "jpeg", "png",
+            // word excel powerpoint
+            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
+            // 压缩文件
+            "rar", "zip", "gz", "bz2",
+            // 视频格式
+            "mp4", "avi", "rmvb",
+            // pdf
+            "pdf"};
+
+    public static String getExtension(String prefix) {
+        switch (prefix) {
+            case IMAGE_PNG:
+                return "png";
+            case IMAGE_JPG:
+                return "jpg";
+            case IMAGE_JPEG:
+                return "jpeg";
+            case IMAGE_BMP:
+                return "bmp";
+            case IMAGE_GIF:
+                return "gif";
+            default:
+                return "";
+        }
+    }
+}