瀏覽代碼

文件上传

zhuhaiwen 3 年之前
父節點
當前提交
a61a9bdb6b

+ 21 - 1
oa-app/src/main/java/com/css/oa/exam/announce/controller/AnnounceController.java

@ -8,9 +8,12 @@ import com.css.oa.exam.announce.service.AnnounceService;
8 8
import com.css.oa.utils.Result;
9 9
import io.swagger.annotations.Api;
10 10
import io.swagger.annotations.ApiOperation;
11
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
12
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
11 13
import org.apache.http.util.TextUtils;
12 14
import org.springframework.beans.factory.annotation.Autowired;
13 15
import org.springframework.web.bind.annotation.*;
16
import org.springframework.web.multipart.MultipartFile;
14 17
15 18
import java.util.List;
16 19
import java.util.Map;
@ -25,12 +28,29 @@ public class AnnounceController extends BaseController {
25 28
26 29
    @ApiOperation(value = "增加公告接口")
27 30
    @PostMapping("/add")
28
    public Result add(@RequestBody Announce announce) {
31
    public Result add(@RequestParam(value = "file") MultipartFile file,
32
                      @RequestParam(value = "title") String title,
33
                      @RequestParam(value = "author") String author,
34
                      @RequestParam(value = "publisher") String publisher,
35
                      @RequestParam(value = "content") String content,
36
                      @RequestParam(value = "is_top") int is_top,
37
                      @RequestParam(value = "type") int type
38
                      ) {
29 39
        Result<Map> result;
30 40
        try {
41
            Announce announce = new Announce();
42
            announce.file = file;
43
            announce.title = title;
44
            announce.author = author;
45
            announce.publisher = publisher;
46
            announce.content = content;
47
            announce.is_top = is_top;
48
            announce.type = type;
31 49
            if (announce.type == 0) {
32 50
                return setErr("type公告类型为必选类型");
33 51
            }
52
            String token = getToken();
53
            mService.setToken(token);
34 54
            mService.add(announce);
35 55
            result = setResult();
36 56
        } catch (Exception e) {

+ 4 - 0
oa-app/src/main/java/com/css/oa/exam/announce/repository/Announce.java

@ -2,6 +2,7 @@ package com.css.oa.exam.announce.repository;
2 2
3 3
import com.fasterxml.jackson.annotation.JsonFormat;
4 4
import lombok.Data;
5
import org.springframework.web.multipart.MultipartFile;
5 6
6 7
import javax.persistence.*;
7 8
import java.io.Serializable;
@ -46,6 +47,9 @@ public class Announce implements Serializable {
46 47
    @Column(name = "FILE_PATH")
47 48
    public String file_path;
48 49
50
    @Transient
51
    public MultipartFile file;
52
49 53
//    // - - - - - - - - - - - - - - - - - - 下面是基础属性 - - - - - - - - - - - - - - - - - -
50 54
51 55
    @Column(name = "CREATE_TIME")

+ 33 - 27
oa-app/src/main/java/com/css/oa/exam/announce/service/AnnounceService.java

@ -1,5 +1,6 @@
1 1
package com.css.oa.exam.announce.service;
2 2
3
import com.css.oa.exam.admin.bean.Admin;
3 4
import com.css.oa.exam.announce.bean.AnnoType;
4 5
import com.css.oa.exam.announce.bean.SearchReq;
5 6
import com.css.oa.exam.base.BaseService;
@ -7,8 +8,8 @@ import com.css.oa.exam.announce.bean.AnnoQueryReq;
7 8
import com.css.oa.exam.announce.repository.Announce;
8 9
import com.css.oa.exam.announce.repository.IAnnounceRepository;
9 10
import com.css.oa.exam.util.CopyObjTool;
11
import com.css.oa.exam.util.upload.UploadService;
10 12
import com.css.oa.utils.DateUtils;
11
import com.css.oa.utils.UUIDGenerator;
12 13
import lombok.extern.slf4j.Slf4j;
13 14
import org.apache.http.util.TextUtils;
14 15
import org.springframework.beans.factory.annotation.Autowired;
@ -33,33 +34,38 @@ public class AnnounceService extends BaseService implements IAnnounceService {
33 34
    @Override
34 35
    public void add(Announce obj) {
35 36
        System.out.println("传入的obj => " + obj.toString());
36
        if (obj.getUuid() == null) {
37
            String id = UUIDGenerator.getUUID();
38
            obj.setUuid(id);
37
        //上传文件
38
        if (obj.file != null) {
39
            Admin admin = Admin.getAdminByToken(token);
40
            UploadService.upload(obj.file, admin);
39 41
        }
40
        Date newDate = new Date();
41
        if (obj.getPublish_time() == null) {
42
            obj.setPublish_time(newDate);
43
        }
44
        if (obj.getCreate_time() == null) {
45
            obj.setCreate_time(newDate);
46
        }
47
        if (obj.getUpdate_time() == null) {
48
            obj.setUpdate_time(newDate);
49
        }
50
        if (TextUtils.isEmpty(obj.getCreate_user()) || obj.getCreate_user().equalsIgnoreCase("null")) {
51
            obj.setCreate_user("系统");
52
        }
53
        if (TextUtils.isEmpty(obj.getUpdate_user()) || obj.getCreate_user().equalsIgnoreCase("null")) {
54
            obj.setUpdate_user("系统");
55
        }
56
        if (obj.getDel_flag() == null) {
57
            obj.setDel_flag("1");
58
        }
59
        if (obj.getRemark() == null) {
60
            obj.setRemark("系统默认的备注");
61
        }
62
        repository.save(obj);
42
//        if (obj.getUuid() == null) {
43
//            String id = UUIDGenerator.getUUID();
44
//            obj.setUuid(id);
45
//        }
46
//        Date newDate = new Date();
47
//        if (obj.getPublish_time() == null) {
48
//            obj.setPublish_time(newDate);
49
//        }
50
//        if (obj.getCreate_time() == null) {
51
//            obj.setCreate_time(newDate);
52
//        }
53
//        if (obj.getUpdate_time() == null) {
54
//            obj.setUpdate_time(newDate);
55
//        }
56
//        if (TextUtils.isEmpty(obj.getCreate_user()) || obj.getCreate_user().equalsIgnoreCase("null")) {
57
//            obj.setCreate_user("系统");
58
//        }
59
//        if (TextUtils.isEmpty(obj.getUpdate_user()) || obj.getCreate_user().equalsIgnoreCase("null")) {
60
//            obj.setUpdate_user("系统");
61
//        }
62
//        if (obj.getDel_flag() == null) {
63
//            obj.setDel_flag("1");
64
//        }
65
//        if (obj.getRemark() == null) {
66
//            obj.setRemark("系统默认的备注");
67
//        }
68
//        repository.save(obj);
63 69
    }
64 70
65 71
    @Override

+ 71 - 0
oa-app/src/main/java/com/css/oa/exam/util/upload/Exceptions.java

@ -0,0 +1,71 @@
1
/**
2
 * Copyright (c) 2005-2012 springside.org.cn
3
 */
4
package com.css.oa.exam.util.upload;
5
6
import javax.servlet.http.HttpServletRequest;
7
import java.io.PrintWriter;
8
import java.io.StringWriter;
9
10
/**
11
 * 关于异常的工具类.
12
 * @author calvin
13
 * @version 2013-01-15
14
 */
15
public class Exceptions {
16
17
	/**
18
	 * 将CheckedException转换为UncheckedException.
19
	 */
20
	public static RuntimeException unchecked(Exception e) {
21
		if (e instanceof RuntimeException) {
22
			return (RuntimeException) e;
23
		} else {
24
			return new RuntimeException(e);
25
		}
26
	}
27
28
	/**
29
	 * 将ErrorStack转化为String.
30
	 */
31
	public static String getStackTraceAsString(Throwable e) {
32
		if (e == null){
33
			return "";
34
		}
35
		StringWriter stringWriter = new StringWriter();
36
		e.printStackTrace(new PrintWriter(stringWriter));
37
		return stringWriter.toString();
38
	}
39
40
	/**
41
	 * 判断异常是否由某些底层的异常引起.
42
	 */
43
	public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
44
		Throwable cause = ex.getCause();
45
		while (cause != null) {
46
			for (Class<? extends Exception> causeClass : causeExceptionClasses) {
47
				if (causeClass.isInstance(cause)) {
48
					return true;
49
				}
50
			}
51
			cause = cause.getCause();
52
		}
53
		return false;
54
	}
55
56
	/**
57
	 * 在request中获取异常类
58
	 * @param request
59
	 * @return 
60
	 */
61
	public static Throwable getThrowable(HttpServletRequest request){
62
		Throwable ex = null;
63
		if (request.getAttribute("exception") != null) {
64
			ex = (Throwable) request.getAttribute("exception");
65
		} else if (request.getAttribute("javax.servlet.error.exception") != null) {
66
			ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
67
		}
68
		return ex;
69
	}
70
	
71
}

+ 73 - 0
oa-app/src/main/java/com/css/oa/exam/util/upload/FileInfoEntity.java

@ -0,0 +1,73 @@
1
package com.css.oa.exam.util.upload;
2
3
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4
import io.swagger.annotations.ApiModelProperty;
5
import lombok.Data;
6
7
import javax.persistence.Entity;
8
import javax.persistence.Id;
9
import javax.persistence.Table;
10
import java.util.Date;
11
12
@Data
13
@Entity
14
@Table(name = "OP_XM_ENCLOSURE")
15
@JsonIgnoreProperties(value = {"hibernateLazyInitializer"})
16
public class FileInfoEntity {
17
18
    @Id
19
    @ApiModelProperty("主键ID")
20
    private String uuid;
21
22
    @ApiModelProperty("项目ID,具体业务ID,例如:公告ID,OP_SHENBAO_NEWS表主键")
23
    private String xmId;
24
25
    @ApiModelProperty("项目类型,具体业务类型,例如:1=公告附件 2=公告图片")
26
    private String xmType;
27
28
    @ApiModelProperty("上传系统")
29
    private String uploadSystem;
30
31
    @ApiModelProperty("上传时指定的文件类型")
32
    private String uploadType;
33
34
    @ApiModelProperty("sm3值")
35
    private String uploadSm;
36
37
    @ApiModelProperty("sm3路径")
38
    private String uploadPath;
39
40
    @ApiModelProperty("密钥串")
41
    private String cipherKey;
42
43
    @ApiModelProperty("附件名称")
44
    private String fileName;
45
46
    @ApiModelProperty("附件类型")
47
    private String fileType;
48
49
    @ApiModelProperty("附件大小")
50
    private String fileSize;
51
52
    @ApiModelProperty("创建时间")
53
    private Date createTime;
54
55
    @ApiModelProperty("更新时间")
56
    private Date updateTime;
57
58
    @ApiModelProperty("创建人")
59
    private String createUser;
60
61
    @ApiModelProperty("更新人")
62
    private String updateUser;
63
64
    @ApiModelProperty("是否生效,0=无效 1=有效")
65
    private Integer isValid;
66
67
    @ApiModelProperty("删除标记,0=未删除 1=删除")
68
    private Integer delFlag;
69
70
    @ApiModelProperty("备注")
71
    private String remark;
72
73
}

+ 37 - 0
oa-app/src/main/java/com/css/oa/exam/util/upload/FileInfoRepository.java

@ -0,0 +1,37 @@
1
package com.css.oa.exam.util.upload;
2
3
import org.springframework.data.jpa.repository.JpaRepository;
4
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
5
import org.springframework.data.jpa.repository.Modifying;
6
import org.springframework.data.jpa.repository.Query;
7
import org.springframework.stereotype.Repository;
8
import org.springframework.transaction.annotation.Transactional;
9
10
@Repository
11
public interface FileInfoRepository extends JpaRepository<FileInfoEntity, String>, JpaSpecificationExecutor<FileInfoEntity> {
12
13
    /**
14
     * @brief 通过uuid获取FileInfoEntity
15
     * @detail 2021/4/21 17:51 zangtie 详细1 需求id#
16
     * @author zangtie
17
     * @since 2021/4/21 17:51
18
     * @param uuid OP_XM_ENCLOSURE表主键
19
     * @return com.css.oa.zcsb.repository.entity.FileInfoEntity
20
     */
21
    @Query("select f from FileInfoEntity f  where f.isValid = 1 and f.delFlag = 0 and f.uuid = ?1")
22
    FileInfoEntity findOne(String uuid);
23
24
    /**
25
     * @brief 通过uuid逻辑删除FileInfoEntity
26
     * @detail 2021/4/21 17:52 zangtie 详细1 需求id#
27
     * @author zangtie
28
     * @since 2021/4/21 17:52
29
     * @param uuid OP_XM_ENCLOSURE表主键
30
     * @return void
31
     */
32
    @Modifying
33
    @Transactional
34
    @Query("update FileInfoEntity set delFlag = 1 where uuid = ?1")
35
    void delete(String uuid);
36
37
}

+ 57 - 0
oa-app/src/main/java/com/css/oa/exam/util/upload/FileInfoUtil.java

@ -0,0 +1,57 @@
1
package com.css.oa.exam.util.upload;
2
3
import net.sf.json.JSONObject;
4
import com.css.oa.utils.UUIDGenerator;
5
import io.micrometer.core.instrument.util.StringUtils;
6
import lombok.extern.slf4j.Slf4j;
7
import org.springframework.beans.factory.annotation.Autowired;
8
9
import java.util.Date;
10
11
@Slf4j
12
public class FileInfoUtil {
13
14
    private static FileInfoUtil instance;
15
16
    public static FileInfoUtil getInstance() {
17
        if (instance == null) {
18
            instance = new FileInfoUtil();
19
        }
20
        return instance;
21
    }
22
23
    @Autowired
24
    FileInfoRepository fileInfoRepository;
25
26
    public void saveInfo(JSONObject json) {
27
        if (json.containsKey("result") && "false".equals(json.getString("result"))) {
28
            log.debug("上传文档报错:" + json.getString("message"));
29
            return;
30
        }
31
        FileInfoEntity entity = entity = new FileInfoEntity();
32
        entity.setUuid(UUIDGenerator.getUUID());
33
        entity.setUploadSystem(json.getString("srcSystem"));
34
        entity.setUploadType(json.getString("fileType"));
35
        entity.setUploadSm("sm3");
36
        entity.setUploadPath(json.getString("sm3Path"));
37
        entity.setCipherKey(json.getString("cipherKey"));
38
        String fileSrcName = json.getString("fileSrcName");
39
        if (fileSrcName.contains("-已加密.")) {
40
            fileSrcName = fileSrcName.replace("-已加密.", ".");
41
        }
42
        entity.setFileName(fileSrcName);
43
        entity.setFileType(json.getString("fileExt"));
44
        entity.setFileSize(json.getString("fileSize"));
45
        String xmType = json.getString("xmType");
46
        if (StringUtils.isNotEmpty(xmType)) {
47
            entity.setXmType(json.getString("xmType"));
48
        }
49
        entity.setCreateTime(new Date());
50
        entity.setCreateUser(json.getString("user_id"));
51
52
        entity.setDelFlag(0);
53
        entity.setIsValid(1);
54
        fileInfoRepository.save(entity);
55
    }
56
57
}

+ 755 - 0
oa-app/src/main/java/com/css/oa/exam/util/upload/HttpClientUtil.java

@ -0,0 +1,755 @@
1
package com.css.oa.exam.util.upload;
2
3
//import com.gxb.utils.Exceptions;
4
5
import org.apache.commons.io.IOUtils;
6
import org.apache.commons.lang3.StringUtils;
7
import org.apache.commons.lang3.tuple.ImmutableTriple;
8
import org.apache.commons.lang3.tuple.Triple;
9
import org.apache.http.*;
10
import org.apache.http.client.HttpRequestRetryHandler;
11
import org.apache.http.client.config.AuthSchemes;
12
import org.apache.http.client.config.CookieSpecs;
13
import org.apache.http.client.config.RequestConfig;
14
import org.apache.http.client.entity.UrlEncodedFormEntity;
15
import org.apache.http.client.methods.CloseableHttpResponse;
16
import org.apache.http.client.methods.HttpGet;
17
import org.apache.http.client.methods.HttpPost;
18
import org.apache.http.client.methods.HttpRequestBase;
19
import org.apache.http.client.protocol.HttpClientContext;
20
import org.apache.http.config.Registry;
21
import org.apache.http.config.RegistryBuilder;
22
import org.apache.http.conn.ConnectTimeoutException;
23
import org.apache.http.conn.routing.HttpRoute;
24
import org.apache.http.conn.socket.ConnectionSocketFactory;
25
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
26
import org.apache.http.conn.ssl.NoopHostnameVerifier;
27
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
28
import org.apache.http.entity.ContentType;
29
import org.apache.http.entity.StringEntity;
30
import org.apache.http.entity.mime.HttpMultipartMode;
31
import org.apache.http.entity.mime.MultipartEntityBuilder;
32
import org.apache.http.entity.mime.content.InputStreamBody;
33
import org.apache.http.entity.mime.content.StringBody;
34
import org.apache.http.impl.client.CloseableHttpClient;
35
import org.apache.http.impl.client.HttpClients;
36
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
37
import org.apache.http.message.BasicNameValuePair;
38
import org.apache.http.protocol.HttpContext;
39
import org.apache.http.ssl.SSLContexts;
40
import org.apache.http.ssl.TrustStrategy;
41
import org.apache.http.util.EntityUtils;
42
import org.slf4j.Logger;
43
import org.slf4j.LoggerFactory;
44
45
import javax.net.ssl.SSLContext;
46
import javax.net.ssl.SSLException;
47
import javax.net.ssl.SSLHandshakeException;
48
import javax.servlet.http.HttpServletResponse;
49
import java.io.*;
50
import java.net.UnknownHostException;
51
import java.nio.charset.StandardCharsets;
52
import java.security.KeyManagementException;
53
import java.security.KeyStoreException;
54
import java.security.NoSuchAlgorithmException;
55
import java.security.cert.CertificateException;
56
import java.security.cert.X509Certificate;
57
import java.util.*;
58
import java.util.concurrent.Executors;
59
import java.util.concurrent.ScheduledExecutorService;
60
import java.util.concurrent.TimeUnit;
61
62
/**
63
 * http请求工具类
64
 *
65
 * @author wangke
66
 * @date 2018/5/3 11:46
67
 */
68
public class HttpClientUtil {
69
70
    /**
71
     * 最大重试次数
72
     */
73
    public static int maxRetryTimes = 5;
74
75
    private static final int CONNECT_TIMEOUT = 4000;// 设置连接建立的超时时间为4s
76
    private static final int SOCKET_TIMEOUT = 300000;
77
    private static final int IDLE_TIMEOUT = 28000;
78
    private static final int MAX_CONN = 3000; // 最大连接数
79
    private static final int Max_PER_ROUTE = 1500;
80
    private static final int MAX_ROUTE = 2000;
81
    private static final String url = "http://fileback.miit.gov.cn";
82
    private final CloseableHttpClient httpClient; // 发送请求的客户端单例
83
    private static PoolingHttpClientConnectionManager manager; //连接池管理类
84
    private static ScheduledExecutorService monitorExecutor;
85
86
    private final static Object syncLock = new Object(); // 相当于线程锁,用于线程安全
87
88
    public static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
89
90
    public static void config(HttpRequestBase httpRequestBase) {
91
        httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
92
        httpRequestBase.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
93
        httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5");
94
        httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
95
        // 配置请求的超时设置
96
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
97
                .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
98
                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(CONNECT_TIMEOUT)
99
                .setSocketTimeout(SOCKET_TIMEOUT)
100
                .setConnectTimeout(CONNECT_TIMEOUT)
101
                .build();
102
        httpRequestBase.setConfig(requestConfig);
103
    }
104
105
    /**
106
     * 关闭连接池
107
     */
108
    public static void closeConnectionPool() {
109
        try {
110
            getInstance().httpClient.close();
111
            manager.close();
112
            monitorExecutor.shutdown();
113
        } catch (IOException e) {
114
            e.printStackTrace();
115
        }
116
    }
117
118
    public CloseableHttpClient getHttpClient() {
119
        return httpClient;
120
    }
121
122
    private static final HttpClientUtil httpClientUtil = new HttpClientUtil();
123
124
    public static HttpClientUtil getInstance() {
125
        return httpClientUtil;
126
    }
127
128
    /**
129
     * 根据host和port构建httpclient实例
130
     *
131
     * @param host 要访问的域名
132
     * @param port 要访问的端口
133
     * @return
134
     */
135
    public static CloseableHttpClient createHttpClient(String host, int port) {
136
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
137
        SSLConnectionSocketFactory sslConnectionSocketFactory = null;
138
        try {
139
            final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
140
                @Override
141
                public boolean isTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException {
142
                    return true;
143
                }
144
            }).build();
145
146
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
147
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
148
                    .register("http", plainsf)
149
                    .register("https", sslConnectionSocketFactory)
150
                    .build();
151
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
152
                    .setSocketTimeout(SOCKET_TIMEOUT)
153
                    .setConnectTimeout(CONNECT_TIMEOUT)
154
                    .build();
155
            manager = new PoolingHttpClientConnectionManager(registry);
156
            // 将最大连接数增加到200
157
            manager.setMaxTotal(MAX_CONN);
158
            // 将每个路由基础的连接增加到20
159
            manager.setDefaultMaxPerRoute(Max_PER_ROUTE);
160
161
            // 将目标主机的最大连接数增加到50
162
            HttpHost localhost = new HttpHost(host, port);
163
            manager.setMaxPerRoute(new HttpRoute(localhost), MAX_ROUTE);
164
165
            //请求重试处理
166
            HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
167
                public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
168
                    if (executionCount >= maxRetryTimes) {// 如果已经重试了5次,就放弃
169
                        return false;
170
                    }
171
                    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
172
                        log.error("receive no response from server, retry");
173
                        return true;
174
                    }
175
                    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
176
                        log.error("SSL hand shake exception");
177
                        return false;
178
                    }
179
                    if (exception instanceof InterruptedIOException) {// 超时
180
                        log.error("InterruptedIOException");
181
                        return false;
182
                    }
183
                    if (exception instanceof UnknownHostException) {// 目标服务器不可达
184
                        log.error("server host unknown");
185
                        return true;
186
                    }
187
                    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
188
                        log.error("Connection Time out");
189
                        return false;
190
                    }
191
                    if (exception instanceof SSLException) {// ssl握手异常
192
                        log.error("SSLException");
193
                        return false;
194
                    }
195
196
                    HttpClientContext clientContext = HttpClientContext.adapt(context);
197
                    HttpRequest request = clientContext.getRequest();
198
                    // 如果请求是幂等的,就再次尝试
199
                    return !(request instanceof HttpEntityEnclosingRequest);
200
                }
201
            };
202
            return HttpClients.custom()
203
                    .setConnectionManager(manager)
204
                    .setRetryHandler(httpRequestRetryHandler).setDefaultRequestConfig(requestConfig)
205
                    .build();
206
        } catch (NoSuchAlgorithmException e) {
207
            e.printStackTrace();
208
        } catch (KeyStoreException e) {
209
            e.printStackTrace();
210
        } catch (KeyManagementException e) {
211
            e.printStackTrace();
212
        }
213
        return null;
214
    }
