ANDRU-PC\Andru
2022-07-21 0546530fe7e1696cf3ae4eaf9e79a5e7c4e203fe
Merge branch 'master' of http://1.15.4.62/r/~chenjiahe/hx_common
4个文件已修改
369 ■■■■■ 已修改文件
src/main/java/com/hx/mp/util/MPWeixinBaseUtil.java 103 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/hx/util/COSUtil.java 140 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/hx/util/DownFileUtil.java 35 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/hx/util/ExcelUtil.java 91 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/hx/mp/util/MPWeixinBaseUtil.java
@@ -605,4 +605,107 @@
        return obj;
    }
    /**生成无限二维码,返回临时文
     * @param at 微信token
     * @param scene 参数,只能32位,最好不要中文
     * @param page 跳转链接
     * @param width 宽度
     * @param autoColor 默认false
     * @param lineColor 默认null
     * @param isHyaline 默认false
     * @return
     */
    public static File createUnlimitQrCode(String at, String scene, String page, int width, boolean autoColor,
                                           JSONObject lineColor, boolean isHyaline, String env_version) throws IOException {
        String imgUrl = null;
        InputStream in = null;
        HttpURLConnection conn = null;
        //创建临时文件
        File file = File.createTempFile("temp", ".jpg");
        try {
            //生成发送数据
            JSONObject obj = new JSONObject();
            obj.put("scene", scene);
            obj.put("width", width);
            obj.put("page", page);
            obj.put("auto_color", autoColor);
            obj.put("line_color", lineColor);
            obj.put("is_hyaline", isHyaline);
            obj.put("env_version", env_version);
            // 创建url资源
            URL url = new URL(StringUtils.format(URL_UNLIMIT_SQUARE, at));
            // 建立http连接
            conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");
            // 开始连接请求
            conn.connect();
            OutputStream out = conn.getOutputStream();
            // 写入请求的字符串
            out.write((obj.toString()).getBytes());
            out.flush();
            out.close();
            // 请求返回的状态
            if (conn.getResponseCode() == 200) {
                // 请求返回的数据
                in = conn.getInputStream();
                //输入到临时文件
                /*OutputStream os = new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }*/
                FileUtils.copyInputStreamToFile(in, file);
                conn.disconnect();
                conn = null;
            }
            if (in != null) {
                in.close();
                in = null;
            }
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }catch (Exception e) {
            e.printStackTrace();
            if (in != null) {
                try {
                    in.close();
                }catch (Exception ep) {
                    ep.printStackTrace();
                }
                in = null;
            }
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }finally {
            file.deleteOnExit();
        }
        return file;
    }
}
src/main/java/com/hx/util/COSUtil.java
@@ -1,22 +1,26 @@
package com.hx.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.hx.exception.TipsException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.TransferManager;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**腾讯云 COS
 * @author ChenJiaHe
