123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510 |
- package org.springblade.common.utils;
- import cn.hutool.core.io.FileUtil;
- import cn.hutool.http.HttpUtil;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.drew.imaging.ImageMetadataReader;
- import com.drew.imaging.ImageProcessingException;
- import com.drew.metadata.Metadata;
- import com.drew.metadata.exif.ExifIFD0Directory;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.util.CollectionUtils;
- import javax.imageio.IIOImage;
- import javax.imageio.ImageIO;
- import javax.imageio.ImageWriteParam;
- import javax.imageio.ImageWriter;
- import java.awt.*;
- import java.awt.geom.AffineTransform;
- import java.awt.image.AffineTransformOp;
- import java.awt.image.BufferedImage;
- import java.io.*;
- import java.math.BigDecimal;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.time.LocalDate;
- import java.util.*;
- import java.util.List;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
- import com.drew.metadata.MetadataException;
- /**
- * 通用工具类
- *
- * @author Chill
- */
- public class CommonUtil {
- public static Boolean checkBigDecimal(Object value) {
- try {
- if (value != null && StringUtils.isNotEmpty(value.toString())) {
- new BigDecimal(value.toString());
- return true;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
- public static void removeFile(List<String> removeList) {
- for (String fileUrl : removeList) {
- try {
- FileUtil.del(new File(fileUrl));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public static String handleNull(Object obj) {
- if (null == obj) {
- return "";
- } else {
- return obj.toString().trim();
- }
- }
- public static String join(Object... args) {
- if (args != null) {
- if (args.length > 2) {
- List<String> list = Arrays.stream(args).limit(args.length - 1).map(CommonUtil::handleNull).collect(Collectors.toList());
- String split = handleNull(args[args.length - 1]);
- return join(list, split);
- } else {
- return handleNull(args[0]);
- }
- } else {
- return "";
- }
- }
- public static String join(List<String> list, String split) {
- StringBuilder sb = new StringBuilder();
- if (list != null && list.size() > 0) {
- for (String str : list) {
- if (StringUtils.isNotEmpty(str)) {
- sb.append(str).append(split);
- }
- }
- if (sb.length() > 0 && StringUtils.isNotEmpty(split)) {
- sb.delete(sb.length() - split.length(), sb.length());
- }
- }
- return sb.toString();
- }
- public static Matcher matcher(String regex, String value) {
- Pattern pattern = Pattern.compile(regex);
- return pattern.matcher(value);
- }
- /**
- * 根据OSS文件路径获取文件输入流
- */
- public static InputStream getOSSInputStream(String urlStr) throws Exception {
- //获取OSS文件流
- urlStr = replaceOssUrl(urlStr);
- URL imageUrl = new URL(urlStr);
- try {
- HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
- conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
- return conn.getInputStream();
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * 根据OSS文件路径获取文件输入流
- */
- public static InputStream getOSSInputStreamTow(String urlStr) throws Exception {
- //获取OSS文件流
- urlStr = replaceOssUrl(urlStr);
- URL imageUrl = new URL(urlStr);
- HttpURLConnection conn = null;
- try {
- conn = (HttpURLConnection) imageUrl.openConnection();
- conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
- return conn.getInputStream();
- } catch (IOException e) {
- e.printStackTrace();
- if (conn != null) {
- conn.disconnect(); //关闭网络连接
- }
- throw new Exception("获取图片输入流失败!URL:" + urlStr, e);
- }
- }
- /**
- * 获取字节数组
- */
- public static byte[] InputStreamToBytes(InputStream is) throws IOException {
- BufferedInputStream bis = new BufferedInputStream(is);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- int date = -1;
- while ((date = bis.read()) != -1) {
- os.write(date);
- }
- return os.toByteArray();
- }
- /**
- * 随机生成短信验证码
- *
- * @param length 生成长度
- */
- public static String getCharAndNumber(int length) {
- StringBuilder val = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < length; i++) {
- String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
- if ("char".equalsIgnoreCase(charOrNum)) {
- int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
- val.append((char) (choice + random.nextInt(26)));
- } else {
- val.append(random.nextInt(10));
- }
- }
- return val.toString();
- }
- /**
- * 判断参数是否是数字
- *
- * @param value 需要判断数据
- * @return 判断结果,数字则为true,反之false
- */
- public static boolean checkIsBigDecimal(Object value) {
- try {
- if (value != null && StringUtils.isNotEmpty(String.valueOf(value))) {
- new BigDecimal(String.valueOf(value));
- return true;
- } else {
- return false;
- }
- } catch (Exception e) {
- return false;
- }
- }
- /**
- * 根据每页信息分组
- */
- public static <T> List<List<T>> getBatchSize(List<T> allIds, int size) {
- List<List<T>> batchIds = new ArrayList<>();
- if (allIds == null || allIds.size() == 0 || size <= 0) {
- return batchIds;
- }
- int i = 0;
- List<T> tmp = new ArrayList<>();
- for (T map : allIds) {
- tmp.add(map);
- i++;
- if (i % size == 0 || i == allIds.size()) {
- batchIds.add(tmp);
- tmp = new ArrayList<>();
- }
- }
- return batchIds;
- }
- /**
- * @param src
- * @throws IOException
- * @throws ClassNotFoundException
- */
- public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
- ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
- ObjectOutputStream out = new ObjectOutputStream(byteOut);
- out.writeObject(src);
- ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
- ObjectInputStream in = new ObjectInputStream(byteIn);
- @SuppressWarnings("unchecked")
- List<T> dest = (List<T>) in.readObject();
- return dest;
- }
- /**
- * Description: Java8 Stream分割list集合
- *
- * @param list 集合数据
- * @param splitSize 几个分割一组
- * @return 集合分割后的集合
- */
- public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
- //判断集合是否为空
- if (CollectionUtils.isEmpty(list))
- return Collections.emptyList();
- //计算分割后的大小
- int maxSize = (list.size() + splitSize - 1) / splitSize;
- //开始分割
- return Stream.iterate(0, n -> n + 1)
- .limit(maxSize)
- .parallel()
- .map(a -> list.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
- .filter(b -> !b.isEmpty())
- .collect(Collectors.toList());
- }
- /**
- * 流写入文件
- *
- * @param inputStream 文件输入流
- * @param file 输出文件
- */
- public static void inputStreamToFile(InputStream inputStream, File file) {
- try {
- OutputStream os = new FileOutputStream(file);
- int bytesRead = 0;
- byte[] buffer = new byte[8192];
- while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
- os.write(buffer, 0, bytesRead);
- }
- os.close();
- inputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 删除文件夹下所有文件
- *
- * @param path
- * @return
- */
- public static boolean deleteDir(String path) {
- File file = new File(path);
- if (!file.exists()) {//判断是否待删除目录是否存在
- System.err.println("The dir are not exists!");
- return false;
- }
- String[] content = file.list();//取得当前目录下所有文件和文件夹
- for (String name : content) {
- File temp = new File(path, name);
- if (temp.isDirectory()) {//判断是否是目录
- deleteDir(temp.getAbsolutePath());//递归调用,删除目录里的内容
- temp.delete();//删除空目录
- } else {
- if (!temp.delete()) {//直接删除文件
- System.err.println("Failed to delete " + name);
- }
- }
- }
- return true;
- }
- /**
- * 压缩指定路径下的文件夹
- *
- * @param filesPath
- * @throws Exception
- */
- public static void packageZip(String filesPath) throws Exception {
- // 要被压缩的文件夹
- File file = new File(filesPath); //需要压缩的文件夹
- File zipFile = new File(filesPath + ".zip"); //放于和需要压缩的文件夹同级目录
- ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
- isDirectory(file, zipOut, "", true); //判断是否为文件夹
- zipOut.close();
- }
- public static void isDirectory(File file, ZipOutputStream zipOutputStream, String filePath, boolean flag) throws IOException {
- //判断是否为问加减
- if (file.isDirectory()) {
- File[] files = file.listFiles(); //获取该文件夹下所有文件(包含文件夹)
- filePath = flag == true ? file.getName() : filePath + File.separator + file.getName(); //首次为选中的文件夹,即根目录,之后递归实现拼接目录
- for (int i = 0; i < files.length; ++i) {
- //判断子文件是否为文件夹
- if (files[i].isDirectory()) {
- //进入递归,flag置false 即当前文件夹下仍包含文件夹
- isDirectory(files[i], zipOutputStream, filePath, false);
- } else {
- //不为文件夹则进行压缩
- InputStream input = new FileInputStream(files[i]);
- zipOutputStream.putNextEntry(new ZipEntry(filePath + File.separator + files[i].getName()));
- int temp = 0;
- while ((temp = input.read()) != -1) {
- zipOutputStream.write(temp);
- }
- input.close();
- }
- }
- } else {
- //将子文件夹下的文件进行压缩
- InputStream input = new FileInputStream(file);
- zipOutputStream.putNextEntry(new ZipEntry(file.getPath()));
- int temp = 0;
- while ((temp = input.read()) != -1) {
- zipOutputStream.write(temp);
- }
- input.close();
- }
- }
- /**
- * @param urlStr
- * @return 返回Url资源大小
- * @throws IOException
- */
- public static long getResourceLength(String urlStr) throws IOException {
- URL url = new URL(urlStr);
- URLConnection urlConnection = url.openConnection();
- urlConnection.connect();
- //返回响应报文头字段Content-Length的值
- return urlConnection.getContentLength();
- }
- /**
- * 图片缩放、压缩、旋转处理
- *
- * @param imageData
- * @return
- * @throws IOException
- * @throws ImageProcessingException
- * @throws MetadataException
- */
- public static byte[] compressImage(byte[] imageData) throws IOException, ImageProcessingException, MetadataException {
- // 读取原始图像(处理旋转问题)
- Metadata metadata = ImageMetadataReader.readMetadata(new ByteArrayInputStream(imageData));
- if (metadata.containsDirectoryOfType(ExifIFD0Directory.class)) {
- ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
- if (exifIFD0Directory.containsTag(ExifIFD0Directory.TAG_ORIENTATION)) {
- // 获取 Orientation 标签的值
- int orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
- // 需要旋转图片
- BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
- AffineTransform transform = new AffineTransform();
- if (orientation == 6) {
- transform.rotate(Math.PI / 2, originalImage.getWidth() / 2, originalImage.getHeight() / 2);
- } else if (orientation == 8) {
- transform.rotate(-Math.PI / 2, originalImage.getWidth() / 2, originalImage.getHeight() / 2);
- }
- AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
- originalImage = op.filter(originalImage, null);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ImageIO.write(originalImage, "jpg", baos);
- imageData = baos.toByteArray();
- }
- }
- // 缩放图像
- String formatName = "JPEG";
- ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
- BufferedImage originalImage = ImageIO.read(bais);
- long sizeLimit = 366912; //358KB
- int width = 768;
- int height = 1024;
- Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
- BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
- resizedImage.getGraphics().drawImage(scaledImage, 0, 0, null);
- // 压缩图像
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ImageIO.write(resizedImage, formatName, baos);
- if (baos.size() <= sizeLimit) {
- // 图片大小已经小于等于目标大小,直接返回原始数据
- return baos.toByteArray();
- }
- float quality = 0.9f; // 初始化压缩质量
- int retries = 10; // 最多尝试 10 次
- while (baos.size() > sizeLimit && retries > 0) {
- // 压缩图像并重新计算压缩质量
- byte[] data = baos.toByteArray();
- bais = new ByteArrayInputStream(data);
- BufferedImage compressedImage = ImageIO.read(bais);
- baos.reset();
- ImageWriter writer = null;
- Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
- if (writers.hasNext()) {
- writer = writers.next();
- } else {
- throw new IllegalArgumentException("Unsupported image format: " + formatName);
- }
- ImageWriteParam writeParam = writer.getDefaultWriteParam();
- writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
- writeParam.setCompressionQuality(quality);
- writer.setOutput(ImageIO.createImageOutputStream(baos));
- writer.write(null, new IIOImage(compressedImage, null, null), writeParam);
- writer.dispose();
- float ratio = sizeLimit * 1.0f / baos.size();
- quality *= Math.sqrt(ratio);
- retries--;
- }
- return baos.toByteArray();
- }
- /**
- * 根据起止日期获取工作日
- * @return
- */
- public static int getWorkDays(LocalDate startTime,LocalDate endTime){
- StringBuilder str = new StringBuilder();
- List<String> list = new ArrayList<>();
- while (!startTime.equals(endTime)){
- str.append("d="+startTime+"&");
- list.add(startTime.toString());
- startTime = startTime.plusDays(1L);
- }
- str.append("d="+endTime+"&");
- list.add(endTime.toString());
- str.append("type=Y");
- String post = HttpUtil.get("http://timor.tech/api/holiday/batch?" + str.toString());
- JSONObject jsonObject = JSON.parseObject(post).getJSONObject("type");
- System.out.println(jsonObject);
- int workDays = 0;
- for (String s : list) {
- Map map = JSONObject.parseObject(jsonObject.get(s).toString(), Map.class);
- int type = (int) map.get("type");
- if (type == 0 || type == 3){
- workDays++;
- }
- }
- return workDays;
- }
- // 上传文件路径获取
- public String getSysFileUrl() {
- return "";
- }
- public static String replaceOssUrl(String url) {
- String osName = System.getProperty("os.name");
- if (osName != null && osName.toLowerCase().contains("linux")) {
- // 如果当前操作系统是Linux系统
- Map<String, String> envMap = System.getenv();
- if (!envMap.containsKey("linuxtesttest")) {
- // 如果当前环境变量不包含linuxtesttest,则替换URL中的oss路径
- url = url.replace("oss-cn-hangzhou.aliyuncs.com", "oss-cn-hangzhou-internal.aliyuncs.com");
- }
- }
- //后续删除
- System.out.println("replaceOssUrl " + url);
- return url;
- }
- }
|