215
216
    private HttpClientUtil() {
217
//        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
218
//        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
219
//        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "info");
220
//        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "info");
221
222
        String hostName = url;
223
        int port = 80;
224
        if (url.startsWith("http") || url.startsWith("HTTP"))
225
            hostName = url.split("/")[2];
226
        if (hostName.contains(":")) {
227
            String[] args = hostName.split(":");
228
            hostName = args[0];
229
            port = Integer.parseInt(args[1]);
230
        }
231
        //Security.insertProviderAt(new BouncyCastleProvider(), 1);
232
        httpClient = createHttpClient(hostName, port);
233
        if (monitorExecutor == null) {
234
            monitorExecutor = Executors.newScheduledThreadPool(1);
235
            monitorExecutor.scheduleAtFixedRate(new TimerTask() {
236
                @Override
237
                public void run() {
238
                    //关闭异常连接
239
                    manager.closeExpiredConnections();
240
                    //关闭5s空闲的连接
241
                    manager.closeIdleConnections(IDLE_TIMEOUT, TimeUnit.MILLISECONDS);
242
                    log.info("close expired and idle for over 5s connection");
243
                }
244
            }, 10000, 30000, TimeUnit.MILLISECONDS);
245
        }
246
    }
247
248
    /**
249
     * http get请求
250
     *
251
     * @param url
252
     * @return
253
     */