@@ -109,4 +113,130 @@
    }
    /**下载文件
     * @param key 上传路径(包括图片名称和和后缀),指定要上传到 COS 上对象键
     * @param secretId 用户id
     * @param secretKey 用户秘钥
     * @param regionName 存在域,参考腾讯云
     * @param bucketName 指定要上传到的存储桶
     */
    public static File download(String key,String secretId, String secretKey,String regionName,String bucketName){
        // 使用高级接口必须先保证本进程存在一个 TransferManager 实例,如果没有则创建
        // 详细代码参见本页:高级接口 -> 创建 TransferManager
        TransferManager transferManager = createTransferManager( secretId, secretKey,regionName);
        // 本地文件路径
        File downloadFile = null;
        try {
            GetObjectRequest getObjectRequest;
            System.out.println("key:"+key);
            System.out.println("bucketName:"+bucketName);
            System.out.println("regionName:"+regionName);
            System.out.println("regionName:"+regionName+".myqcloud.com");
            //截取文件名称
            String[] datas = key.split(regionName+".myqcloud.com/");
            if(datas.length ==1){
                getObjectRequest = new GetObjectRequest(bucketName, datas[0]);
            }else if(datas.length ==2){
                System.out.println("datas[1]:"+datas[1]);
                getObjectRequest = new GetObjectRequest(bucketName, datas[1]);
            }else{
                throw new TipsException("文件路径错误【key】");
            }
            ////生成临时文件
            //获取后缀名称
            String suffix = key.substring(key.lastIndexOf("."));
            downloadFile = File.createTempFile("temp", suffix);
            // 返回一个异步结果 Donload, 可同步的调用 waitForCompletion 等待下载结束, 成功返回 void, 失败抛出异常
            Download download = transferManager.download(getObjectRequest, downloadFile);
            download.waitForCompletion();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            // 确定本进程不再使用 transferManager 实例之后,关闭之
            // 详细代码参见本页:高级接口 -> 关闭 TransferManager
            shutdownTransferManager(transferManager);
        }
        return downloadFile;
    }
    /**
     * 创建 TransferManager 实例,这个实例用来后续调用高级接口
     * @param secretId
     * @param secretKey
     * @return
     */
    public static TransferManager createTransferManager(String secretId, String secretKey,String regionName) {
        // 创建一个 COSClient 实例,这是访问 COS 服务的基础实例。
        // 详细代码参见本页: 简单操作 -> 创建 COSClient
        COSClient cosClient = createCOSClient( secretId, secretKey,regionName);
        // 自定义线程池大小,建议在客户端与 COS 网络充足(例如使用腾讯云的 CVM,同地域上传 COS)的情况下,设置成16或32即可,可较充分的利用网络资源
        // 对于使用公网传输且网络带宽质量不高的情况,建议减小该值,避免因网速过慢,造成请求超时。
        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        // 传入一个 threadpool, 若不传入线程池,默认 TransferManager 中会生成一个单线程的线程池。
        TransferManager transferManager = new TransferManager(cosClient, threadPool);
        return transferManager;
    }
    /**
     * 关闭管理
     * @param transferManager
     */
    public static void shutdownTransferManager(TransferManager transferManager) {
        // 指定参数为 true, 则同时会关闭 transferManager 内部的 COSClient 实例。
        // 指定参数为 false, 则不会关闭 transferManager 内部的 COSClient 实例。
        transferManager.shutdownNow(true);
    }
    /**
     *  创建 COSClient 实例,这个实例用来后续调用请求
     * @param secretId
     * @param secretKey
     * @return
     */
    public static COSClient createCOSClient(String secretId, String secretKey,String regionName) {
        // 设置用户身份信息。
        // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // ClientConfig 中包含了后续请求 COS 的客户端设置:
        ClientConfig clientConfig = new ClientConfig();
        // 设置 bucket 的地域
        // COS_REGION 请参照 https://cloud.tencent.com/document/product/436/6224
        clientConfig.setRegion(new Region(regionName));
        // 设置请求协议, http 或者 https
        // 5.6.53 及更低的版本,建议设置使用 https 协议
        // 5.6.54 及更高版本,默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 以下的设置,是可选的:
        // 设置 socket 读取超时,默认 30s
        clientConfig.setSocketTimeout(300*1000);
        // 设置建立连接超时,默认 30s
        clientConfig.setConnectionTimeout(30*1000);
        // 如果需要的话,设置 http 代理,ip 以及 port
        //clientConfig.setHttpProxyIp("httpProxyIp");
        //clientConfig.setHttpProxyPort(80);
        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }
}
src/main/java/com/hx/util/DownFileUtil.java
@@ -187,4 +187,39 @@
        }
    }
    /**
     * 下载文件工具(提示选择路径)
     *
     * @param downfile
     *            导出的文件
     * @param fileName
     *            导出的文件名称
     */
    public static void DownFileTips( HttpServletResponse response, File downfile, String fileName) {
        try {
            if(StringUtils.isEmpty(fileName)){
                fileName = downfile.getName();
            }
            String filename =  "";
            filename = URLEncoder.encode(fileName,"UTF8");//其他浏览器
            InputStream fis = new BufferedInputStream(new FileInputStream(
                    downfile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.addHeader("Content-Disposition", "attachment;filename="+ filename);
            OutputStream toClient= new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
src/main/java/com/hx/util/ExcelUtil.java
@@ -498,6 +498,97 @@
     * @return
     * @throws Exception
     */
    public static List<List<String>> getExcelDataCompatible(File file,boolean header) throws Exception {
        try {
            String fileName = file.getName();
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new TipsException("上传文件格式不正确");
            }
            // 结果集
            List<List<String>> list = new ArrayList<>();
            Workbook book = create(new BufferedInputStream(new FileInputStream(file)));
            // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
            for(int s=0;s<book.getNumberOfSheets();s++) {
                Sheet hssfsheet = book.getSheetAt(s);
                int col = 0;
                // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
                for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
                    Row hssfrow = hssfsheet.getRow(j);
                    if(hssfrow!=null){
                        if(j == 0) {
                            col = hssfrow.getPhysicalNumberOfCells();
                            if(!header) {
                                //不包括表头
                                continue;
                            }
                        }
                        // 单行数据
                        List<String> arrayString = new ArrayList<>();
                        for (int i = 0; i < col; i++) {
                            Cell cell = hssfrow.getCell(i);
                            if (cell == null) {
                                arrayString.add("");
                            } else if (cell.getCellType() == 0) {
                                // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
                                if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
                                    short format = cell.getCellStyle().getDataFormat();
                                    if(format == 14 || format == 31 || format == 57 || format == 58){
                                        //日期(中文时间格式的)
                                        Date d = cell.getDateCellValue();
                                        DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                        // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        arrayString.add(formater.format(d));
                                        //arrayString[i] = formater.format(d);
                                    }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                        Date d = cell.getDateCellValue();
                                        //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
                                        DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                        arrayString.add(formater.format(d));
                                        //arrayString[i] = formater.format(d);
                                    } else {
                                        if(HSSFCell.CELL_TYPE_STRING == cell.getCellType()){
                                            arrayString.add(cell.getStringCellValue());
                                            //arrayString[i] =cell.getStringCellValue();
                                        }else if(HSSFCell.CELL_TYPE_FORMULA==cell.getCellType()){
                                            arrayString.add(cell.getCellFormula());
                                            //arrayString[i] =cell.getCellFormula();
                                        }else if(HSSFCell.CELL_TYPE_NUMERIC== cell.getCellType()){
                                            HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
                                            arrayString.add(dataFormatter.formatCellValue(cell));
                                            //arrayString[i] =dataFormatter.formatCellValue(cell);
                                        }
                                    }
                                }
                            } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
                                arrayString.add("");
                                //arrayString[i] = "";
                            } else { // 如果EXCEL表格中的数据类型为字符串型
                                arrayString.add(cell.getStringCellValue().trim());
                                //arrayString[i] = cell.getStringCellValue().trim();
                            }
                        }
                        list.add(arrayString);
                    }
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**读取excel文件,兼容2003和2007
     * 通过流读取Excel文件
     * @return
     * @throws Exception
     */
    public static List<List<String>> getExcelDataCompatible(MultipartFile file,boolean header) throws Exception {
        try {