From 71057ec730fb78704a5401488406b0a7369259aa Mon Sep 17 00:00:00 2001
From: yanzg <yanzuoguang@qq.com>
Date: Wed, 8 May 2019 20:53:52 +0800
Subject: [PATCH] =?UTF-8?q?Excel=E5=AF=BC=E5=87=BA=E5=8A=9F=E8=83=BD?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../yanzuoguang/util/helper/RandomHelper.java | 115 +++++++++
 .../cloud/helper/HttpUploadHelper.java        | 110 +++++++++
 .../cloud/helper/WebFileHelper.java           | 226 ++++++++++++++++++
 .../com/yanzuoguang/cloud/vo/WebFileVo.java   |  59 +++++
 4 files changed, 510 insertions(+)
 create mode 100755 yzg-util-base/src/main/java/com/yanzuoguang/util/helper/RandomHelper.java
 create mode 100755 yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/HttpUploadHelper.java
 create mode 100755 yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/WebFileHelper.java
 create mode 100755 yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/vo/WebFileVo.java

diff --git a/yzg-util-base/src/main/java/com/yanzuoguang/util/helper/RandomHelper.java b/yzg-util-base/src/main/java/com/yanzuoguang/util/helper/RandomHelper.java
new file mode 100755
index 00000000..c9c42909
--- /dev/null
+++ b/yzg-util-base/src/main/java/com/yanzuoguang/util/helper/RandomHelper.java
@@ -0,0 +1,115 @@
+package com.yanzuoguang.util.helper;
+
+import com.yanzuoguang.util.contants.SystemContants;
+
+import java.util.UUID;
+
+/**
+ * ��寴������綏ュ��
+ */
+public final class RandomHelper {
+
+    public static final String NUMBER = "0123456789";
+
+    public static final String LOWER_LETTER = "abcdefghijklmnopqrstuvwxyz";
+
+    public static final String UPPER_LETTER = LOWER_LETTER.toUpperCase();
+
+    private static final String RANDOM_CHARSET = NUMBER + LOWER_LETTER + UPPER_LETTER;
+
+    private static final int RANDOM_CHARSET_LEN = RANDOM_CHARSET.length();
+
+    /**
+     * 緇���32篏���寴��
+     *
+     * @return
+     */
+    public static String generateUUID32() {
+        return replace(UUID.randomUUID().toString(), SystemContants.TRANSVERSE, SystemContants.EMPTY);
+    }
+
+    /**
+     * 緇���64篏���寴��
+     *
+     * @return
+     */
+    public static String generateUUID64() {
+        return generateUUID32() + generateUUID32();
+    }
+
+    /**
+     * ��寴��鐚�6篏�鐚�
+     *
+     * @return
+     */
+    public static String generateRandomCodeSix() {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < 6; i++) {
+            sb.append(generateRandomCodeOne(RANDOM_CHARSET, RANDOM_CHARSET_LEN));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * ��寴��鐚���絎��水墾鐚�
+     *
+     * @param len ��寴���水墾
+     * @return
+     */
+    public static String generateRandomCodeSix(int len) {
+        if (len < 1) {
+            throw new RuntimeException("length params is error, must be greater than 0, this params is [" + len + "]");
+        }
+
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < len; i++) {
+            sb.append(generateRandomCodeOne(RANDOM_CHARSET, RANDOM_CHARSET_LEN));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * ��寴������絎�絖�膃�������絎��水墾������寴��
+     *
+     * @param charset �榊�絖�膃���
+     * @param len ������寴���水墾
+     * @return
+     */
+    public static String generateRandomCode(String charset, int len) {
+        if (null == charset || "".equals(charset)) {
+            throw new RuntimeException("random code, essential data is empty.");
+        }
+
+        if (len < 1) {
+            throw new RuntimeException("length params is error, must be greater than 0, this params is [" + len + "]");
+        }
+
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < len; i++) {
+            sb.append(generateRandomCodeOne(charset, charset.length()));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * ��絎�絖�膃���筝㍼���寠婚��筝�筝��膃�
+     *
+     * @param charset
+     * @param len
+     * @return
+     */
+    private static String generateRandomCodeOne(String charset, int len) {
+        int index = (int) (Math.random() * len);
+        return String.valueOf(charset.charAt(index));
+    }
+
+    private static String replace(String str, String olds, String news) {
+        if(null == str) {
+            return "";
+        }
+        while (str.indexOf(olds) > -1) {
+            str = str.replace(olds, news);
+        }
+        return str;
+    }
+}
diff --git a/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/HttpUploadHelper.java b/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/HttpUploadHelper.java
new file mode 100755
index 00000000..11460d5d
--- /dev/null
+++ b/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/HttpUploadHelper.java
@@ -0,0 +1,110 @@
+package com.yanzuoguang.cloud.helper;
+
+import com.alibaba.fastjson.JSON;
+import com.yanzuoguang.util.vo.ResponseResult;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.entity.mime.content.FileBody;
+import org.apache.http.entity.mime.content.StringBody;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * HTTP絎∽�欠�筝�篌���篁�
+ * @author 蘂�篏���
+ */
+public final class HttpUploadHelper {
+
+    private static final Logger logger = LoggerFactory.getLogger(HttpUploadHelper.class);
+
+    public static final String tagName = "file";
+
+    public static final int CONNECT_TIME_OUT = 200000;
+
+    public static final int SOCKET_TIME_OUT = 200000;
+
+    /**
+     * 筝�篌���篁�
+     *
+     * @param url      筝�篌�����篁�
+     * @param filePath 筝�篌���莊��
+     * @return
+     */
+    public static String upload(final String url, final String filePath) {
+        CloseableHttpClient httpclient = HttpClients.createDefault();
+        try {
+            HttpPost httpPost = initHttpPost(url);
+            httpPost.setEntity(initRequestEntity(filePath));
+
+            logger.debug("executing request: {}", httpPost.getRequestLine());
+            CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpPost);
+            HttpEntity responseEntity = closeableHttpResponse.getEntity();
+            if (responseEntity != null) {
+                String result = EntityUtils.toString(closeableHttpResponse.getEntity());
+                logger.debug("response result: {}", result);
+                return result;
+            }
+            EntityUtils.consume(responseEntity);
+            closeableHttpResponse.close();
+            return JSON.toJSONString(initResponseError());
+        } catch (ClientProtocolException e) {
+            logger.error("exception ClientProtocolException.", e);
+            throw new RuntimeException(e);
+        } catch (IOException e) {
+            logger.error("exception IOException.", e);
+            throw new RuntimeException(e);
+        } finally {
+            try {
+                httpclient.close();
+            } catch (IOException e) {
+                logger.error("close IO exception IOException.", e);
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    /**
+     * ��紮���HttpPost
+     *
+     * @param url
+     * @return
+     */
+    private static HttpPost initHttpPost(String url) {
+        HttpPost httpPost = new HttpPost(url);
+        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIME_OUT).setSocketTimeout(SOCKET_TIME_OUT).build();
+        httpPost.setConfig(requestConfig);
+        return httpPost;
+    }
+
+    /**
+     * ��紮���莚傑�HttpEntity
+     *
+     * @param filePath
+     * @return
+     */
+    private static HttpEntity initRequestEntity(String filePath) {
+        FileBody fileBody = new FileBody(new File(filePath));
+        StringBody stringBody = new StringBody("This is comment", ContentType.TEXT_PLAIN);
+        return MultipartEntityBuilder.create().addPart(tagName, fileBody).addPart("comment", stringBody).build();
+    }
+
+    /**
+     * ��紮���菴�����莚�拭��
+     *
+     * @return
+     */
+    private static ResponseResult initResponseError() {
+        return ResponseResult.error("01", "筝�篌���篁九け茣�");
+    }
+}
diff --git a/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/WebFileHelper.java b/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/WebFileHelper.java
new file mode 100755
index 00000000..e0178841
--- /dev/null
+++ b/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/helper/WebFileHelper.java
@@ -0,0 +1,226 @@
+package com.yanzuoguang.cloud.helper;
+
+import com.yanzuoguang.cloud.vo.WebFileVo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.core.io.InputStreamResource;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.MultipartHttpServletRequest;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * 筝�篌���篁駈�筝�莉醇��篁倶��篏�膠�
+ */
+public final class WebFileHelper {
+
+    private static final Logger logger = LoggerFactory.getLogger(WebFileHelper.class);
+
+    private static final String CACHE_CONTROL_VALUE = "no-cache, no-store, must-revalidate";
+
+    private static final String CONTENT_DISPOSITION_VALUE = "attachment; filename=\"%s\"";
+
+    private static final String PRAGMA_VALUE = "no-cache";
+
+    private static final String EXPIRES_VALUE = "0";
+
+    private static final String SEPARATE_SPOT = ".";
+
+    private static final String SEPARATE_HR = "-";
+
+    private static final String UTF_8 = "UTF-8";
+
+    private static WebFileVo webFileVo;
+
+    private WebFileHelper() {
+        super();
+    }
+
+    /**
+     * 罍��ュ攻��綮堺��篁九す
+     *
+     * @param path
+     */
+    public static boolean createDirectory(String path) {
+        File file = new File(path);
+        if (!file.isDirectory()) {
+            return file.mkdirs();
+        }
+        return false;
+    }
+
+    /**
+     * 筝�莉醇��篁駈�筝�莉醇��篁九��筝堺���≦���絖���篁九��
+     *
+     * @param path ��篁区君緇�
+     * @return
+     */
+    public static ResponseEntity download(String path) {
+        try {
+            FileSystemResource file = new FileSystemResource(path);
+
+            HttpHeaders httpHeaders = buildHttpHeaders(file.getFilename());
+
+            return buildResponseEntity(httpHeaders, file);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 筝�莉醇��篁駈���絎�筝�莉醇��篁九����篁九��
+     *
+     * @param path 筝�莉処君緇�
+     * @param name ���遵��
+     * @return
+     */
+    public static ResponseEntity download(String path, String name) {
+        try {
+            FileSystemResource file = new FileSystemResource(path);
+
+            HttpHeaders httpHeaders = buildHttpHeaders(name);
+
+            return buildResponseEntity(httpHeaders, file);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 莅丞舟筝�莉�headers
+     *
+     * @param name
+     * @return
+     */
+    private static HttpHeaders buildHttpHeaders(String name) throws UnsupportedEncodingException {
+        HttpHeaders headers = new HttpHeaders();
+        headers.add(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_VALUE);
+        String encodeName = URLEncoder.encode(name, UTF_8);
+
+        if (logger.isDebugEnabled()) {
+            logger.debug("download taskDefinition name, and before encode taskDefinition name [{}], and after taskDefinition name[{}]", name, encodeName);
+        }
+
+        headers.add(HttpHeaders.CONTENT_DISPOSITION, String.format(CONTENT_DISPOSITION_VALUE, encodeName));
+        headers.add(HttpHeaders.PRAGMA, PRAGMA_VALUE);
+        headers.add(HttpHeaders.EXPIRES, EXPIRES_VALUE);
+        return headers;
+    }
+
+    /**
+     * 筝�莉処�臀������
+     *
+     * @param httpHeaders
+     * @param file
+     * @return
+     * @throws IOException
+     */
+    private static ResponseEntity buildResponseEntity(HttpHeaders httpHeaders, FileSystemResource file) throws IOException {
+        return ResponseEntity
+                .ok()
+                .headers(httpHeaders)
+                .contentLength(file.contentLength())
+                .contentType(MediaType.parseMediaType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
+                .body(new InputStreamResource(file.getInputStream()));
+    }
+
+
+    /**
+     * ����篁銀�篌�
+     *
+     * @param multipartFile
+     * @param savePath
+     * @return
+     */
+    public static WebFileVo upload(MultipartFile multipartFile, String savePath) {
+        String fileName = multipartFile.getOriginalFilename();
+
+        if (!savePath.endsWith("/") || !savePath.endsWith("\\")) {
+            savePath += "/";
+        }
+
+        webFileVo = new WebFileVo();
+        webFileVo.setOldName(fileName);
+        try {
+            String suffixName = suffix(fileName);
+            String uuid = generateUUID();
+            String newPath = rename(uuid, suffixName, savePath);
+
+            webFileVo.setNewName(uuid + suffixName);
+
+            File newFile = new File(newPath);
+            createDirectory(savePath);
+            multipartFile.transferTo(newFile);
+
+            webFileVo.setPath(newPath);
+
+            return webFileVo;
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 紊���篁銀�篌�
+     *
+     * @param tagName 蕁級�∽ァ篁九��腱�
+     * @return
+     */
+    public static List<WebFileVo> upload(HttpServletRequest request, String tagName, String savePath) {
+        List<WebFileVo> list = new ArrayList<>();
+        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles(tagName);
+        if (null != files && !files.isEmpty()) {
+            for (MultipartFile multipartFile : files) {
+                WebFileVo tempBean = upload(multipartFile, savePath);
+                list.add(tempBean);
+            }
+        }
+        return list;
+    }
+
+
+    /**
+     * 筝�篌���篁狗���遵��
+     *
+     * @param suffixName
+     * @param savePath
+     * @return
+     */
+    private static String rename(String uuid, String suffixName, String savePath) {
+        return savePath + uuid + suffixName;
+    }
+
+    /**
+     * �桁�UUID
+     *
+     * @return
+     */
+    private static String generateUUID() {
+        String str = String.valueOf(UUID.randomUUID());
+        while (str.indexOf(SEPARATE_HR) >= 0) {
+            str = str.replace(SEPARATE_HR, "");
+        }
+        return str;
+    }
+
+    /**
+     * 藥�莅よキ�����
+     *
+     * @param fileName
+     * @return
+     */
+    private static String suffix(String fileName) {
+        return fileName.substring(fileName.lastIndexOf(SEPARATE_SPOT));
+    }
+}
diff --git a/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/vo/WebFileVo.java b/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/vo/WebFileVo.java
new file mode 100755
index 00000000..1de7fe88
--- /dev/null
+++ b/yzg-util-cloud/src/main/java/com/yanzuoguang/cloud/vo/WebFileVo.java
@@ -0,0 +1,59 @@
+package com.yanzuoguang.cloud.vo;
+
+import com.yanzuoguang.util.vo.BaseVo;
+
+
+/**
+ * 筝�篌���篁区���絎�篏�
+ * @author �水Ж筝㊧�綛�
+ */
+public class WebFileVo extends BaseVo {
+    /**
+     * 筝�篌�����篁九��腱�
+     */
+    private String oldName;
+    /**
+     * 筝�篌�����篁九��腱�
+     */
+    private String newName;
+    /**
+     * ��篁銀�絖�莊��
+     */
+    private String path;
+    /**
+     * nginx莚傑��医��
+     */
+    private String nginxUrl;
+
+    public String getOldName() {
+        return oldName;
+    }
+
+    public void setOldName(String oldName) {
+        this.oldName = oldName;
+    }
+
+    public String getNewName() {
+        return newName;
+    }
+
+    public void setNewName(String newName) {
+        this.newName = newName;
+    }
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+
+    public String getNginxUrl() {
+        return nginxUrl;
+    }
+
+    public void setNginxUrl(String nginxUrl) {
+        this.nginxUrl = nginxUrl;
+    }
+}
-- 
2.18.1