254
    public Triple<StatusLine, Header[], String> httpGet(String url, Map<String, String> headMap, Map<String, Object> parameterMap) {
255
        long startTime = System.currentTimeMillis();
256
        String responseContent = null;
257
        Header[] headers = null;
258
        StatusLine statusLine = null;
259
        try {
260
            if (!url.contains("?"))
261
                url += "?";
262
            else
263
                url += "&";
264
            if (parameterMap != null) {
265
                for (Map.Entry<String, Object> paramsMap : parameterMap.entrySet()) {
266
                    if (paramsMap.getKey() == null||paramsMap.getValue()==null)
267
                        continue;
268
                    else if (paramsMap.getValue() instanceof String) {
269
                        url += paramsMap.getKey() + "=" + paramsMap.getValue() + "&";
270
                    } else if (List.class.isAssignableFrom(paramsMap.getValue().getClass())) {
271
                        List list = (List) paramsMap.getValue();
272
                        for (int i = 0; i < list.size(); i++)
273
                            url += paramsMap.getKey() + "=" +  list.get(i).toString() + "&";
274
                    }
275
                }
276
            }
277
            if (url.endsWith("&"))
278
                url = url.substring(0, url.length() - 1);
279
            HttpGet request = new HttpGet(url);
280
            if (headMap != null) {
281
                for (Map.Entry<String, String> e : headMap.entrySet()) {
282
                    request.addHeader(e.getKey(), e.getValue());
283
                }
284
            }
285
            CloseableHttpResponse response = httpClient.execute(request);
286
            try {
287
                headers = response.getAllHeaders();
288
                statusLine = response.getStatusLine();
289
                HttpEntity entity = response.getEntity();
290
                responseContent = EntityUtils.toString(entity, "UTF-8");
291
                EntityUtils.consume(entity);
292
            } finally {
293
                response.close();
294
            }
295
        } catch (Exception e) {
296
            log.error(Exceptions.getStackTraceAsString(e));
297
        }
298
        log.debug(System.currentTimeMillis() - startTime + " ms httpGet spendTime");
299
        return new ImmutableTriple(statusLine, headers, responseContent);
300
    }
