AliOssFileTool.java 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. package com.tzld.piaoquan.api.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.aliyun.opensearch.sdk.dependencies.org.apache.commons.codec.binary.Base64;
  6. import com.aliyun.oss.*;
  7. import com.aliyun.oss.common.utils.BinaryUtil;
  8. import com.aliyun.oss.model.*;
  9. import com.aliyuncs.DefaultAcsClient;
  10. import com.aliyuncs.exceptions.ServerException;
  11. import com.aliyuncs.http.MethodType;
  12. import com.aliyuncs.http.ProtocolType;
  13. import com.aliyuncs.mts.model.v20140618.SubmitJobsRequest;
  14. import com.aliyuncs.mts.model.v20140618.SubmitJobsResponse;
  15. import com.aliyuncs.mts.model.v20140618.SubmitMediaInfoJobRequest;
  16. import com.aliyuncs.mts.model.v20140618.SubmitMediaInfoJobResponse;
  17. import com.aliyuncs.mts.model.v20140618.SubmitMediaInfoJobResponse.MediaInfoJob.Properties;
  18. import com.aliyuncs.profile.DefaultProfile;
  19. import com.aliyuncs.profile.IClientProfile;
  20. import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
  21. import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
  22. import com.stuuudy.commons.external.filestorage.alibaba.OSSFileDO;
  23. import com.stuuudy.commons.external.filestorage.enums.*;
  24. import com.stuuudy.commons.util.BlankUtil;
  25. import com.stuuudy.commons.util.CompressImage;
  26. import com.stuuudy.commons.util.MD5.Md5Util;
  27. import com.stuuudy.commons.util.exception.CommonsException;
  28. import com.stuuudy.commons.util.exception.EnumErrorException;
  29. import com.tzld.piaoquan.api.common.enums.EnumUploadFileType;
  30. import com.tzld.piaoquan.api.config.AliOssConfig;
  31. import com.tzld.piaoquan.api.model.vo.SignatureVO;
  32. import com.tzld.piaoquan.api.model.vo.StsTokenVO;
  33. import com.tzld.piaoquan.growth.common.utils.DateUtils;
  34. import com.tzld.piaoquan.growth.common.utils.RandomUtil;
  35. import org.apache.commons.collections4.CollectionUtils;
  36. import org.apache.commons.io.IOUtils;
  37. import org.apache.commons.lang3.StringUtils;
  38. import org.apache.log4j.Logger;
  39. import org.springframework.stereotype.Component;
  40. import javax.crypto.Mac;
  41. import javax.crypto.SecretKey;
  42. import javax.crypto.spec.SecretKeySpec;
  43. import javax.imageio.ImageIO;
  44. import javax.xml.crypto.dsig.SignatureMethod;
  45. import java.awt.image.BufferedImage;
  46. import java.io.*;
  47. import java.net.URL;
  48. import java.net.URLEncoder;
  49. import java.security.DigestInputStream;
  50. import java.security.InvalidKeyException;
  51. import java.security.MessageDigest;
  52. import java.security.NoSuchAlgorithmException;
  53. import java.util.*;
  54. /**
  55. * (阿里对象存储工具类)<BR>
  56. * AliOssFileTool<BR>
  57. * 创建人:陈海 <BR>
  58. * 时间:2016年7月18日-下午12:47:52 <BR>
  59. *
  60. * @version 1.0.0
  61. */
  62. @Component
  63. public class AliOssFileTool extends AliOssConfig {
  64. private static Logger logger = Logger.getLogger(AliOssFileTool.class);
  65. private static final String ENCODE_TYPE = "UTF-8";
  66. private static final String ALGORITHM = "HmacSHA1";
  67. private static final String HTTP_METHOD = "GET";
  68. private static final String SEPARATOR = "&";
  69. private static final String EQUAL = "=";
  70. public static String saveInPublicWithPress(InputStream inputStream, EnumPublicBuckets bucket, String key, EnumFileType type,
  71. EnumFileSuffix fileSuffix) throws OSSException, ClientException {
  72. inputStream = compressImg(inputStream, fileSuffix, type);
  73. return saveInPublicNoPress(inputStream, bucket, key, type);
  74. }
  75. public static String saveInPublicReturnHost(InputStream inputStream, EnumPublicBuckets bucket, String fullKey,
  76. EnumFileType type) {
  77. String path = saveInPublic(inputStream, bucket, fullKey, type);
  78. // 保存路径
  79. return CdnUtil.getCdnUrlHost(type) + path;
  80. }
  81. public static String saveInPublic(InputStream inputStream, EnumPublicBuckets bucket, String fullKey, EnumFileType type) {
  82. String bucketName = getBucket(bucket.getBucketName());
  83. if (EnumFileType.VOICE.equals(type)) {
  84. ObjectMetadata om = new ObjectMetadata();
  85. om.setContentType("audio/mpeg");
  86. getOssClient().putObject(bucketName, fullKey, inputStream, om);
  87. } else {
  88. getOssClient().putObject(bucketName, fullKey, inputStream);
  89. }
  90. return fullKey;
  91. }
  92. public static String moveFile(EnumPublicBuckets sourceBucket, String sourceKey, EnumPublicBuckets targetBucket, String targetKey) {
  93. getOssClient().copyObject(getBucket(sourceBucket.getBucketName()), sourceKey,
  94. getBucket(targetBucket.getBucketName()), targetKey);
  95. if (!StringUtils.equals(sourceKey, targetKey)) {
  96. getOssClient().deleteObject(getBucket(sourceBucket.getBucketName()), sourceKey);
  97. }
  98. return targetKey;
  99. }
  100. public static void deleteFile(EnumPublicBuckets bucket, String key) {
  101. getOssClient().deleteObject(getBucket(bucket.getBucketName()), key);
  102. }
  103. public static String saveInPublicNoPress(InputStream inputStream, EnumPublicBuckets bucket, String key,
  104. EnumFileType type) throws OSSException, ClientException {
  105. String fullKey = getProjectName() + "/" + type.getLocation() + key;
  106. saveInPublic(inputStream, bucket, fullKey, type);
  107. return fullKey;
  108. }
  109. /**
  110. * (网络资源上传) 方法名saveURLInPublicNoPress
  111. *
  112. * @param url 资源地址
  113. * @param key
  114. * @param type
  115. * @param fileSuffix
  116. * @return
  117. * @throws OSSException
  118. * @throws ClientException
  119. * @throws IOException String
  120. * @throws @version 1.0
  121. * @author 创建人:何振斌
  122. * @time 创建日期:2018年3月12日 下午7:10:00
  123. */
  124. public static String saveURLInPublicNoPress(String url, String bucketName, String key, EnumFileType type,
  125. EnumFileSuffix fileSuffix) throws OSSException, ClientException, IOException {
  126. String fullKey = getProjectName() + "/" + type.getLocation() + key;
  127. InputStream inputStream = null;
  128. if (!BlankUtil.isBlank(url)) {
  129. inputStream = new URL(url).openStream();
  130. }
  131. if (EnumFileType.VOICE.equals(type)) {
  132. ObjectMetadata om = new ObjectMetadata();
  133. om.setContentType("audio/mpeg");
  134. getOssClient().putObject(bucketName, fullKey, inputStream, om);
  135. } else {
  136. getOssClient().putObject(bucketName, fullKey, inputStream);
  137. }
  138. return getProjectName() + "/" + type.getLocation() + key;
  139. }
  140. /**
  141. * (根据名称和类型保存文件,返回是否成功)<BR>
  142. * 方法名:saveWiteKeyAndType<BR>
  143. * 创建人:陈海 <BR>
  144. * 时间:2016年7月18日-下午1:02:10 <BR>
  145. *
  146. * @param inputStream 文件流
  147. * @param bucket 空间名称
  148. * @param key 文件保存在服务器上的另存名
  149. * @param type 枚举文件类型,声音或图片等
  150. * @return boolean<BR>
  151. * @throws IOException
  152. * @throws ClientException
  153. * @throws OSSException
  154. * @throws <BR>
  155. * @since 1.0.0
  156. */
  157. public static boolean saveInPrivate(InputStream inputStream, EnumPrivateBuckets bucket, String key,
  158. EnumFileType type, EnumFileSuffix suffix) throws OSSException, ClientException, IOException {
  159. inputStream = compressImg(inputStream, suffix, type);
  160. String bucketName = getBucket(bucket.getBucketName());
  161. String fullKey = getProjectName() + "/" + type.getLocation() + key;
  162. getOssClient().putObject(bucketName, fullKey, inputStream);
  163. return true;
  164. }
  165. /**
  166. * (获取前缀为prefix的全部文件)<BR>
  167. * 方法名:listFileInFolder<BR>
  168. * 创建人:陈海 <BR>
  169. * 时间:2017年1月20日-下午4:59:25 <BR>
  170. *
  171. * @param bucket
  172. * @param prefix
  173. * @return List<OSSObjectSummary><BR>
  174. * @throws <BR>
  175. * @since 1.0.0
  176. */
  177. public static List<OSSObjectSummary> listFileInFolder(EnumPublicBuckets bucket, String prefix) {
  178. final int maxKeys = 200;
  179. String nextMarker = null;
  180. ObjectListing objectListing;
  181. List<OSSObjectSummary> sums = new ArrayList<OSSObjectSummary>();
  182. // 递归列出fun目录下的所有文件
  183. do {
  184. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(getBucket(bucket.getBucketName()));
  185. listObjectsRequest.setPrefix(prefix);
  186. listObjectsRequest.withMarker(nextMarker).withMaxKeys(maxKeys);
  187. objectListing = getOssClient().listObjects(listObjectsRequest);
  188. List<OSSObjectSummary> temp = objectListing.getObjectSummaries();
  189. if (temp != null) {
  190. sums.addAll(temp);
  191. }
  192. nextMarker = objectListing.getNextMarker();
  193. } while (objectListing.isTruncated());
  194. return sums;
  195. }
  196. /**
  197. * (判断是否存在文件)<BR>
  198. * 方法名:isExist<BR>
  199. * 创建人:陈海 <BR>
  200. * 时间:2016年11月21日-下午3:54:36 <BR>
  201. *
  202. * @param bucket
  203. * @param key
  204. * @param type
  205. * @return boolean<BR>
  206. * @throws <BR>
  207. * @since 1.0.0
  208. */
  209. public static boolean isExist(EnumPrivateBuckets bucket, String key, EnumFileType type) {
  210. String fullKey = getProjectName() + "/" + type.getLocation() + key;
  211. return getOssClient().doesObjectExist(getBucket(bucket.getBucketName()), fullKey);
  212. }
  213. public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
  214. public static final String STS_API_VERSION = "2015-04-01";
  215. public static AssumeRoleResponse getTempUserToken(long durationSeconds, Integer uid)
  216. throws com.aliyuncs.exceptions.ClientException {
  217. // 只有 RAM用户(子账号)才能调用 AssumeRole 接口
  218. // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
  219. // 请首先在RAM控制台创建一个RAM用户,并为这个用户创建AccessKeys
  220. String accessKeyId = "LTAIQLkVvDFXRO7j";
  221. String accessKeySecret = "aOnxO0xyoa0lDmTxTI1cNmVLNotF15";
  222. // RoleArn 需要在 RAM 控制台上获取
  223. String roleArn = "acs:ram::1894469520484605:role/aliyunosstokengeneratorrole";
  224. String policy = JSONObject.toJSONString(AliOssFileTool.getPolicyDetail());
  225. // RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
  226. // 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
  227. // 具体规则请参考API文档中的格式要求
  228. String roleSessionName = "uid_" + uid;
  229. // 此处必须为 HTTPS
  230. ProtocolType protocolType = ProtocolType.HTTPS;
  231. try {
  232. final AssumeRoleResponse stsResponse = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName,
  233. policy, protocolType, durationSeconds);
  234. return stsResponse;
  235. /*
  236. * Map<String, String> respMap = new LinkedHashMap<String, String>();
  237. * respMap.put("status", "200"); respMap.put("AccessKeyId",
  238. * stsResponse.getCredentials().getAccessKeyId());
  239. * respMap.put("AccessKeySecret",
  240. * stsResponse.getCredentials().getAccessKeySecret());
  241. * respMap.put("SecurityToken",
  242. * stsResponse.getCredentials().getSecurityToken()); respMap.put("Expiration",
  243. * stsResponse.getCredentials().getExpiration());
  244. */
  245. } catch (ClientException e) {
  246. throw e;
  247. }
  248. }
  249. protected static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn,
  250. String roleSessionName, String policy, ProtocolType protocolType, long durationSeconds)
  251. throws com.aliyuncs.exceptions.ClientException {
  252. try {
  253. // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
  254. IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
  255. DefaultAcsClient client = new DefaultAcsClient(profile);
  256. // 创建一个 AssumeRoleRequest 并设置请求参数
  257. final AssumeRoleRequest request = new AssumeRoleRequest();
  258. request.setVersion(STS_API_VERSION);
  259. request.setMethod(MethodType.POST);
  260. request.setProtocol(protocolType);
  261. request.setRoleArn(roleArn);
  262. request.setRoleSessionName(roleSessionName);
  263. request.setPolicy(policy);
  264. request.setDurationSeconds(durationSeconds);
  265. // 发起请求,并得到response
  266. final AssumeRoleResponse response = client.getAcsResponse(request);
  267. return response;
  268. } catch (com.aliyuncs.exceptions.ClientException e) {
  269. throw e;
  270. }
  271. }
  272. /**
  273. * (判断是否存在文件)<BR>
  274. * 方法名:isExist<BR>
  275. * 创建人:陈海 <BR>
  276. * 时间:2016年11月21日-下午3:54:36 <BR>
  277. *
  278. * @param bucket
  279. * @param key
  280. * @param type
  281. * @return boolean<BR>
  282. * @throws <BR>
  283. * @since 1.0.0
  284. */
  285. @Deprecated
  286. public boolean isExist(EnumPublicBuckets bucket, String key, EnumFileType type) {
  287. String fullKey = getProjectName() + "/" + type.getLocation() + key;
  288. return getOssClient().doesObjectExist(getBucket(bucket.getBucketName()), fullKey);
  289. }
  290. /**
  291. * (用bucket名称和完整key 判断文件是否存在)<BR>
  292. * 方法名:isExist<BR>
  293. * 创建人:陈海 <BR>
  294. * 时间:2017年5月12日-下午6:38:49 <BR>
  295. *
  296. * @param bucket
  297. * @param fullKey
  298. * @return boolean<BR>
  299. * @throws <BR>
  300. * @since 1.0.0
  301. */
  302. public static boolean isExist(String bucket, String fullKey) {
  303. return getOssClient().doesObjectExist(bucket, fullKey);
  304. }
  305. /**
  306. * 文件是否存在 内网
  307. *
  308. * @param bucket
  309. * @param fullKey
  310. * @return
  311. */
  312. public static boolean isExistOfInternal(String bucket, String fullKey) {
  313. return getInternalOssClient().doesObjectExist(bucket, fullKey);
  314. }
  315. /**
  316. * (删除oss文件)<BR>
  317. * 方法名:delFile<BR>
  318. * 创建人:陈海 <BR>
  319. * 时间:2016年7月20日-上午10:44:52 <BR>
  320. *
  321. * @param bucket 存储空间名称
  322. * @param key 文件保存在服务器上的另存名
  323. * @param type 枚举文件类型,声音或图片等
  324. * @return boolean<BR>
  325. * @throws <BR>
  326. * @since 1.0.0
  327. */
  328. public static boolean delFile(EnumAllBuckets bucket, String key, EnumFileType type) {
  329. getOssClient().deleteObject(getBucket(bucket.getBucketName()),
  330. getProjectName() + "/" + type.getLocation() + key);
  331. return true;
  332. }
  333. public static boolean deleteObject(String bucketName, String objectKey) {
  334. getInternalOssClient().deleteObject(bucketName, objectKey);
  335. return true;
  336. }
  337. public static boolean deleteObjects(String bucketName, List<String> objectKeys) {
  338. if (objectKeys == null || objectKeys.size() == 0) {
  339. return false;
  340. }
  341. DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);
  342. deleteObjectsRequest.setKeys(objectKeys);
  343. deleteObjectsRequest.setQuiet(true);
  344. getInternalOssClient().deleteObjects(deleteObjectsRequest);
  345. return true;
  346. }
  347. /**
  348. * (获取经处理的图片签名url)<BR>
  349. * 方法名:getPicUrlWithSign<BR>
  350. * 创建人:陈海 <BR>
  351. * 时间:2016年7月18日-下午1:07:23 <BR>
  352. *
  353. * @param bucket 空间名称
  354. * @param key 文件保存在服务器上的名称
  355. * @param type 枚举文件类型,声音或图片等
  356. * @return String<BR>
  357. * @throws <BR>
  358. * @since 1.0.0
  359. */
  360. public static String getPicUrl(EnumPrivateBuckets bucket, String key, EnumFileType type, Long expiresSec) {
  361. if (expiresSec == null) {
  362. expiresSec = getExpiration();
  363. }
  364. Date expires = new Date(new Date().getTime() + getExpiration() * 1000);
  365. String picUrl = getPriClient().generatePresignedUrl(getBucket(bucket.getBucketName()),
  366. getProjectName() + "/" + type.getLocation() + key, expires).toString();
  367. return picUrl;
  368. }
  369. /**
  370. * (获取文件对象的签名url)<BR>
  371. * 方法名:getUrlWithSign<BR>
  372. * 创建人:陈海 <BR>
  373. * 时间:2016年7月18日-下午1:05:50 <BR>
  374. *
  375. * @param bucket 空间名称
  376. * @param key 文件保存在服务器上的名称
  377. * @param type 枚举文件类型,声音或图片等
  378. * @return String<BR>
  379. * @throws <BR>
  380. * @since 1.0.0
  381. */
  382. public static String getUrl(EnumPrivateBuckets bucket, String key, EnumFileType type, Long expiresSec) {
  383. if (expiresSec == null) {
  384. expiresSec = getExpiration();
  385. }
  386. Date expires = new Date(new Date().getTime() + expiresSec * 1000);
  387. String url = "";
  388. if (type.equals(EnumFileType.VIDEO)) {
  389. url = getVideoClient().generatePresignedUrl(getBucket(bucket.getBucketName()),
  390. getProjectName() + "/" + type.getLocation() + key, expires).toString();
  391. } else {
  392. url = getPriClient().generatePresignedUrl(getBucket(bucket.getBucketName()),
  393. getProjectName() + "/" + type.getLocation() + key, expires).toString();
  394. }
  395. return url;
  396. }
  397. public static String getUrlWithOssEndPoint(EnumPrivateBuckets bucket, String key, EnumFileType type,
  398. Long expiresSec) {
  399. if (expiresSec == null) {
  400. expiresSec = getExpiration();
  401. }
  402. Date expires = new Date(new Date().getTime() + expiresSec * 1000);
  403. return getOssClient().generatePresignedUrl(getBucket(bucket.getBucketName()),
  404. getProjectName() + "/" + type.getLocation() + key, expires).toString();
  405. }
  406. /**
  407. * (获取object)<BR>
  408. * 方法名:getObject<BR>
  409. * 创建人:陈海 <BR>
  410. * 时间:2016年12月28日-上午10:55:43 <BR>
  411. *
  412. * @param bucket
  413. * @param key
  414. * @param type
  415. * @return OSSObject<BR>
  416. * @throws <BR>
  417. * @since 1.0.0
  418. */
  419. public static OSSObject getObject(EnumPrivateBuckets bucket, String key, EnumFileType type) {
  420. OSSObject ossObject = getOssClient().getObject(getBucket(bucket.getBucketName()),
  421. getProjectName() + "/" + type.getLocation() + key);
  422. return ossObject;
  423. }
  424. public static OSSObject getPubObject(EnumAllBuckets bucket, String key, EnumFileType type) {
  425. OSSObject ossObject = getOssClient().getObject(getBucket(bucket.getBucketName()),
  426. getProjectName() + "/" + type.getLocation() + key);
  427. return ossObject;
  428. }
  429. public static OSSObject getPubObject(String bucketName, String fullKey) {
  430. OSSObject ossObject = getOssClient().getObject(bucketName, fullKey);
  431. return ossObject;
  432. }
  433. public static OSSObject getInternalPubObject(String bucketName, String fullKey) {
  434. OSSObject ossObject = getInternalOssClient().getObject(bucketName, fullKey);
  435. return ossObject;
  436. }
  437. public static ObjectMetadata getPubObjectMedeta(EnumAllBuckets bucket, String key, EnumFileType type) {
  438. ObjectMetadata ossObjectMeta = getOssClient().getObjectMetadata(getBucket(bucket.getBucketName()),
  439. getProjectName() + "/" + type.getLocation() + key);
  440. return ossObjectMeta;
  441. }
  442. public static String calcFileMD5(String bucketName, String objectKey) {
  443. try {
  444. OSSObject ossObj = getOssClient().getObject(bucketName, objectKey);
  445. MessageDigest md = MessageDigest.getInstance("MD5");
  446. try (DigestInputStream digestInputStream = new DigestInputStream(ossObj.getObjectContent(), md)) {
  447. // 读取数据流并更新 MD5
  448. byte[] buffer = new byte[8192];
  449. while (digestInputStream.read(buffer) != -1) {
  450. // DigestInputStream 会自动更新 MessageDigest
  451. }
  452. } catch (Exception e) {
  453. logger.info("读取oss文件异常: ", e);
  454. return "";
  455. }
  456. // 获取最终的 MD5 值
  457. byte[] md5Bytes = md.digest();
  458. // 转换为十六进制字符串
  459. StringBuilder sb = new StringBuilder();
  460. for (byte b : md5Bytes) {
  461. sb.append(String.format("%02x", b));
  462. }
  463. String md5 = sb.toString();
  464. logger.info(String.format("buketName: %s, objectKey: %s, MD5: %s", bucketName, objectKey, md5));
  465. return md5;
  466. } catch (Exception e) {
  467. logger.error("计算文件MD5异常: ", e);
  468. }
  469. return "";
  470. }
  471. /**
  472. * (重命名文件,实现是先拷贝文件,再删掉旧的文件)<BR>
  473. * 方法名:renameFile<BR>
  474. * 创建人:陈海 <BR>
  475. * 时间:2016年8月1日-下午4:03:09 <BR>
  476. *
  477. * @param srcBucket
  478. * @param srckey
  479. * @param destkey
  480. * @return boolean<BR>
  481. * @throws <BR>
  482. * @since 1.0.0
  483. */
  484. @Deprecated
  485. public boolean renameFile(EnumAllBuckets srcBucket, String srckey, String destkey, EnumFileType srcType,
  486. EnumFileType destType) {
  487. // 拷贝Object
  488. getOssClient().copyObject(getBucket(srcBucket.getBucketName()),
  489. getProjectName() + "/" + srcType.getLocation() + srckey, getBucket(srcBucket.getBucketName()),
  490. getProjectName() + "/" + destType.getLocation() + destkey);
  491. delFile(srcBucket, srckey, srcType);
  492. return true;
  493. }
  494. /**
  495. * (将oss srckey 命名为 destkey)<BR>
  496. * 方法名:renameFileWithFullKey<BR>
  497. * 创建人:陈海 <BR>
  498. * 时间:2017年9月16日-下午5:24:39 <BR>
  499. *
  500. * @param srcBucket
  501. * @param srckey
  502. * @param destkey
  503. * @return boolean<BR>
  504. * @throws <BR>
  505. * @since 1.0.0
  506. */
  507. public static boolean renameFileWithFullKey(EnumAllBuckets srcBucket, String srckey, String destkey) {
  508. // 拷贝Object
  509. getOssClient().copyObject(getBucket(srcBucket.getBucketName()), srckey, getBucket(srcBucket.getBucketName()),
  510. destkey);
  511. getOssClient().deleteObject(getBucket(srcBucket.getBucketName()), srckey);
  512. return true;
  513. }
  514. public static boolean renameFileWithFullKeyFromInternal(EnumAllBuckets srcBucket, String srckey, String destkey, long size) {
  515. // 拷贝Object
  516. if (size < 1024 * 1024 * 1024) {
  517. getInternalOssClient().copyObject(getBucket(srcBucket.getBucketName()), srckey,
  518. getBucket(srcBucket.getBucketName()), destkey);
  519. } else {
  520. multipartCopyObjectFromInternal(getBucket(srcBucket.getBucketName()), srckey,
  521. getBucket(srcBucket.getBucketName()), destkey);
  522. }
  523. getInternalOssClient().deleteObject(getBucket(srcBucket.getBucketName()), srckey);
  524. return true;
  525. }
  526. // 分片拷贝object,大于1G的文件需要分片拷贝
  527. public static void multipartCopyObjectFromInternal(String sourceBucketName, String sourceObjectName,
  528. String destinationBucketName, String destinationObjectName) {
  529. OSSClient ossClient = getInternalOssClient();
  530. ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceObjectName);
  531. // 获取被拷贝文件的大小。
  532. long contentLength = objectMetadata.getContentLength();
  533. // 设置分片大小为10MB。
  534. long partSize = 1024 * 1024 * 10;
  535. // 计算分片总数。
  536. int partCount = (int) (contentLength / partSize);
  537. if (contentLength % partSize != 0) {
  538. partCount++;
  539. }
  540. logger.info("oss 分片拷贝开始,sourceObjectName:" + sourceObjectName + ",size:" + contentLength + ",partCount:" + partCount);
  541. // 初始化拷贝任务。可以通过InitiateMultipartUploadRequest指定目标文件元信息。
  542. InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(
  543. destinationBucketName, destinationObjectName);
  544. InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient
  545. .initiateMultipartUpload(initiateMultipartUploadRequest);
  546. String uploadId = initiateMultipartUploadResult.getUploadId();
  547. // 分片拷贝。
  548. List<PartETag> partETags = new ArrayList<PartETag>();
  549. for (int i = 0; i < partCount; i++) {
  550. // 计算每个分片的大小。
  551. long skipBytes = partSize * i;
  552. long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes;
  553. // 创建UploadPartCopyRequest。可以通过UploadPartCopyRequest指定限定条件。
  554. UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucketName, sourceObjectName,
  555. destinationBucketName, destinationObjectName);
  556. uploadPartCopyRequest.setUploadId(uploadId);
  557. uploadPartCopyRequest.setPartSize(size);
  558. uploadPartCopyRequest.setBeginIndex(skipBytes);
  559. uploadPartCopyRequest.setPartNumber(i + 1);
  560. UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);
  561. // 将返回的分片ETag保存到partETags中。
  562. partETags.add(uploadPartCopyResult.getPartETag());
  563. }
  564. // 提交分片拷贝任务。
  565. CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
  566. destinationBucketName, destinationObjectName, uploadId, partETags);
  567. ossClient.completeMultipartUpload(completeMultipartUploadRequest);
  568. logger.info("oss 分片拷贝结束,sourceObjectName:" + sourceObjectName + ",size:" + contentLength + ",partCount:" + partCount);
  569. }
  570. public static void copyObject(String srcBucketName, String srcObjectKey,
  571. String destBucketName, String destObjectKey) {
  572. getOssClient().copyObject(srcBucketName, srcObjectKey, destBucketName, destObjectKey);
  573. }
  574. public static void copyObjectFromInternal(String srcBucketName, String srcObjectKey,
  575. String destBucketName, String destObjectKey) {
  576. getInternalOssClient().copyObject(srcBucketName, srcObjectKey, destBucketName, destObjectKey);
  577. }
  578. private static InputStream compressImg(InputStream stream, EnumFileSuffix suffix, EnumFileType fileType) {
  579. if (!getNeedPress()) {
  580. return stream;
  581. }
  582. if (suffix == EnumFileSuffix.JPG || suffix == EnumFileSuffix.PNG || suffix == EnumFileSuffix.JPEG
  583. || suffix == EnumFileSuffix.BMP) {
  584. try {
  585. byte[] file = CompressImage.compress(stream, 1080);
  586. if (file != null) {
  587. stream = new ByteArrayInputStream(file);
  588. } else {
  589. logger.warn("图片上传有误");
  590. return null;
  591. }
  592. } catch (Exception e) {
  593. logger.error("图片压缩失败", e);
  594. if (null != stream) {
  595. try {
  596. stream.close();
  597. } catch (IOException e1) {
  598. }
  599. }
  600. throw new CommonsException(EnumErrorException.PIC_FORMAT_ERROR);
  601. }
  602. }
  603. return stream;
  604. }
  605. public static String submitPubTranscodeJob(EnumPublicBuckets inputBucket, EnumAllBuckets outputBucket,
  606. String fullKey, String outPutKey, String templateId) {
  607. OSSFileDO inputFile = new OSSFileDO(OSS_REGION, getBucket(EnumAllBuckets.PUBVIDEOBUCKET.getBucketName()),
  608. fullKey);
  609. JSONArray outputs = new JSONArray();
  610. JSONObject outPutConfig = new JSONObject();
  611. outPutConfig.put("OutputObject", outPutKey);
  612. outPutConfig.put("TemplateId", templateId);
  613. outputs.add(outPutConfig);
  614. SubmitJobsRequest request = new SubmitJobsRequest();
  615. request.setInput(inputFile.toJsonString());
  616. request.setOutputs(outputs.toJSONString());
  617. request.setPipelineId(PIPELINEID);
  618. request.setOutputBucket(getBucket(outputBucket.getBucketName()));
  619. request.setOutputLocation(OSS_REGION);
  620. Integer outputJobCount = 1;
  621. SubmitJobsResponse response = null;
  622. try {
  623. response = getDefaultAcsClient().getAcsResponse(request);
  624. if (response.getJobResultList().size() != outputJobCount) {
  625. throw new RuntimeException("SubmitJobsRequest Size failed");
  626. }
  627. return response.getJobResultList().get(0).getJob().getJobId();
  628. } catch (ServerException e) {
  629. logger.error("submitTranscodeJob Server failed", e);
  630. throw new CommonsException(EnumErrorException.TRANS_CODE_SERVER_ERROR);
  631. } catch (com.aliyuncs.exceptions.ClientException e) {
  632. logger.error("submitTranscodeJob Client failed", e);
  633. throw new CommonsException(EnumErrorException.TRANS_CODE_CLIENT_ERROR);
  634. }
  635. }
  636. public static String getPubPicAverageColor(EnumAllBuckets bucket, String key) {
  637. String style = "image/average-hue";
  638. try {
  639. GetObjectRequest request = new GetObjectRequest(getBucket(bucket.getBucketName()), key);
  640. request.setProcess(style);
  641. OSSObject obj = getOssClient().getObject(request);
  642. if (obj != null) {
  643. String a = IOUtils.toString(obj.getObjectContent());
  644. JSONObject jo = (JSONObject) JSONObject.parse(a);
  645. String rgb = jo.getString("RGB");
  646. if (rgb != null) {
  647. rgb = rgb.replace("0x", "#");
  648. }
  649. return rgb;
  650. }
  651. } catch (Exception e) {
  652. throw new CommonsException(EnumErrorException.TRANS_CODE_CLIENT_ERROR);
  653. }
  654. return null;
  655. }
  656. public static Properties getPubObjMediaInfoData(String bucketName, String fullKey) {
  657. DefaultAcsClient client = getDefaultAcsClient();
  658. SubmitMediaInfoJobRequest request = new SubmitMediaInfoJobRequest();
  659. request.setReadTimeout(Integer.MAX_VALUE);
  660. SubmitMediaInfoJobResponse response = new SubmitMediaInfoJobResponse();
  661. JSONObject json = new JSONObject();
  662. json.put("Location", "oss-cn-hangzhou");
  663. json.put("Bucket", bucketName);
  664. json.put("Object", fullKey);
  665. request.setInput(json.toJSONString());
  666. try {
  667. response = client.getAcsResponse(request);
  668. // String width = response.getMediaInfoJob().getProperties().getWidth();
  669. // String height = response.getMediaInfoJob().getProperties().getHeight();
  670. return response.getMediaInfoJob().getProperties();
  671. } catch (Exception e) {
  672. throw new CommonsException(EnumErrorException.TRANS_CODE_CLIENT_ERROR, e);
  673. }
  674. }
  675. public static SignatureVO getUploadPolicy(Integer fileType) throws Exception {
  676. // 后台随机生成唯一文件名
  677. String env = PropertiesUtils.getProjectEnv();
  678. if (StringUtils.isEmpty(env)) {
  679. env = "qa";
  680. }
  681. String fileName = RandomUtil.generate18String();
  682. String contentType = "";
  683. if (EnumUploadFileType.VIDEO.getIntType().equals(fileType)) {
  684. fileName = "/video/" + env + "/" + DateUtils.dateToStringyyyyMMdd(new Date()) + "/" + fileName;
  685. } else if (EnumUploadFileType.VOICE.getIntType().equals(fileType)) {
  686. fileName = "/voice/" + env + "/" + DateUtils.dateToStringyyyyMMdd(new Date()) + "/" + fileName;
  687. } else {
  688. fileName = "/pic/" + env + "/" + DateUtils.dateToStringyyyyMMdd(new Date()) + "/" + fileName;
  689. }
  690. long expireTime = 60 * 60 * 4;
  691. long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
  692. Date expiration = new Date(expireEndTime);
  693. PolicyConditions policyConds = new PolicyConditions();
  694. //4.95G 上限是5个G
  695. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 5261334938l);
  696. policyConds.addConditionItem(MatchMode.Exact, PolicyConditions.COND_KEY,
  697. AliOssConfig.getProjectName() + fileName);
  698. if (!StringUtils.isEmpty(contentType)) {
  699. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_TYPE, contentType);
  700. }
  701. String postPolicy = AliOssConfig.getOssClient().generatePostPolicy(expiration, policyConds);
  702. byte[] binaryData = postPolicy.getBytes("utf-8");
  703. String encodedPolicy = BinaryUtil.toBase64String(binaryData);
  704. String postSignature = AliOssConfig.getOssClient().calculatePostSignature(postPolicy);
  705. SignatureVO signatureVO = new SignatureVO();
  706. signatureVO.setAccessId(AliOssConfig.getAccessKeyId());
  707. signatureVO.setPolicy(encodedPolicy);
  708. signatureVO.setSignature(postSignature);
  709. signatureVO.setFileName(AliOssConfig.getProjectName() + fileName);
  710. signatureVO.setHost(AliOssConfig.getUploadDomain());
  711. signatureVO.setExpire(String.valueOf(expireEndTime / 1000));
  712. return signatureVO;
  713. }
  714. public static String getSignaturedUrl(String fileName, Boolean isPrivate) {
  715. if (StringUtils.isBlank(fileName)) {
  716. return fileName;
  717. }
  718. if (StringUtils.startsWith(fileName, "https")) {
  719. return fileName;
  720. }
  721. String host = AliOssConfig.getVideoDomain();
  722. fileName = host + fileName;
  723. return fileName;
  724. }
  725. public static String getSignaturedInternalUrl(String fileName, Boolean isPrivate) throws Exception {
  726. if (StringUtils.isBlank(fileName)) {
  727. return fileName;
  728. }
  729. if (StringUtils.startsWith(fileName, "https")) {
  730. return fileName;
  731. }
  732. String bucket = getBucket(isPrivate);
  733. String host = "http://" + bucket + "." + AliOssConfig.getInternalEndPoint();
  734. fileName = host + "/" + fileName;
  735. return fileName;
  736. }
  737. public static String saveVideoCoverImagFromInternal(File file, Integer fileType, Boolean isPrivate, Long videoId)
  738. throws Exception {
  739. Date begin = new Date();
  740. logger.info(String.format("开始往阿里云OSS上传封面图片,当前时间为:%s", begin.getTime()));
  741. String bucketName = getBucket(isPrivate);
  742. String fullKey = getVideoCoverImagPath(fileType, isPrivate, videoId.toString(), null);
  743. AliOssConfig.getInternalOssClient().putObject(bucketName, fullKey, file);
  744. Date end = new Date();
  745. logger.info(String.format("阿里云OSS上传封面图片完成,总耗时为 %s 毫秒。图片地址为:%s, 正在执行下一步。。", end.getTime() - begin.getTime(),
  746. fullKey));
  747. return fullKey;
  748. }
  749. public static String saveVideoCoverImagFromInternal(InputStream input, Integer fileType, Boolean isPrivate,
  750. String filePrex, String dic) throws Exception {
  751. Date begin = new Date();
  752. logger.info(String.format("开始往阿里云OSS上传图片,当前时间为:%s", begin.getTime()));
  753. String bucketName = getBucket(isPrivate);
  754. String fullKey = getVideoCoverImagPath(fileType, isPrivate, filePrex, dic);
  755. // AliOssConfig.getOssClient().putObject(bucketName, fullKey, file);
  756. AliOssConfig.getInternalOssClient().putObject(bucketName, fullKey, input);
  757. Date end = new Date();
  758. logger.info(
  759. String.format("阿里云OSS上传图片完成,总耗时为 %s 毫秒。图片地址为:%s, 正在执行下一步。。", end.getTime() - begin.getTime(), fullKey));
  760. return fullKey;
  761. }
  762. public static String getVideoCoverImagPath(Integer fileType, Boolean isPrivate, String filePrex, String dic)
  763. throws Exception {
  764. String fileName = UUID.randomUUID().toString().replaceAll("-", "") + Calendar.getInstance().getTimeInMillis()
  765. + "_" + filePrex;
  766. if (StringUtils.isNotBlank(dic)) {
  767. fileName = (dic + "/" + fileName);
  768. }
  769. if (EnumUploadFileType.VIDEO.getIntType().equals(fileType)) {
  770. fileName = "/video/" + fileName;
  771. } else if (EnumUploadFileType.VOICE.getIntType().equals(fileType)) {
  772. fileName = "/voice/" + fileName;
  773. } else {
  774. fileName = "/pic/" + fileName;
  775. }
  776. String fullKey = AliOssConfig.getProjectName() + fileName;
  777. return fullKey;
  778. }
  779. public static String getBucket(boolean isPrivate) {
  780. if (isPrivate) {
  781. return AliOssFileTool.getBucket(EnumAllBuckets.PRIVIDEOBUCKET.getBucketName());
  782. } else {
  783. return AliOssFileTool.getBucket(EnumAllBuckets.PUBVIDEOBUCKET.getBucketName());
  784. }
  785. }
  786. public static ObjectMetadata getObjectMetadata(String fileName) throws Exception {
  787. // Endpoint以杭州为例,其它Region请按实际情况填写。
  788. // 创建OSSClient实例。
  789. OSSClient ossClient = new OSSClient(AliOssConfig.getInternalEndPoint(), AliOssConfig.getAccessKeyId(),
  790. AliOssConfig.getAccessKeySecret());
  791. // // 获取文件的部分元信息。
  792. // SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(
  793. // getBucket(false), fileName);
  794. // logger.info( "SimplifiedObjectMeta==="+ JSON.toJSONString(objectMeta));
  795. // 获取文件的全部元信息。
  796. ObjectMetadata metadata = ossClient.getObjectMetadata(getBucket(false), fileName);
  797. // logger.info( "metadata==="+ JSON.toJSONString(metadata));
  798. return metadata;
  799. }
  800. /**
  801. * 获取部分元信息
  802. *
  803. * @param bucketName
  804. * @param fileName
  805. * @return
  806. * @throws Exception
  807. */
  808. public static SimplifiedObjectMeta getSimpleObjectMetadata(String bucketName, String fileName) throws Exception {
  809. OSS ossClient = new OSSClientBuilder().build(AliOssConfig.getInternalEndPoint(), AliOssConfig.getAccessKeyId(),
  810. AliOssConfig.getAccessKeySecret());
  811. SimplifiedObjectMeta metadata = ossClient.getSimplifiedObjectMeta(bucketName, fileName);
  812. ossClient.shutdown();
  813. return metadata;
  814. }
  815. /**
  816. * 获取全部元信息
  817. *
  818. * @param bucketName
  819. * @param fileName
  820. * @return
  821. * @throws Exception
  822. */
  823. public static ObjectMetadata getObjectMetadata(String bucketName, String fileName) throws Exception {
  824. // OSS ossClient = new OSSClientBuilder().build(AliOssConfig.getInternalEndPoint(), AliOssConfig.getAccessKeyId(),
  825. // AliOssConfig.getAccessKeySecret());
  826. // // 获取文件的全部元信息
  827. // ObjectMetadata metadata = ossClient.getObjectMetadata(bucketName, fileName);
  828. // ossClient.shutdown();
  829. // return metadata;
  830. ObjectMetadata metadata = getInternalOssClient().getObjectMetadata(bucketName, fileName);
  831. return metadata;
  832. }
  833. // public static void main(String[] args) throws Exception {
  834. //// String a = JSONObject.toJSONString(AliOssFileTool.getDefaultAcsClient());
  835. //// System.out.println(a);
  836. // }
  837. public static Map<String, String> buildCommonParameters() {
  838. Map<String, String> parameterMap = new HashMap<>();
  839. // 请求公共参数
  840. parameterMap.put("Version", "2014-06-18");
  841. parameterMap.put("AccessKeyId", AliOssConfig.getAccessKeyId()); // 此处请替换成您自己的AccessKeyId
  842. // parameterMap.put("Timestamp",
  843. // "2018-07-27T13:03:45Z");//此处将时间戳固定只是测试需要,这样此示例中生成的签名值就不会变,方便您对比验证,可变时间戳的生成需要用下边这句替换
  844. parameterMap.put("Timestamp", DateUtils.formatIso8601Date(new Date()));
  845. parameterMap.put("SignatureMethod", "HMAC-SHA1");
  846. parameterMap.put("SignatureVersion", "1.0");
  847. // parameterMap.put("SignatureNonce", "4902260a-516a-4b6a-a455-45b653cf6150");
  848. // //此处将唯一随机数固定只是测试需要,这样此示例中生成的签名值就不会变,方便您对比验证,可变唯一随机数的生成需要用下边这句替换
  849. parameterMap.put("SignatureNonce", UUID.randomUUID().toString());
  850. parameterMap.put("Format", "JSON"); // 另外支持JSON格式
  851. return parameterMap;
  852. }
  853. /**
  854. * @Title: sendAsyncSnapshotJob @Description: 获取发送视频批量截图的任务的URL,此接口为异步任务 @param
  855. * fileName 要截图的视频的路径,如 longvideo/video/XXXXX,其中XXXXX为视频名称 @param
  856. * snapshotPath 截图后的图片输出路径,如
  857. * longvideo/snapshot/XXXXX,截图时会自动在文件名后面加序号,输出路径为空时,自动指定为longvideo/snapshot/XXXXX @param
  858. * startMillseconds 截图时间,单位毫秒 @param interval
  859. * 截图间隔时间,若指定则表示异步模式序列截图,Interval必须大于等于0,默认10,单位秒。其中Interval=0表示根据视频时长平均截图。 @param
  860. * snapshotNumber
  861. * 截图数量,若指定则表示异步模式序列截图,且必须大于0,当Time+Interval*Num的截取点超过视频时长时,后续截图自动失效,截图完成时返回实际截取的个数;当Num=1,忽略Interval参数,表示异步单张截图 @return @throws
  862. * Exception @author 王树杞 @date 2018年7月27日 下午5:17:31 @version 2.0 @throws
  863. */
  864. public static String sendAsyncSnapshotJob(String fileName, String snapshotPath, Integer startMillseconds,
  865. Integer interval, Integer snapshotNumber) throws Exception {
  866. // 首先获取公众参数
  867. Map<String, String> parameterMap = buildCommonParameters();
  868. parameterMap.put("Action", "SubmitSnapshotJob");
  869. Map<String, String> inputParamsMap = new HashMap<>();
  870. inputParamsMap.put("Bucket", AliOssFileTool.getBucket(false));
  871. inputParamsMap.put("Location", AliOssFileTool.getSnapshotLocation());
  872. inputParamsMap.put("Object", URLEncoder.encode(fileName, "UTF-8"));
  873. parameterMap.put("Input", JSON.toJSONString(inputParamsMap));
  874. Map<String, String> snapshotConfig = new HashMap<>();
  875. Map<String, String> outPutFile = new HashMap<>();
  876. outPutFile.put("Bucket", AliOssFileTool.getBucket(false));
  877. outPutFile.put("Location", AliOssFileTool.getSnapshotLocation());
  878. if (StringUtils.isBlank(snapshotPath)) {
  879. snapshotPath = fileName.replace("/video/", "/snapshot/");
  880. }
  881. outPutFile.put("Object", URLEncoder.encode(snapshotPath + "_{Count}", "UTF-8"));
  882. snapshotConfig.put("Interval", interval.toString());
  883. snapshotConfig.put("Num", snapshotNumber.toString());
  884. parameterMap.put("PipelineId", "abe6a0b9b9334858913eb416974485d2");
  885. snapshotConfig.put("OutputFile", JSON.toJSONString(outPutFile));
  886. parameterMap.put("SnapshotConfig", JSON.toJSONString(snapshotConfig));
  887. String canonicalizedQueryString = buildCanonicalizedQueryString(parameterMap);
  888. String stringToSign = buildStringToSign(canonicalizedQueryString);
  889. String signature = buildSignature(AliOssConfig.getAccessKeySecret(), stringToSign);
  890. return buildRequestURL(signature, parameterMap);
  891. }
  892. /**
  893. * @Title: sendSyncSnapshotJob @Description: 获取发送某个视频的同步截图的任务URL地址 @param
  894. * fileName 视频路径 @param snapshotPath 输出的截图路径 @param startMillseconds
  895. * 截图的时间戳 @return 某个视频的同步截图的任务URL地址 @throws Exception @author 王树杞 @date
  896. * 2018年7月27日 下午8:07:47 @version 2.0 @throws
  897. */
  898. public static String sendSyncSnapshotJob(String fileName, String snapshotPath, Integer startMillseconds)
  899. throws Exception {
  900. // 首先获取公众参数
  901. Map<String, String> parameterMap = buildCommonParameters();
  902. parameterMap.put("Action", "SubmitSnapshotJob");
  903. Map<String, String> inputParamsMap = new HashMap<>();
  904. inputParamsMap.put("Bucket", AliOssFileTool.getBucket(false));
  905. inputParamsMap.put("Location", AliOssFileTool.getSnapshotLocation());
  906. inputParamsMap.put("Object", URLEncoder.encode(fileName, "UTF-8"));
  907. parameterMap.put("Input", JSON.toJSONString(inputParamsMap));
  908. Map<String, String> snapshotConfig = new HashMap<>();
  909. Map<String, String> outPutFile = new HashMap<>();
  910. outPutFile.put("Bucket", AliOssFileTool.getBucket(false));
  911. outPutFile.put("Location", AliOssFileTool.getSnapshotLocation());
  912. if (StringUtils.isBlank(snapshotPath)) {
  913. snapshotPath = fileName.replace("/video/", "/snapshot/");
  914. }
  915. outPutFile.put("Object", URLEncoder.encode(snapshotPath, "UTF-8"));
  916. snapshotConfig.put("Time", startMillseconds.toString());
  917. snapshotConfig.put("OutputFile", JSON.toJSONString(outPutFile));
  918. parameterMap.put("SnapshotConfig", JSON.toJSONString(snapshotConfig));
  919. String canonicalizedQueryString = buildCanonicalizedQueryString(parameterMap);
  920. String stringToSign = buildStringToSign(canonicalizedQueryString);
  921. String signature = buildSignature(AliOssConfig.getAccessKeySecret(), stringToSign);
  922. return buildRequestURL(signature, parameterMap);
  923. }
  924. private static String percentEncode(String value) throws UnsupportedEncodingException {
  925. return URLEncoder.encode(value, ENCODE_TYPE).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
  926. }
  927. private static String buildCanonicalizedQueryString(Map<String, String> parameterMap)
  928. throws UnsupportedEncodingException {
  929. // 对参数进行排序
  930. List<String> sortedKeys = new ArrayList<String>(parameterMap.keySet());
  931. Collections.sort(sortedKeys);
  932. StringBuilder temp = new StringBuilder();
  933. for (String key : sortedKeys) {
  934. // 此处需要对key和value进行编码
  935. String value = parameterMap.get(key);
  936. temp.append(SEPARATOR).append(percentEncode(key)).append(EQUAL).append(percentEncode(value));
  937. }
  938. return temp.toString().substring(1);
  939. }
  940. private static String buildStringToSign(String canonicalizedQueryString) throws UnsupportedEncodingException {
  941. // 生成stringToSign字符
  942. StringBuilder temp = new StringBuilder();
  943. temp.append(HTTP_METHOD).append(SEPARATOR);
  944. temp.append(percentEncode("/")).append(SEPARATOR);
  945. // 此处需要对canonicalizedQueryString进行编码
  946. temp.append(percentEncode(canonicalizedQueryString));
  947. return temp.toString();
  948. }
  949. private static String buildSignature(String keySecret, String stringToSign)
  950. throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
  951. SecretKey key = new SecretKeySpec((keySecret + SEPARATOR).getBytes(ENCODE_TYPE), SignatureMethod.HMAC_SHA1);
  952. Mac mac = Mac.getInstance(ALGORITHM);
  953. mac.init(key);
  954. byte[] hashBytes = mac.doFinal(stringToSign.toString().getBytes(ENCODE_TYPE));
  955. byte[] base64Bytes = new Base64().encode(hashBytes);
  956. String base64UTF8String = new String(base64Bytes, "utf-8");
  957. return URLEncoder.encode(base64UTF8String, ENCODE_TYPE);
  958. }
  959. private static String buildRequestURL(String signature, Map<String, String> parameterMap)
  960. throws UnsupportedEncodingException {
  961. // 生成请求URL
  962. StringBuilder temp = new StringBuilder("http://mts.cn-hangzhou.aliyuncs.com?");
  963. temp.append(URLEncoder.encode("Signature", ENCODE_TYPE)).append("=").append(signature);
  964. for (Map.Entry<String, String> e : parameterMap.entrySet()) {
  965. temp.append("&").append(percentEncode(e.getKey())).append("=").append(percentEncode(e.getValue()));
  966. }
  967. return temp.toString();
  968. }
  969. public static String saveInputStreamPic(InputStream inputStream, String bucket, String project, String dir,
  970. String key) throws OSSException, ClientException, IOException {
  971. String fullKey = project + "/" + dir + "/" + key;
  972. ObjectMetadata objectMetadata = new ObjectMetadata();
  973. objectMetadata.setContentType("image/jpg");
  974. getOssClient().putObject(bucket, fullKey, inputStream, objectMetadata);
  975. return fullKey;
  976. }
  977. public static String sendImageToAliOss(BufferedImage image) throws Exception {
  978. ByteArrayOutputStream os = new ByteArrayOutputStream();
  979. ImageIO.write(image, "jpg", os);
  980. InputStream is = new ByteArrayInputStream(os.toByteArray());
  981. // 将生成的图片往OSS里面上传
  982. String random = UUID.randomUUID().toString().replaceAll("-", "") + new Random().nextLong();
  983. String key = Md5Util.encoderByMd5(random);
  984. String coverImgPath = AliOssFileTool.saveVideoCoverImagFromInternal(is, key);
  985. return coverImgPath;
  986. }
  987. public static String saveVideoCoverImagFromInternal(InputStream inputStream, String key)
  988. throws OSSException, ClientException, IOException {
  989. String bucketName = AliOssConfig.getBucket(EnumAllBuckets.PUBVIDEOBUCKET.getBucketName());
  990. String fullKey = getProjectName() + "/pic/video/cover/" + DateUtils.dateToStringyyyyMMdd(new Date()) + "/"
  991. + key;
  992. ObjectMetadata objectMetadata = new ObjectMetadata();
  993. objectMetadata.setContentType("image/jpg");
  994. getInternalOssClient().putObject(bucketName, fullKey, inputStream, objectMetadata);
  995. return fullKey;
  996. }
  997. /**
  998. * @param duration 时长,如果是图片则传0,视频则传视频时长
  999. * @param isInternal 是否内网访问
  1000. * @return
  1001. * @return String
  1002. * @Title: generatePresignedUrl
  1003. * @Description:得到对象的临时访问URL
  1004. * @author 王树杞
  1005. * @date 2019年2月25日 上午11:04:22
  1006. * @version 2.0
  1007. */
  1008. public static String generatePresignedUrl(String filePath, Integer duration, boolean isInternal) {
  1009. if (StringUtils.isEmpty(filePath)) {
  1010. return null;
  1011. }
  1012. if (filePath.startsWith("http")) {
  1013. filePath = filePath.replace(PropertiesUtils.getDownloadDomain(), "");
  1014. filePath = filePath.replace("https://weappupload.piaoquantv.com/", "");
  1015. filePath = filePath.replace("https://testweappupload.yishihui.com/", "");
  1016. filePath = filePath.replace("https://lvupload.piaoquantv.com/", "");
  1017. }
  1018. if (filePath.contains("Signature") && filePath.contains("OSSAccessKeyId")) {
  1019. return filePath;
  1020. }
  1021. if (duration == null) {
  1022. duration = 0;
  1023. }
  1024. // 设置URL过期时间为视频时长+3天。
  1025. // 单位为秒;
  1026. Date expiration = new Date(new Date().getTime() + (duration + (3 * 24 * 60 * 60)) * 1000);
  1027. // //一分钟
  1028. // Date expiration = new Date(new Date().getTime() +( 60) * 1000);
  1029. // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
  1030. URL url = getOssReadOnlyClient().generatePresignedUrl(BasePropertiesUtils.getVideoBucket(),
  1031. filePath, expiration, HttpMethod.GET);
  1032. String path = url.getFile();
  1033. if (StringUtils.startsWith(path, "/")) {
  1034. return StringUtils.substring(path, 1);
  1035. }
  1036. return path;
  1037. }
  1038. public static String saveObjectFromInternal(InputStream inputStream, String fullKey)
  1039. throws OSSException, ClientException, IOException {
  1040. String bucketName = BasePropertiesUtils.getVideoBucket();
  1041. getInternalOssClient().putObject(bucketName, fullKey, inputStream);
  1042. return fullKey;
  1043. }
  1044. public static String saveObjectFromInternal(String bucketName, String url, String fullKey)
  1045. throws Exception {
  1046. InputStream inputStream = new URL(url).openStream();
  1047. getInternalOssClient().putObject(bucketName, fullKey, inputStream);
  1048. if (inputStream != null) {
  1049. inputStream.close();
  1050. }
  1051. return fullKey;
  1052. }
  1053. public static boolean checkObjectExistFromInternal(String bucketName, String fullKey) {
  1054. return getInternalOssClient().doesObjectExist(bucketName, fullKey);
  1055. }
  1056. public static String uploadShangHaiVideo(InputStream inputStream, String key, String bucketName) {
  1057. ObjectMetadata objectMetadata = new ObjectMetadata();
  1058. objectMetadata.setContentType("video/mp4");
  1059. getShangHaiInternalOssClient().putObject(bucketName, key, inputStream, objectMetadata);
  1060. return key;
  1061. }
  1062. public static boolean isShangHaiExist(String bucket, String fullKey) {
  1063. return getShangHaiInternalOssClient().doesObjectExist(bucket, fullKey);
  1064. }
  1065. public static Boolean isStorageClassArchive(String bucket, String key) throws OSSException, ClientException {
  1066. ObjectMetadata objectMetadata = getInternalOssClient().getObjectMetadata(bucket, key);
  1067. StorageClass storageClass = objectMetadata.getObjectStorageClass();
  1068. return storageClass == StorageClass.Archive;
  1069. }
  1070. public static boolean isStorageClassColdArchive(String bucket, String key) throws OSSException, ClientException {
  1071. ObjectMetadata objectMetadata = getInternalOssClient().getObjectMetadata(bucket, key);
  1072. StorageClass storageClass = objectMetadata.getObjectStorageClass();
  1073. return storageClass == StorageClass.ColdArchive;
  1074. }
  1075. public static void setStorageClassToArchive(String bucket, String key) throws OSSException, ClientException {
  1076. // 创建CopyObjectRequest对象。
  1077. CopyObjectRequest request = new CopyObjectRequest(bucket, key, bucket, key);
  1078. // 创建ObjectMetadata对象。
  1079. ObjectMetadata objectMetadata = new ObjectMetadata();
  1080. // 封装header,此处以设置存储类型为归档类型为例。
  1081. objectMetadata.setHeader("x-oss-storage-class", StorageClass.Archive);
  1082. request.setNewObjectMetadata(objectMetadata);
  1083. // 更改文件存储类型。
  1084. CopyObjectResult result = getInternalOssClient().copyObject(request);
  1085. }
  1086. public static void recoverVideoAsync(String bucket, String srckey) {
  1087. OSSClient ossInternalClient = getInternalOssClient();
  1088. ObjectMetadata objectMetadata = ossInternalClient.getObjectMetadata(bucket, srckey);
  1089. // 校验文件是否为归档文件。
  1090. StorageClass storageClass = objectMetadata.getObjectStorageClass();
  1091. if (storageClass == StorageClass.Archive) {
  1092. // 解冻文件。
  1093. try {
  1094. ossInternalClient.restoreObject(bucket, srckey);
  1095. } catch (Exception e) {
  1096. // OSS Auto-generated catch blockvideo-common/src/main/java/com/weiqu/video/common/enums/ExceptionCodeEnum.java
  1097. // e.printStackTrace();
  1098. logger.error("视频可能在解冻中");
  1099. }
  1100. } else if (storageClass == StorageClass.ColdArchive) {
  1101. // 解冻文件。
  1102. try {
  1103. RestoreJobParameters parameters = new RestoreJobParameters(RestoreTier.RESTORE_TIER_EXPEDITED);
  1104. RestoreConfiguration configuration = new RestoreConfiguration(3, parameters);
  1105. ossInternalClient.restoreObject(bucket, srckey, configuration);
  1106. } catch (Exception ex) {
  1107. logger.error("视频可能在解冻中", ex);
  1108. }
  1109. }
  1110. }
  1111. public static Boolean isRestoreCompleted(String bucket, String key) throws OSSException, ClientException {
  1112. ObjectMetadata objectMetadata = getInternalOssClient().getObjectMetadata(bucket, key);
  1113. Boolean isRestoreCompleted = false;
  1114. try {
  1115. isRestoreCompleted = objectMetadata.isRestoreCompleted();
  1116. } catch (Exception e) {
  1117. // OSS Auto-generated catch block
  1118. // e.printStackTrace();
  1119. logger.error("视频可能在解冻中");
  1120. }
  1121. return isRestoreCompleted;
  1122. }
  1123. /**
  1124. * @param path
  1125. * @param path
  1126. * @return
  1127. * @ApiModelProperty(value="冻结状态: -1:无须解冻 0:待解冻 1:解冻中 2:解冻完成")
  1128. */
  1129. public static Integer getFrozenStatus(String path) {
  1130. if (path.startsWith("http") && !path.startsWith(PropertiesUtils.getDownloadDomain())) {
  1131. logger.info("getFrozenStatus-outer size video, path :" + path);
  1132. return -1;
  1133. }
  1134. String realPath = path.replace(PropertiesUtils.getDownloadDomain(), "");
  1135. String bucketName = BasePropertiesUtils.getVideoBucket();
  1136. ObjectMetadata objectMetadata = null;
  1137. try {
  1138. objectMetadata = getInternalOssClient().getObjectMetadata(bucketName, realPath);
  1139. } catch (Exception ex) {
  1140. logger.error("getFrozenStatus-error", ex);
  1141. return -1;
  1142. }
  1143. if (Objects.isNull(objectMetadata)) {
  1144. logger.error("getFrozenStatus-error, path :" + path + " do not has metaData");
  1145. return -1;
  1146. }
  1147. StorageClass storageClass = objectMetadata.getObjectStorageClass();
  1148. if (storageClass != StorageClass.Archive && storageClass != StorageClass.ColdArchive) {
  1149. logger.info("getFrozenStatus, path :" + path + " do not in Archive status");
  1150. return -1;
  1151. }
  1152. try {
  1153. // 解冻完成
  1154. boolean isRestoreCompleted = objectMetadata.isRestoreCompleted();
  1155. if (isRestoreCompleted) {
  1156. return 2;
  1157. } else {
  1158. return 1;
  1159. }
  1160. } catch (NullPointerException e) {
  1161. logger.info("getFrozenStatus, path :" + path + " waiting for forzed!");
  1162. return 0;
  1163. }
  1164. }
  1165. public static Map<String, Object> getMediaAllInfo(String inPath) {
  1166. return getMediaAllInfo(inPath, BasePropertiesUtils.getVideoBucket());
  1167. }
  1168. public static Map<String, Object> getMediaAllInfo(String inPath, String bucketName) {
  1169. Map<String, Object> map = new HashMap<String, Object>();
  1170. String encodedInput;
  1171. try {
  1172. encodedInput = URLEncoder.encode(inPath, "utf-8");
  1173. } catch (UnsupportedEncodingException e) {
  1174. logger.error("获取元数据输入流解析错误", e);
  1175. map.put("status", "1");
  1176. return map;
  1177. }
  1178. SubmitMediaInfoJobRequest request = new SubmitMediaInfoJobRequest();
  1179. JSONObject input = new JSONObject();
  1180. input.put("Bucket", bucketName);
  1181. input.put("Location", PropertiesUtils.getTranscodeLocation());
  1182. input.put("Object", encodedInput);
  1183. request.setInput(input.toJSONString());
  1184. request.setPipelineId(PropertiesUtils.getTranscodePipelineId());
  1185. try {
  1186. SubmitMediaInfoJobResponse response = new SubmitMediaInfoJobResponse();
  1187. response = AliOssConfig.getIAcsClient().getAcsResponse(request);
  1188. if (response.getMediaInfoJob().getState() != null
  1189. && response.getMediaInfoJob().getState().equalsIgnoreCase("Fail")) {
  1190. logger.error("获取元数据错误:" + JSONObject.toJSONString(response.getMediaInfoJob())
  1191. + ",requestId:" + response.getRequestId());
  1192. map.put("status", "2");
  1193. return map;
  1194. }
  1195. Properties properties = response.getMediaInfoJob().getProperties();
  1196. Properties.Streams.VideoStream videoStream = null;
  1197. if (CollectionUtils.isNotEmpty(properties.getStreams().getVideoStreamList())) {
  1198. videoStream = properties.getStreams().getVideoStreamList().get(0);
  1199. }
  1200. Properties.Format format = properties.getFormat();
  1201. logger.info("videoStream:" + JSONObject.toJSONString(videoStream));
  1202. logger.info("format:" + JSONObject.toJSONString(format));
  1203. map.put("status", "0");
  1204. if (properties.getWidth() != null) {
  1205. map.put("width", Integer.parseInt(properties.getWidth()) + "");
  1206. }
  1207. if (properties.getHeight() != null) {
  1208. map.put("height", Integer.parseInt(properties.getHeight()) + "");
  1209. }
  1210. if (videoStream != null) {
  1211. map.put("rotate", videoStream.getRotate());
  1212. map.put("codeName", videoStream.getCodecName());
  1213. }
  1214. if (format != null) {
  1215. map.put("size", format.getSize());
  1216. //设置成long类型的 大于0少于1的设置成1
  1217. if (Double.parseDouble(format.getDuration()) > 0 && Double.parseDouble(format.getDuration()) < 1) {
  1218. map.put("duration", new Double(1).longValue());
  1219. } else {
  1220. map.put("duration", StringUtils.isEmpty(format.getDuration()) ? 0 : new Double(Double.parseDouble(format.getDuration())).longValue());
  1221. }
  1222. map.put("bitRate", StringUtils.isEmpty(format.getBitrate()) ? 0 : new Double(Double.parseDouble(format.getBitrate())).longValue() * 1000);
  1223. }
  1224. } catch (ServerException e) {
  1225. logger.error("获取元数据服务器异常", e);
  1226. map.put("status", "3");
  1227. } catch (ClientException e) {
  1228. logger.error("获取元数据客户端异常", e);
  1229. map.put("status", "4");
  1230. } catch (Exception e) {
  1231. logger.error("获取元数据异常", e);
  1232. map.put("status", "5");
  1233. }
  1234. return map;
  1235. }
  1236. public static CopyObjectResult setStorageClassToColdArchive(String bucket, String key) {
  1237. CopyObjectRequest request = new CopyObjectRequest(bucket, key, bucket, key);
  1238. ObjectMetadata objectMetadata = new ObjectMetadata();
  1239. // 封装header,此处以设置存储类型为归档类型为例。
  1240. objectMetadata.setHeader("x-oss-storage-class", StorageClass.ColdArchive);
  1241. request.setNewObjectMetadata(objectMetadata);
  1242. // 更改文件存储类型。
  1243. return getInternalOssClient().copyObject(request);
  1244. }
  1245. public static String getRandomObjectKey(Integer fileType) {
  1246. String env = PropertiesUtils.getProjectEnv();
  1247. if (StringUtils.isEmpty(env)) {
  1248. env = "qa";
  1249. }
  1250. String fileName = RandomUtil.generate18String();
  1251. if (EnumUploadFileType.VIDEO.getIntType().equals(fileType)) {
  1252. fileName = "/video/" + env + "/" + DateUtils.dateToStringyyyyMMdd(new Date()) + "/" + fileName;
  1253. } else if (EnumUploadFileType.VOICE.getIntType().equals(fileType)) {
  1254. fileName = "/voice/" + env + "/" + DateUtils.dateToStringyyyyMMdd(new Date()) + "/" + fileName;
  1255. } else {
  1256. fileName = "/pic/" + env + "/" + DateUtils.dateToStringyyyyMMdd(new Date()) + "/" + fileName;
  1257. }
  1258. return getProjectName() + fileName;
  1259. }
  1260. public static StsTokenVO getStsToken(String fileName, Long durationSeconds) {
  1261. String endpoint = BasePropertiesUtils.getLongvideoStsEndpoint();
  1262. String accessKeyId = BasePropertiesUtils.getLongvideoStsAccessKeyId();
  1263. String accessKeySecret = BasePropertiesUtils.getLongvideoStsAccessKeySecret();
  1264. String roleArn = BasePropertiesUtils.getLongvideoStsRoleArn();
  1265. String roleSessionName = BasePropertiesUtils.getLongvideoStsSessionName();
  1266. StsTokenVO result = new StsTokenVO();
  1267. try {
  1268. String region = "cn-hangzhou";
  1269. DefaultProfile.addEndpoint("", "", "Sts", endpoint);
  1270. IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
  1271. DefaultAcsClient client = new DefaultAcsClient(profile);
  1272. final AssumeRoleRequest request = new AssumeRoleRequest();
  1273. request.setMethod(MethodType.POST);
  1274. request.setRoleArn(roleArn);
  1275. request.setRoleSessionName(roleSessionName);
  1276. //设置过期时间 临时访问凭证的有效时间,单位为秒。最小值为900,最大值以当前角色设定的最大会话时间为准。角色最大会话时间取值范围为3600秒~43200秒
  1277. if (Objects.nonNull(durationSeconds)) {
  1278. request.setDurationSeconds(durationSeconds);
  1279. }
  1280. JSONObject policy = getUploadFileStsPolicy(BasePropertiesUtils.getVideoBucket(), fileName);
  1281. request.setPolicy(policy.toJSONString());
  1282. final AssumeRoleResponse response = client.getAcsResponse(request);
  1283. result.setExpiration(response.getCredentials().getExpiration());
  1284. result.setAccessKeyId(response.getCredentials().getAccessKeyId());
  1285. result.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
  1286. result.setSecurityToken(response.getCredentials().getSecurityToken());
  1287. result.setRequestId(response.getRequestId());
  1288. result.setFileName(fileName);
  1289. result.setHost(AliOssConfig.getUploadDomain());
  1290. String host0 = BasePropertiesUtils.getOssaccelerateUploadDomain();
  1291. String host1 = "https://" + AliOssConfig.getBucket(EnumPublicBuckets.PUBBUCKET.getBucketName()) + "." + AliOssConfig.getOssEndPoint() + "/";
  1292. result.setHosts(new String[]{host0, host1});
  1293. result.setBucket(BasePropertiesUtils.getVideoBucket());
  1294. result.setRegion(region);
  1295. result.setCname(true);
  1296. // 返回服务器当前时间
  1297. result.setServerTimestamp(System.currentTimeMillis());
  1298. } catch (com.aliyuncs.exceptions.ClientException e) {
  1299. logger.error(String.format("获取临时令牌失败,errorCode:%s;errorMessage:%s;requestId:%s",
  1300. e.getErrCode(), e.getErrMsg(), e.getRequestId()));
  1301. } catch (Exception e) {
  1302. logger.error("获取临时令牌失败", e);
  1303. }
  1304. return result;
  1305. }
  1306. private static JSONObject getUploadFileStsPolicy(String bucketName, String fileName) {
  1307. JSONObject policy = new JSONObject();
  1308. policy.put("Version", "1");
  1309. JSONArray statements = new JSONArray();
  1310. JSONObject statement = new JSONObject();
  1311. statement.put("Effect", "Allow");
  1312. JSONArray action = new JSONArray();
  1313. action.add("oss:PutObject");
  1314. statement.put("Action", action);
  1315. JSONArray resource = new JSONArray();
  1316. resource.add("acs:oss:*:1894469520484605:" + bucketName + "/" + fileName);
  1317. statement.put("Resource", resource);
  1318. statements.add(statement);
  1319. policy.put("Statement", statements);
  1320. logger.info(String.format("Policy:%s", JSON.toJSONString(policy)));
  1321. return policy;
  1322. }
  1323. }