inleft
2022-02-09 9bcb19959eeb9da9bde2561e7278f6d0a55eb151
commit | author | age
9bcb19 1 /*
I 2 Copyright [2020] [https://www.xiaonuo.vip]
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8   http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15
16 Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
17
18 1.请不要删除和修改根目录下的LICENSE文件。
19 2.请不要删除和修改Snowy源码头部的版权声明。
20 3.请保留源码和相关描述文件的项目出处,作者声明等。
21 4.分发源码时候,请注明软件出处 https://gitee.com/xiaonuobase/snowy
22 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/xiaonuobase/snowy
23 6.若您的项目无法满足以上几点,可申请商业授权,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip
24  */
25 package vip.xiaonuo.core.file.modular.tencent;
26
27 import cn.hutool.core.io.IoUtil;
28 import com.qcloud.cos.COSClient;
29 import com.qcloud.cos.ClientConfig;
30 import com.qcloud.cos.auth.BasicCOSCredentials;
31 import com.qcloud.cos.auth.COSCredentials;
32 import com.qcloud.cos.exception.CosClientException;
33 import com.qcloud.cos.exception.CosServiceException;
34 import com.qcloud.cos.http.HttpMethodName;
35 import com.qcloud.cos.model.*;
36 import com.qcloud.cos.region.Region;
37 import com.qcloud.cos.transfer.TransferManager;
38 import com.qcloud.cos.transfer.TransferManagerConfiguration;
39 import vip.xiaonuo.core.file.FileOperator;
40 import vip.xiaonuo.core.file.common.enums.BucketAuthEnum;
41 import vip.xiaonuo.core.file.modular.tencent.exp.TencentFileServiceException;
42 import vip.xiaonuo.core.file.modular.tencent.prop.TenCosProperties;
43
44 import javax.activation.MimetypesFileTypeMap;
45 import java.io.ByteArrayInputStream;
46 import java.io.InputStream;
47 import java.net.URL;
48 import java.util.Date;
49 import java.util.concurrent.ExecutorService;
50 import java.util.concurrent.Executors;
51
52 /**
53  * 腾讯云内网文件操作
54  *
55  * @author xuyuxiang
56  * @date 2020-05-22-6:51 下午
57  */
58 public class TenFileOperator implements FileOperator {
59
60     private final TenCosProperties tenCosProperties;
61
62     private COSClient cosClient;
63
64     private TransferManager transferManager;
65
66     public TenFileOperator(TenCosProperties tenCosProperties) {
67         this.tenCosProperties = tenCosProperties;
68         initClient();
69     }
70
71     @Override
72     public void initClient() {
73
74         // 1.初始化用户身份信息
75         String secretId = tenCosProperties.getSecretId();
76         String secretKey = tenCosProperties.getSecretKey();
77         COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
78
79         // 2.设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
80         Region region = new Region(tenCosProperties.getRegionId());
81         ClientConfig clientConfig = new ClientConfig(region);
82
83         // 3.生成 cos 客户端。
84         cosClient = new COSClient(cred, clientConfig);
85
86         // 4.线程池大小,建议在客户端与 COS 网络充足(例如使用腾讯云的 CVM,同地域上传 COS)的情况下,设置成16或32即可,可较充分的利用网络资源
87         // 对于使用公网传输且网络带宽质量不高的情况,建议减小该值,避免因网速过慢,造成请求超时。
88         ExecutorService threadPool = Executors.newFixedThreadPool(32);
89
90         // 5.传入一个 threadpool, 若不传入线程池,默认 TransferManager 中会生成一个单线程的线程池。
91         transferManager = new TransferManager(cosClient, threadPool);
92
93         // 6.设置高级接口的分块上传阈值和分块大小为10MB
94         TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
95         transferManagerConfiguration.setMultipartUploadThreshold(10 * 1024 * 1024);
96         transferManagerConfiguration.setMinimumUploadPartSize(10 * 1024 * 1024);
97         transferManager.setConfiguration(transferManagerConfiguration);
98     }
99
100     @Override
101     public void destroyClient() {
102         cosClient.shutdown();
103     }
104
105     @Override
106     public Object getClient() {
107         return cosClient;
108     }
109
110     @Override
111     public boolean doesBucketExist(String bucketName) {
112         try {
113             return cosClient.doesBucketExist(bucketName);
114         } catch (CosServiceException e) {
115             throw new TencentFileServiceException(e);
116         } catch (CosClientException e) {
117             throw new TencentFileServiceException(e);
118         }
119     }
120
121     @Override
122     public void setBucketAcl(String bucketName, BucketAuthEnum bucketAuthEnum) {
123         try {
124             if (bucketAuthEnum.equals(BucketAuthEnum.PRIVATE)) {
125                 cosClient.setBucketAcl(bucketName, CannedAccessControlList.Private);
126             } else if (bucketAuthEnum.equals(BucketAuthEnum.PUBLIC_READ)) {
127                 cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
128             } else if (bucketAuthEnum.equals(BucketAuthEnum.PUBLIC_READ_WRITE)) {
129                 cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicReadWrite);
130             }
131         } catch (CosServiceException e) {
132             throw new TencentFileServiceException(e);
133         } catch (CosClientException e) {
134             throw new TencentFileServiceException(e);
135         }
136     }
137
138     @Override
139     public boolean isExistingFile(String bucketName, String key) {
140         try {
141             cosClient.getObjectMetadata(bucketName, key);
142             return true;
143         } catch (CosServiceException e) {
144             return false;
145         }
146     }
147
148     @Override
149     public void storageFile(String bucketName, String key, byte[] bytes) {
150         // 根据文件名获取contentType
151         String contentType = "application/octet-stream";
152         if (key.contains(".")) {
153             contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(key);
154         }
155
156         // 上传文件
157         ByteArrayInputStream byteArrayInputStream = null;
158         try {
159             byteArrayInputStream = new ByteArrayInputStream(bytes);
160             ObjectMetadata objectMetadata = new ObjectMetadata();
161             objectMetadata.setContentType(contentType);
162             cosClient.putObject(bucketName, key, new ByteArrayInputStream(bytes), objectMetadata);
163         } catch (CosServiceException e) {
164             throw new TencentFileServiceException(e);
165         } catch (CosClientException e) {
166             throw new TencentFileServiceException(e);
167         } finally {
168             IoUtil.close(byteArrayInputStream);
169         }
170
171     }
172
173     @Override
174     public void storageFile(String bucketName, String key, InputStream inputStream) {
175
176         // 根据文件名获取contentType
177         String contentType = "application/octet-stream";
178         if (key.contains(".")) {
179             contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(key);
180         }
181
182         // 上传文件
183         try {
184             ObjectMetadata objectMetadata = new ObjectMetadata();
185             objectMetadata.setContentType(contentType);
186             cosClient.putObject(bucketName, key, inputStream, objectMetadata);
187         } catch (CosServiceException e) {
188             throw new TencentFileServiceException(e);
189         } catch (CosClientException e) {
190             throw new TencentFileServiceException(e);
191         } finally {
192             IoUtil.close(inputStream);
193         }
194     }
195
196     @Override
197     public byte[] getFileBytes(String bucketName, String key) {
198         COSObjectInputStream cosObjectInput = null;
199         try {
200             GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
201             COSObject cosObject = cosClient.getObject(getObjectRequest);
202             cosObjectInput = cosObject.getObjectContent();
203             return IoUtil.readBytes(cosObjectInput);
204         } catch (CosServiceException e) {
205             throw new TencentFileServiceException(e);
206         } catch (CosClientException e) {
207             throw new TencentFileServiceException(e);
208         } finally {
209             IoUtil.close(cosObjectInput);
210         }
211     }
212
213     @Override
214     public void setFileAcl(String bucketName, String key, BucketAuthEnum bucketAuthEnum) {
215         if (bucketAuthEnum.equals(BucketAuthEnum.PRIVATE)) {
216             cosClient.setObjectAcl(bucketName, key, CannedAccessControlList.Private);
217         } else if (bucketAuthEnum.equals(BucketAuthEnum.PUBLIC_READ)) {
218             cosClient.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead);
219         } else if (bucketAuthEnum.equals(BucketAuthEnum.PUBLIC_READ_WRITE)) {
220             cosClient.setObjectAcl(bucketName, key, CannedAccessControlList.PublicReadWrite);
221         }
222     }
223
224     @Override
225     public void copyFile(String originBucketName, String originFileKey, String newBucketName, String newFileKey) {
226         // 初始化拷贝参数
227         Region srcBucketRegion = new Region(tenCosProperties.getRegionId());
228         CopyObjectRequest copyObjectRequest = new CopyObjectRequest(
229                 srcBucketRegion, originBucketName, originFileKey, newBucketName, newFileKey);
230
231         // 拷贝对象
232         try {
233             transferManager.copy(copyObjectRequest, cosClient, null);
234         } catch (CosServiceException e) {
235             throw new TencentFileServiceException(e);
236         } catch (CosClientException e) {
237             throw new TencentFileServiceException(e);
238         }
239     }
240
241     @Override
242     public String getFileAuthUrl(String bucketName, String key, Long timeoutMillis) {
243         GeneratePresignedUrlRequest presignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key, HttpMethodName.GET);
244         Date expirationDate = new Date(System.currentTimeMillis() + timeoutMillis);
245         presignedUrlRequest.setExpiration(expirationDate);
246         URL url = null;
247         try {
248             url = cosClient.generatePresignedUrl(presignedUrlRequest);
249         } catch (CosServiceException e) {
250             throw new TencentFileServiceException(e);
251         } catch (CosClientException e) {
252             throw new TencentFileServiceException(e);
253         }
254         return url.toString();
255     }
256
257     @Override
258     public void deleteFile(String bucketName, String key) {
259         cosClient.deleteObject(bucketName, key);
260     }
261
262 }