301
302
    /**
303
     * 将返回结果转化为String
304
     *
305
     * @param entity
306
     * @return
307
     * @throws Exception
308
     */
309
    private String getRespString(HttpEntity entity) throws Exception {
310
        if (entity == null) {
311
            return null;
312
        }
313
        StringBuffer strBuf = new StringBuffer();
314
        try (InputStream is = entity.getContent()) {
315
            byte[] buffer = new byte[4096];
316
            int r = 0;
317
            while ((r = is.read(buffer)) > 0) {
318
                strBuf.append(new String(buffer, 0, r, StandardCharsets.UTF_8));
319
            }
320
        }
321
        return strBuf.toString();
322
    }
323
324
    /**
325
     * http的post请求
326
     *
327
     * @param url
328
     * @param paramsMap
329
     * @return
330
     */
331
    public Triple<StatusLine, Header[], String> httpPost(String url, Map<String, Object> paramsMap,
332
                                                         Map<String, String> headMap) {
333
        String responseContent = null;
334
        Header[] headers = null;
335
        StatusLine statusLine = null;
336
        Long startTime = System.currentTimeMillis();
337
        try {
338
            HttpPost httpPost = new HttpPost(url);
339
            if (headMap != null) {
340
                for (Map.Entry<String, String> e : headMap.entrySet()) {
341
                    httpPost.addHeader(e.getKey(), e.getValue());
342
                }
343
            }
344
            if (paramsMap != null) {
345
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
346
                for (String key : paramsMap.keySet()) {
347
                    if (paramsMap.get(key) == null)
348
                        continue;
349
                    else if (paramsMap.get(key) instanceof String) {
350
                        String value = ((String) paramsMap.get(key));
351
                        nameValuePairList.add(new BasicNameValuePair(key, value));
352
                    } else if (List.class.isAssignableFrom(paramsMap.get(key).getClass())) {
353
                        List list = (List) paramsMap.get(key);
354
                        for (int i = 0; i < list.size(); i++)
355
                            nameValuePairList.add(new BasicNameValuePair(key, list.get(i).toString()));
356
                    }
357
                }
358
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
359
                formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
360
                httpPost.setEntity(formEntity);
361
                // request.setEntity(new ByteArrayEntity(body));
362
                // request.setEntity(new StringEntity(body, "utf-8"));
363
            }
364
            CloseableHttpResponse response = httpClient.execute(httpPost);
365
            try {
366
                headers = response.getAllHeaders();
367
                statusLine = response.getStatusLine();
368
                HttpEntity entity = response.getEntity();
369
                responseContent = EntityUtils.toString(entity, "UTF-8");
370
                EntityUtils.consume(entity);
371
            } finally {
372
                response.close();
373
            }
374
        } catch (Exception e) {
375
            log.error(Exceptions.getStackTraceAsString(e));
376
        }
377
        log.debug(System.currentTimeMillis() - startTime + " ms httpPost spendTime");
378
        return new ImmutableTriple(statusLine, headers, responseContent);
379
    }
380
381
    public Triple<StatusLine, Header[], String> httpPost(String url, String json,
382
                                                         Map<String, String> headMap) {
383
        String responseContent = null;
384
        Header[] headers = null;
385
        StatusLine statusLine = null;
386
        Long startTime = System.currentTimeMillis();
387
        try {
388
            HttpPost httpPost = new HttpPost(url);
389
            if (headMap != null) {
390
                for (Map.Entry<String, String> e : headMap.entrySet()) {
391
                    httpPost.addHeader(e.getKey(), e.getValue());
392
                }
393
            }
394
            httpPost.setHeader("Content-type", "application/json");
395
            if (StringUtils.isBlank(json)) {
396
                throw new RuntimeException("json串不能为空");
397
            }
398
            StringEntity requestEntity = new StringEntity(json, "utf-8");
399
            requestEntity.setContentEncoding("UTF-8");
400
            httpPost.setEntity(requestEntity);
401
402
            CloseableHttpResponse response = httpClient.execute(httpPost);
403
            try {
404
                headers = response.getAllHeaders();
405
                statusLine = response.getStatusLine();
406
                HttpEntity entity = response.getEntity();
407
                responseContent = EntityUtils.toString(entity, "UTF-8");
408
                EntityUtils.consume(entity);
409
            } finally {
410
                response.close();
411
            }
412
        } catch (Exception e) {
413
            log.error(Exceptions.getStackTraceAsString(e));
414
        }
415
        log.debug(System.currentTimeMillis() - startTime + " ms httpPost spendTime");
416
        return new ImmutableTriple(statusLine, headers, responseContent);
417
    }
418
419
    public Triple<StatusLine, Header[], String> uploadThenDownload(String serverUrl, InputStream fileInputStream, String fileName,
420
                                                                   String serverFieldName, Map<String, Object> params, Map<String, String> headMap, OutputStream out) throws Exception {
421
422
        Header[] headers = null;
423
        StatusLine statusLine = null;
424
        CloseableHttpResponse response = null;
425
        try {
426
            HttpPost httpPost = new HttpPost(serverUrl);
427
            if (headMap != null) {
428
                for (Map.Entry<String, String> e : headMap.entrySet()) {
429
                    httpPost.addHeader(e.getKey(), e.getValue());
430
                }
431
            }
432
            if (fileInputStream != null) {
433
                InputStreamBody streamBody = new InputStreamBody(fileInputStream, ContentType.APPLICATION_OCTET_STREAM, fileName);
434
                MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
435
                        .create().setMode(HttpMultipartMode.RFC6532);
436
                multipartEntityBuilder.setCharset(Consts.UTF_8);
437
                // add the file params
438
                multipartEntityBuilder.addPart(serverFieldName, streamBody);
439
                // 设置上传的其他参数
440
                setUploadParams(multipartEntityBuilder, params);
441
                HttpEntity reqEntity = multipartEntityBuilder.build();
442
                httpPost.setEntity(reqEntity);
443
            } else {
444
                if (params != null) {
445
                    List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
446
                    for (String key : params.keySet()) {
447
                        if (params.get(key) == null)
448
                            continue;
449
                        else if (params.get(key) instanceof String) {
450
                            String value = params.get(key).toString();
451
                            nameValuePairList.add(new BasicNameValuePair(key, value));
452
                        }
453
                    }
454
                    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
455
                    formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
456
                    httpPost.setEntity(formEntity);
457
                }
458
            }
459
            response = httpClient.execute(httpPost);
460
461
            headers = response.getAllHeaders();
462
            statusLine = response.getStatusLine();
463
            String contentDisposition = response.getFirstHeader("Content-Disposition") != null ? response.getFirstHeader("Content-Disposition").getValue() : "";
464
            if (!contentDisposition.equals(""))
465
                fileName = contentDisposition.substring(contentDisposition.indexOf("\"") + 1, contentDisposition.length() - 1);
466
            HttpEntity entity = response.getEntity();
467
            long contentLength = entity.getContentLength();
468
            log.debug(contentLength + " contentLength");
469
            InputStream in = entity.getContent();
470
            // 通过ioutil 对接输入输出流
471
            if(out!=null)
472
              IOUtils.copy(new BufferedInputStream(in), out);
473
            EntityUtils.consume(entity);
474
        } finally {
475
            if(out!=null)
476
              out.close();
477
            response.close();
478
        }
479
        return new ImmutableTriple(statusLine, headers, fileName);
480
    }
481
482
    /**
483
     * 设置上传文件时所附带的其他参数
484
     *
485
     * @param multipartEntityBuilder
486
     * @param params
487
     */
488
    private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
489
                                 Map<String, Object> params) {
490
        if (params != null && params.size() > 0) {
491
            Set<String> keys = params.keySet();
492
            for (String key : keys) {
493
                multipartEntityBuilder
494
                        .addPart(key, new StringBody(params.get(key).toString(),
495
                                ContentType.create("text/plain", Consts.UTF_8)));
496
            }
497
        }
498
    }
499
500
    /**
501
     * 上传文件
502
     *
503
     * @param serverUrl       服务器地址
504
     * @param serverFieldName
505
     * @param params
506
     * @return
507
     * @throws Exception
508
     */
509
    public Triple<StatusLine, Header[], String> uploadFileImpl(String serverUrl, InputStream fileInputStream, String fileName,
510
                                                               String serverFieldName, Map<String, Object> params, Map<String, String> headMap)
511
            throws Exception {
512
        String respStr = null;
513
        Header[] headers = null;
514
        StatusLine statusLine = null;
515
        CloseableHttpResponse response = null;
516
        try {
517
518
            HttpPost httpPost = new HttpPost(serverUrl);
519
//            RequestConfig requestConfig = RequestConfig.custom().setProxy(new HttpHost("127.0.0.1", 8888)).build();
520
//            httpPost.setConfig(requestConfig);
521
            if (headMap != null) {
522
                for (Map.Entry<String, String> e : headMap.entrySet()) {
523
                    httpPost.addHeader(e.getKey(), e.getValue());
524
                }
525
            }
526
            InputStreamBody streamBody = new InputStreamBody(fileInputStream, ContentType.APPLICATION_OCTET_STREAM, fileName);
527
            //FileBody binFileBody = new FileBody(new File(localFilePath), ContentType.APPLICATION_OCTET_STREAM);
528
529
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
530
                    .create().setMode(HttpMultipartMode.RFC6532);
531
            multipartEntityBuilder.setCharset(Consts.UTF_8);
532
            // add the file params
533
            multipartEntityBuilder.addPart(serverFieldName, streamBody);
534
            // 设置上传的其他参数
535
            setUploadParams(multipartEntityBuilder, params);
536
537
            HttpEntity reqEntity = multipartEntityBuilder.build();
538
            httpPost.setEntity(reqEntity);
539
            response = httpClient.execute(httpPost);
540
            headers = response.getAllHeaders();
541
            statusLine = response.getStatusLine();
542
543
            HttpEntity resEntity = response.getEntity();
544
            respStr = EntityUtils.toString(resEntity, "UTF-8");
545
            EntityUtils.consume(resEntity);
546
        } finally {
547
            if (response != null)
548
                response.close();
549
            if (fileInputStream != null)
550
                fileInputStream.close();
551
        }
552
        return new ImmutableTriple(statusLine, headers, respStr);
553
    }
554
555
    public Triple<StatusLine, Header[], String> httpDownloadFile(String url, String filePath,
556
                                                                 Map<String, String> headMap, Map<String, Object> parameterMap) throws FileNotFoundException {
557
        return httpDownloadFile(url, new FileOutputStream(filePath), headMap, parameterMap);
558
    }
559
560
    public Triple<StatusLine, Header[], String> httpDownloadFile(String url, OutputStream out,
561
                                                                 Map<String, String> headMap, Map<String, Object> parameterMap) {
562
        String fileName = "";
563
        Header[] headers = null;
564
        StatusLine statusLine = null;
565
        try {
566
            HttpPost request = new HttpPost(url);
567
            config(request);
568
            if (headMap != null) {
569
                for (Map.Entry<String, String> e : headMap.entrySet()) {
570
                    request.addHeader(e.getKey(), e.getValue());
571
                }
572
            }
573
            if (parameterMap != null) {
574
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
575
                for (String key : parameterMap.keySet()) {
576
                    if (parameterMap.get(key) == null)
577
                        continue;
578
                    else if (parameterMap.get(key) instanceof String) {
579
                        String value = ((String) parameterMap.get(key));
580
                        nameValuePairList.add(new BasicNameValuePair(key, value));
581
                    } else if (List.class.isAssignableFrom(parameterMap.get(key).getClass())) {
582
                        List list = (List) parameterMap.get(key);
583
                        for (int i = 0; i < list.size(); i++)
584
                            nameValuePairList.add(new BasicNameValuePair(key, list.get(i).toString()));
585
                    }
586
                }
587
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
588
                formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
589
                request.setEntity(formEntity);
590
            }
591
            CloseableHttpResponse response = httpClient.execute(request);
592
            try {
593
                headers = response.getAllHeaders();
594
                statusLine = response.getStatusLine();
595
                String contentDisposition = response.getFirstHeader("Content-Disposition") != null ? response.getFirstHeader("Content-Disposition").getValue() : "";
596
                if (!contentDisposition.equals(""))
597
                    fileName = contentDisposition.substring(contentDisposition.indexOf("\"") + 1, contentDisposition.length() - 1);
598
                //fileName=new String(fileName.getBytes("ISO-8859-1"));
599
                HttpEntity httpEntity = response.getEntity();
600
                long contentLength = httpEntity.getContentLength();
601
                log.debug(contentLength + " contentLength fileName: "+fileName);
602
                InputStream in = httpEntity.getContent();
603
                // 通过ioutil 对接输入输出流
604
                IOUtils.copy(new BufferedInputStream(in), out);
605
                EntityUtils.consume(httpEntity);
606
            } finally {
607
                out.close();
608
                response.close();
609
            }
610
        } catch (Exception e) {
611
            log.error(Exceptions.getStackTraceAsString(e));
612
        }
613
        return new ImmutableTriple(statusLine, headers, fileName);
614
    }
615
616
    public Triple<Header[],String, HttpEntity> httpDownloadFile(String url,
617
                                                                Map<String, String> headMap, Map<String, Object> parameterMap) {
618
        String fileName = "";
619
        Header[] headers = null;
620
        HttpEntity httpEntity = null;
621
        try {
622
            HttpPost request = new HttpPost(url);
623
            config(request);
624
            if (headMap != null) {
625
                for (Map.Entry<String, String> e : headMap.entrySet()) {
626
                    request.addHeader(e.getKey(), e.getValue());
627
                }
628
            }
629
            if (parameterMap != null) {
630
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
631
                for (String key : parameterMap.keySet()) {
632
                    if (parameterMap.get(key) == null)
633
                        continue;
634
                    else if (parameterMap.get(key) instanceof String) {
635
                        String value = ((String) parameterMap.get(key));
636
                        nameValuePairList.add(new BasicNameValuePair(key, value));
637
                    } else if (List.class.isAssignableFrom(parameterMap.get(key).getClass())) {
638
                        List list = (List) parameterMap.get(key);
639
                        for (int i = 0; i < list.size(); i++)
640
                            nameValuePairList.add(new BasicNameValuePair(key, list.get(i).toString()));
641
                    }
642
                }
643
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
644
                formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
645
                request.setEntity(formEntity);
646
            }
647
            CloseableHttpResponse response = httpClient.execute(request);
648
            headers = response.getAllHeaders();
649
            String contentDisposition = response.getFirstHeader("Content-Disposition") != null ? response.getFirstHeader("Content-Disposition").getValue() : "";
650
            if (!contentDisposition.equals(""))
651
                fileName = contentDisposition.substring(contentDisposition.indexOf("\"") + 1, contentDisposition.length() - 1);
652
            //if(fileNameIso8859)
653
            //  fileName=new String(fileName.getBytes("ISO-8859-1"));
654
            httpEntity = response.getEntity();
655
            long contentLength = httpEntity.getContentLength();
656
            log.debug(contentLength + " contentLength");
657
        } catch (Exception e) {
658
            log.error(Exceptions.getStackTraceAsString(e));
659
        }
660
        return new ImmutableTriple(headers, fileName, httpEntity);
661
    }
662
663
    public void httpDownloadFileBackToFront(String url, String userAgent, HttpServletResponse response,
664
                                            Map<String, String> headMap, Map<String, String> parameterMap) {
665
        OutputStream out = null;
666
        String fileName = "";
667
        try {
668
            if (!url.contains("?"))
669
                url += "?";
670
            else
671
                url += "&";
672
            if (parameterMap != null) {
673
                for (Map.Entry<String, String> e : parameterMap.entrySet()) {
674
                    url += e.getKey() + "=" + e.getValue() + "&";
675
                }
676
            }
677
            if (url.endsWith("&"))
678
                url = url.substring(0, url.length() - 1);
679
            HttpGet request = new HttpGet(url);
680
            config(request);
681
            if (headMap != null) {
682
                for (Map.Entry<String, String> e : headMap.entrySet()) {
683
                    request.addHeader(e.getKey(), e.getValue());
684
                }
685
            }
686
            CloseableHttpResponse response1 = httpClient.execute(request);
687
            try {
688
                log.debug(response1.getStatusLine().toString());
689
                fileName = response1.getFirstHeader("Content-Disposition").getValue().substring(response1.getFirstHeader("Content-Disposition").getValue().indexOf("\"") + 1, response1.getFirstHeader("Content-Disposition").getValue().length() - 1);
690
                //fileName=new String(fileName.getBytes("ISO-8859-1"));
691
                HttpEntity httpEntity = response1.getEntity();
692
                long contentLength = httpEntity.getContentLength();
693
                if (contentLength != 0l) {
694
                    response.setContentLength((int) contentLength);
695
                    response.addHeader("Content-Length", contentLength + "");
696
                }
697
                response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
698
                InputStream in = httpEntity.getContent();
699
                // 通过ioutil 对接输入输出流
700
                out = response.getOutputStream();
701
                IOUtils.copy(new BufferedInputStream(in), out);
702
                EntityUtils.consume(httpEntity);
703
            } finally {
704
                out.close();
705
            }
706
        } catch (Exception e) {
707
            e.printStackTrace();
708
        }
709
    }
710
711
    public void httpDownloadFileProgress(String url, String filePath,
712
                                         HttpClientDownLoadProgress progress, Map<String, String> headMap) {
713
714
        try {
715
            HttpGet request = new HttpGet(url);
716
            if (headMap != null) {
717
                for (Map.Entry<String, String> e : headMap.entrySet()) {
718
                    request.addHeader(e.getKey(), e.getValue());
719
                }
720
            }
721
            CloseableHttpResponse response1 = httpClient.execute(request);
722
            try {
723
                System.out.println(response1.getStatusLine());
724
                HttpEntity httpEntity = response1.getEntity();
725
726
                long contentLength = httpEntity.getContentLength();
727
                InputStream is = httpEntity.getContent();
728
                // 根据InputStream 下载文件
729
                FileOutputStream fos = new FileOutputStream(filePath);
730
                byte[] buffer = new byte[4096];
731
                int r = 0;
732
                long totalRead = 0;
733
                while ((r = is.read(buffer)) > 0) {
734
                    fos.write(buffer, 0, r);
735
                    totalRead += r;
736
                    if (progress != null) {// 回调进度
737
                        progress.onProgress((int) (totalRead * 100 / contentLength));
738
                    }
739
                }
740
                fos.flush();
741
                fos.close();
742
                EntityUtils.consume(httpEntity);
743
            } finally {
744
                response1.close();
745
            }
746
        } catch (Exception e) {
747
            e.printStackTrace();
748
        }
749
    }
750
751
    public interface HttpClientDownLoadProgress {
752
        void onProgress(int progress);
753
    }
754
755
}

+ 28 - 0
oa-app/src/main/java/com/css/oa/exam/util/upload/UploadService.java

@ -0,0 +1,28 @@
1
package com.css.oa.exam.util.upload;
2
3
import com.css.oa.exam.admin.bean.Admin;
4
import lombok.extern.slf4j.Slf4j;
5
import net.sf.json.JSONObject;
6
import org.apache.commons.lang3.StringUtils;
7
import org.apache.commons.lang3.tuple.Triple;
8
import org.apache.http.Header;
9
import org.apache.http.StatusLine;
10
import org.slf4j.Logger;
11
import org.slf4j.LoggerFactory;
12
import org.springframework.core.io.ClassPathResource;
13
import org.springframework.web.multipart.MultipartFile;
14
15
import java.io.*;
16
import java.util.*;
17
18
@Slf4j
19
public class UploadService {
20
21
    public static void upload(MultipartFile file, Admin admin) {
22
        JSONObject json = UploadUtil.upload(file, admin);
23
24
        json.put("user_id", admin.my_unit_id);
25
        FileInfoUtil.getInstance().saveInfo(json);
26
    }
27
28
}

+ 134 - 0
oa-app/src/main/java/com/css/oa/exam/util/upload/UploadUtil.java

@ -0,0 +1,134 @@
1
package com.css.oa.exam.util.upload;
2
3
import com.css.oa.exam.admin.bean.Admin;
4
import lombok.extern.slf4j.Slf4j;
5
import net.sf.json.JSONObject;
6
import org.apache.commons.lang3.StringUtils;
7
import org.apache.commons.lang3.tuple.Triple;
8
import org.apache.http.Header;
9
import org.apache.http.StatusLine;
10
import org.springframework.core.io.ClassPathResource;
11
import org.springframework.web.multipart.MultipartFile;
12
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InputStreamReader;
16
import java.util.*;
17
18
@Slf4j
19
public class UploadUtil {
20
21
    private static Map<String, Object> uploadParamsMap = new HashMap();
22
    private static Map<String, Object> downloadParamsMap = new HashMap<String, Object>();
23
    private static Map<String, Object> accessTokenParamsMap = new HashMap<String, Object>();
24
    private static Map<String, Object> decryptParamsMap = new HashMap<String, Object>();
25
    private static Map<String, Object> previewParamsMap = new HashMap<String, Object>();
26
27
    static {
28
        Properties props = new Properties();
29
        StringBuffer whiteList = new StringBuffer();
30
        try {
31
            //读取上传配置文件
32
            ClassPathResource classPathResource = new ClassPathResource("/fileUpload.properties");
33
            InputStream in = classPathResource.getInputStream();
34
            InputStreamReader ins = new InputStreamReader(in, "UTF-8");
35
            props.load(ins);
36
            in.close();
37
            ins.close();
38
        } catch (IOException e) {
39
            e.printStackTrace();
40
            //logger.info("读取配置文件 fileUpload.properties 失败,格式不正确!");
41
        }
42
        Iterator<Map.Entry<Object, Object>> it = props.entrySet().iterator();
43
        while (it.hasNext()) {
44
            Map.Entry<Object, Object> entry = it.next();
45
            String key = entry.getKey() == null ? "" : entry.getKey().toString();
46
            String value = entry.getValue() == null ? "" : entry.getValue().toString();
47
            if (StringUtils.isNotBlank(key)) {
48
                //获取上传参数
49
                if (key.startsWith("upload") && key.indexOf(".") != -1) {
50
                    String[] keys = key.split("\\.");
51
                    if (keys.length >= 2) {
52
                        uploadParamsMap.put(keys[1], value);
53
54
                    }
55
                }
56
                //获取下载参数
57
                if (key.startsWith("download") && key.indexOf(".") != -1) {
58
                    String[] keys = key.split("\\.");
59
                    if (keys.length >= 2) {
60
                        downloadParamsMap.put(keys[1], value);
61
62
                    }
63
                }
64
                //获取获取动态令牌的参数
65
                if (key.startsWith("accesstoken") && key.indexOf(".") != -1) {
66
                    String[] keys = key.split("\\.");
67
                    if (keys.length >= 2) {
68
                        accessTokenParamsMap.put(keys[1], value);
69
70
                    }
71
                }
72
                //获取解密的参数
73
                if (key.startsWith("decrypt") && key.indexOf(".") != -1) {
74
                    String[] keys = key.split("\\.");
75
                    if (keys.length >= 2) {
76
                        decryptParamsMap.put(keys[1], value);
77
78
                    }
79
                }
80
                // 转版DOCX/图片/文本文件获取PDF
81
                if (key.startsWith("preview") && key.indexOf(".") != -1) {
82
                    String[] keys = key.split("\\.");
83
                    if (keys.length >= 2) {
84
                        previewParamsMap.put(keys[1], value);
85
86
                    }
87
                }
88
            }
89
        }
90
91
    }
92
93
    public static JSONObject upload(MultipartFile file, Admin admin) {
94
        JSONObject json = null;
95
        try {
96
            String fileName = file.getOriginalFilename();
97
            InputStream in = file.getInputStream();
98
            Triple<StatusLine, Header[], String> triple = null;
99
100
            uploadParamsMap.put("userName", admin.name);
101
            try {
102
                triple = HttpClientUtil.getInstance().uploadFileImpl(uploadParamsMap.get("serverPath").toString(),
103
                        in, fileName, "file", uploadParamsMap, null); //按照流的方式上传文件名需要单独作为参数上传
104
            } catch (Exception e) {
105
                log.debug(Exceptions.getStackTraceAsString(e));
106
            }
107
            log.debug(triple.getLeft() + " statusLine");
108
            log.debug(Arrays.asList(triple.getMiddle()) + " Headers");
109
            log.debug(triple.getRight());
110
111
            if (isJSON(triple.getRight())) {
112
                json = JSONObject.fromObject(triple.getRight());
113
            } else {
114
                json = new JSONObject();
115
                json.put("result", "false");
116
                json.put("message", triple.getRight());
117
            }
118
        } catch (Exception e) {
119
            e.printStackTrace();
120
        }
121
        return json;
122
    }
123
124
    private static Boolean isJSON(String str) {
125
        Boolean result = false;
126
        try {
127
            JSONObject json = JSONObject.fromObject(str);
128
            result = true;
129
        } catch (Exception e) {
130
            result = false;
131
        }
132
        return result;
133
    }
134
}

+ 47 - 0
oa-app/src/main/resources/fileUpload.properties

@ -0,0 +1,47 @@
1
upload.userId = -1
2
upload.srcSystem = 131452021
3
upload.token = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN-ZunAY9W94DxGz66PQFissaqjLMvyXkBNvCqmNqm1UokbOVpgEqyTzftR0pbMQOBsIV07IBIzlJuV5_ljVbnRSR7UIVrPm6atwpTfm5e5dTt88BmHHjQojQneEOIcZL9Avpvx488HuoNjNpOx2frydwHAHd5IynfVkczg1vfZQIDAQAB
4
upload.businessId =
5
upload.isTemp = 0
6
upload.isPublic = 1
7
upload.isValidate = 1
8
upload.anyoneDownload = 0
9
upload.fileType = GK
10
upload.isEncrypt = 1
11
upload.isStore = 0
12
upload.algorithm = SM4
13
upload.isHexKey = 1
14
upload.iv = 1234567812345678
15
upload.fileServiceURL = http://10.13.1.180
16
upload.serverPath = http://10.13.1.180/file/uploadDfsBackEnd
17
download.userId = -1
18
download.srcSystem = 131452021
19
download.token = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN-ZunAY9W94DxGz66PQFissaqjLMvyXkBNvCqmNqm1UokbOVpgEqyTzftR0pbMQOBsIV07IBIzlJuV5_ljVbnRSR7UIVrPm6atwpTfm5e5dTt88BmHHjQojQneEOIcZL9Avpvx488HuoNjNpOx2frydwHAHd5IynfVkczg1vfZQIDAQAB
20
download.fileType = GK
21
download.fileServiceURL = http://10.13.1.180
22
download.serverPath = http://10.13.1.180/file/downloadBackEnd
23
download.algorithm = SM4
24
download.isHexKey = 1
25
download.iv = 1234567812345678
26
accesstoken.userId = -1
27
accesstoken.srcSystem = 131452021
28
accesstoken.token = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN-ZunAY9W94DxGz66PQFissaqjLMvyXkBNvCqmNqm1UokbOVpgEqyTzftR0pbMQOBsIV07IBIzlJuV5_ljVbnRSR7UIVrPm6atwpTfm5e5dTt88BmHHjQojQneEOIcZL9Avpvx488HuoNjNpOx2frydwHAHd5IynfVkczg1vfZQIDAQAB
29
accesstoken.expireTime = 3600
30
accesstoken.notBeforeTime = 0
31
accesstoken.fileServiceURL = http://10.13.1.180
32
accesstoken.serverPath = http://10.13.1.180/file/getAccessToken
33
decrypt.userId = -1
34
decrypt.srcSystem = 131452021
35
decrypt.token = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN-ZunAY9W94DxGz66PQFissaqjLMvyXkBNvCqmNqm1UokbOVpgEqyTzftR0pbMQOBsIV07IBIzlJuV5_ljVbnRSR7UIVrPm6atwpTfm5e5dTt88BmHHjQojQneEOIcZL9Avpvx488HuoNjNpOx2frydwHAHd5IynfVkczg1vfZQIDAQAB
36
decrypt.noSsoUpload = 1
37
decrypt.isHexKey = 1
38
decrypt.iv = 1234567812345678
39
decrypt.algorithm = SM4
40
decrypt.isResponseFileEntity = 0
41
decrypt.fileType = GK
42
decrypt.isTemp = 0
43
decrypt.isPublic = 4
44
decrypt.businessId =
45
decrypt.isStore = 1
46
decrypt.fileServiceURL = http://10.13.1.180
47
decrypt.serverPath = http://10.13.1.180/file/decryptFile

+ 26 - 19
oa-app/src/test/java/com/css/oa/supervision/waitexec/service/impl/MyTest.java

@ -56,25 +56,32 @@ public class MyTest {
56 56
////        System.out.println("numberString => "+numberString);
57 57
//    }
58 58
59
    @Test
60
    public void a3() {
61
        String accessKeyId = "hellocode";
62
        String secureKey = "f53d3819d5e265984fc8911d36377280";
63
64
        long timestamp = 1619770939;//new Date().getTime();
65
        try {
66
            String signature = hmacsha1((accessKeyId + "\n" + timestamp).getBytes(), secureKey.getBytes());
67
            System.out.println(signature);
68
        } catch (Exception e) {
69
            e.printStackTrace();
70
        }
71
    }
59
//    @Test
60
//    public void a3() {
61
//        String accessKeyId = "hellocode";
62
//        String secureKey = "f53d3819d5e265984fc8911d36377280";
63
//
64
//        long timestamp = 1619770939;//new Date().getTime();
65
//        try {
66
//            String signature = hmacsha1((accessKeyId + "\n" + timestamp).getBytes(), secureKey.getBytes());
67
//            System.out.println(signature);
68
//        } catch (Exception e) {
69
//            e.printStackTrace();
70
//        }
71
//    }
72
//
73
//    private String hmacsha1(byte[] data, byte[] key) throws Exception {
74
//        SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
75
//        Mac mac = Mac.getInstance("HmacSHA1");
76
//        mac.init(signingKey);
77
//        byte[] rawHmac = mac.doFinal(data);
78
//        return org.apache.commons.codec.binary.Base64.encodeBase64String(rawHmac);
79
//    }
72 80
73
    private String hmacsha1(byte[] data, byte[] key) throws Exception {
74
        SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
75
        Mac mac = Mac.getInstance("HmacSHA1");
76
        mac.init(signingKey);
77
        byte[] rawHmac = mac.doFinal(data);
78
        return org.apache.commons.codec.binary.Base64.encodeBase64String(rawHmac);
81
    @Test
82
    public void a4() {
83
        String originalFilename = "logo.png";
84
        String[] filename = originalFilename.split("\\.");
85
        System.out.println(filename);
79 86
    }
80 87
}

+ 6 - 1
pom.xml

@ -160,7 +160,12 @@
160 160
            <version>1.7</version>
161 161
        </dependency>
162 162
163
163
        <!--网络请求的作用-->
164
        <dependency>
165
            <groupId>org.apache.httpcomponents</groupId>
166
            <artifactId>httpmime</artifactId>
167
            <version>4.5.9</version>
168
        </dependency>
164 169
165 170
        <dependency>
166 171
            <groupId>css.slw</groupId>