xiongzhu il y a 4 ans
Parent
commit
e34d83fcbf

+ 2 - 0
src/main/java/com/izouma/nineth/repo/UserRepo.java

@@ -93,4 +93,6 @@ public interface UserRepo extends JpaRepository<User, Long>, JpaSpecificationExe
     void updateMinterForAsset(Long userId);
     void updateMinterForAsset(Long userId);
 
 
     List<User> findByPhoneInAndDelFalse(Iterable<String> phone);
     List<User> findByPhoneInAndDelFalse(Iterable<String> phone);
+
+    List<User> findByIdInAndDelFalse(Iterable<Long> userId);
 }
 }

+ 9 - 1
src/main/java/com/izouma/nineth/security/JwtTokenUtil.java

@@ -15,6 +15,7 @@ import java.io.Serializable;
 import java.util.Date;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Map;
+import java.util.Optional;
 import java.util.function.Function;
 import java.util.function.Function;
 
 
 @Component
 @Component
@@ -62,7 +63,14 @@ public class JwtTokenUtil implements Serializable {
 
 
     private Boolean isTokenExpired(String token) {
     private Boolean isTokenExpired(String token) {
         final Date expiration = getExpirationDateFromToken(token);
         final Date expiration = getExpirationDateFromToken(token);
-        return expiration.before(clock.now()) || !userTokenRepo.findById(getUsernameFromToken(token)).isPresent();
+        Optional<UserToken> userToken = userTokenRepo.findById(getUsernameFromToken(token));
+        if (!userToken.isPresent()) {
+            return true;
+        }
+        if (!token.equals(userToken.get().getToken())) {
+            return true;
+        }
+        return expiration.before(clock.now());
     }
     }
 
 
     private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
     private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {

+ 29 - 12
src/main/java/com/izouma/nineth/service/AirDropService.java

@@ -1,32 +1,33 @@
 package com.izouma.nineth.service;
 package com.izouma.nineth.service;
 
 
-import com.izouma.nineth.domain.AirDrop;
-import com.izouma.nineth.domain.Collection;
-import com.izouma.nineth.domain.Coupon;
-import com.izouma.nineth.domain.UserCoupon;
+import com.izouma.nineth.domain.*;
 import com.izouma.nineth.dto.PageQuery;
 import com.izouma.nineth.dto.PageQuery;
 import com.izouma.nineth.enums.AirDropType;
 import com.izouma.nineth.enums.AirDropType;
+import com.izouma.nineth.enums.CollectionType;
 import com.izouma.nineth.exception.BusinessException;
 import com.izouma.nineth.exception.BusinessException;
-import com.izouma.nineth.repo.AirDropRepo;
-import com.izouma.nineth.repo.CollectionRepo;
-import com.izouma.nineth.repo.CouponRepo;
-import com.izouma.nineth.repo.UserCouponRepo;
+import com.izouma.nineth.repo.*;
 import com.izouma.nineth.utils.JpaUtils;
 import com.izouma.nineth.utils.JpaUtils;
 import lombok.AllArgsConstructor;
 import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.BeanUtils;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Page;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
 import javax.transaction.Transactional;
 import javax.transaction.Transactional;
+import java.util.List;
 
 
 @Service
 @Service
 @AllArgsConstructor
 @AllArgsConstructor
+@Slf4j
 public class AirDropService {
 public class AirDropService {
 
 
-    private AirDropRepo    airDropRepo;
-    private CouponRepo     couponRepo;
-    private UserCouponRepo userCouponRepo;
-    private CollectionRepo collectionRepo;
+    private AirDropRepo       airDropRepo;
+    private CouponRepo        couponRepo;
+    private UserCouponRepo    userCouponRepo;
+    private CollectionRepo    collectionRepo;
+    private UserRepo          userRepo;
+    private AssetService      assetService;
+    private CollectionService collectionService;
 
 
     public Page<AirDrop> all(PageQuery pageQuery) {
     public Page<AirDrop> all(PageQuery pageQuery) {
         return airDropRepo.findAll(JpaUtils.toSpecification(pageQuery, AirDrop.class), JpaUtils.toPageRequest(pageQuery));
         return airDropRepo.findAll(JpaUtils.toSpecification(pageQuery, AirDrop.class), JpaUtils.toPageRequest(pageQuery));
@@ -50,6 +51,22 @@ public class AirDropService {
             if (collection.getStock() < record.getUserIds().size()) {
             if (collection.getStock() < record.getUserIds().size()) {
                 throw new BusinessException("藏品库存不足");
                 throw new BusinessException("藏品库存不足");
             }
             }
+            List<User> users = userRepo.findByIdInAndDelFalse(record.getUserIds());
+            for (User user : users) {
+                try {
+                    if (collection.getType() == CollectionType.BLIND_BOX) {
+                        assetService.createAsset(collection, user, null, collection.getPrice(), "空投");
+                    } else {
+                        BlindBoxItem winItem = collectionService.draw(collection.getId());
+                        assetService.createAsset(winItem, user, null, collection.getPrice(), "空投");
+                    }
+                    collection.setStock(collection.getStock() - 1);
+                    collection.setSale(collection.getSale() + 1);
+                    collectionRepo.save(collection);
+                } catch (Exception e) {
+                    log.error("空投出错", e);
+                }
+            }
         }
         }
         return airDropRepo.save(record);
         return airDropRepo.save(record);
     }
     }

+ 86 - 0
src/main/java/com/izouma/nineth/service/AssetMintService.java

@@ -0,0 +1,86 @@
+package com.izouma.nineth.service;
+
+import com.alipay.api.AlipayClient;
+import com.github.binarywang.wxpay.service.WxPayService;
+import com.github.kevinsawicki.http.HttpRequest;
+import com.izouma.nineth.config.AlipayProperties;
+import com.izouma.nineth.config.WxPayProperties;
+import com.izouma.nineth.domain.Asset;
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.dto.NFT;
+import com.izouma.nineth.dto.NFTAccount;
+import com.izouma.nineth.event.CreateAssetEvent;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.*;
+import io.ipfs.api.IPFS;
+import io.ipfs.api.MerkleNode;
+import io.ipfs.api.NamedStreamable;
+import io.ipfs.multihash.Multihash;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.context.ApplicationContext;
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+
+@Service
+@Slf4j
+@AllArgsConstructor
+public class AssetMintService {
+    private AssetRepo          assetRepo;
+    private UserRepo           userRepo;
+    private NFTService         nftService;
+    private ApplicationContext applicationContext;
+    private TokenHistoryRepo   tokenHistoryRepo;
+    private Environment        env;
+
+    public void mint(Asset asset, Long historyId) {
+        User user = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
+        if (StringUtils.isEmpty(user.getPublicKey())) {
+            NFTAccount account = nftService.createAccount(user.getUsername());
+            user.setNftAccount(account.getAccountId());
+            user.setKmsId(account.getAccountKmsId());
+            user.setPublicKey(account.getPublicKey());
+            userRepo.save(user);
+        }
+        try {
+            NFT nft = nftService.createToken(user.getNftAccount());
+            if (nft != null) {
+                asset.setTokenId(nft.getTokenId());
+                asset.setBlockNumber(nft.getBlockNumber());
+                asset.setTxHash(nft.getTxHash());
+                asset.setGasUsed(nft.getGasUsed());
+                if (asset.getIpfsUrl() == null) {
+                    asset.setIpfsUrl(ipfsUpload(asset.getPic().get(0).getUrl()));
+                }
+                assetRepo.save(asset);
+
+                tokenHistoryRepo.findById(historyId).ifPresent(tokenHistory -> {
+                    tokenHistory.setTokenId(nft.getTokenId());
+                    tokenHistoryRepo.save(tokenHistory);
+                });
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        applicationContext.publishEvent(new CreateAssetEvent(this, true, asset));
+    }
+
+    public String ipfsUpload(String url) {
+        try {
+            IPFS ipfs = new IPFS("112.74.34.84", 5001);
+            HttpRequest request = HttpRequest.get(url);
+            File file = File.createTempFile("ipfs", ".tmp");
+            request.receive(file);
+            NamedStreamable.FileWrapper file1 = new NamedStreamable.FileWrapper(file);
+            MerkleNode put = ipfs.add(file1).get(0);
+            Multihash multihash = ipfs.pin.add(put.hash).get(0);
+            log.info("上传ipfs成功 {}", multihash.toBase58());
+            return multihash.toBase58();
+        } catch (Exception e) {
+        }
+        return null;
+    }
+}

+ 14 - 53
src/main/java/com/izouma/nineth/service/AssetService.java

@@ -39,6 +39,8 @@ import org.springframework.beans.BeanUtils;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationContext;
 import org.springframework.core.env.Environment;
 import org.springframework.core.env.Environment;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Page;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.scheduling.annotation.AsyncResult;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 import org.springframework.ui.Model;
 import org.springframework.ui.Model;
 
 
@@ -49,6 +51,7 @@ import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Arrays;
 import java.util.List;
 import java.util.List;
+import java.util.concurrent.Future;
 
 
 @Service
 @Service
 @AllArgsConstructor
 @AllArgsConstructor
@@ -69,16 +72,18 @@ public class AssetService {
     private WxPayProperties    wxPayProperties;
     private WxPayProperties    wxPayProperties;
     private WxPayService       wxPayService;
     private WxPayService       wxPayService;
     private Environment        env;
     private Environment        env;
+    private AssetMintService   assetMintService;
 
 
     public Page<Asset> all(PageQuery pageQuery) {
     public Page<Asset> all(PageQuery pageQuery) {
         return assetRepo.findAll(JpaUtils.toSpecification(pageQuery, Asset.class), JpaUtils.toPageRequest(pageQuery));
         return assetRepo.findAll(JpaUtils.toSpecification(pageQuery, Asset.class), JpaUtils.toPageRequest(pageQuery));
     }
     }
 
 
-    public Asset createAsset(Collection collection, User user, Long orderId, BigDecimal price, String type) {
+    @Async
+    public Future<Asset> createAsset(Collection collection, User user, Long orderId, BigDecimal price, String type) {
         Asset asset = Asset.create(collection, user);
         Asset asset = Asset.create(collection, user);
         asset.setOrderId(orderId);
         asset.setOrderId(orderId);
         asset.setPrice(price);
         asset.setPrice(price);
-        asset.setIpfsUrl(ipfsUpload(collection.getPic().get(0).getUrl()));
+        asset.setIpfsUrl(assetMintService.ipfsUpload(collection.getPic().get(0).getUrl()));
         assetRepo.save(asset);
         assetRepo.save(asset);
 
 
         TokenHistory tokenHistory = tokenHistoryRepo.save(TokenHistory.builder()
         TokenHistory tokenHistory = tokenHistoryRepo.save(TokenHistory.builder()
@@ -90,15 +95,16 @@ public class AssetService {
                 .operation(type)
                 .operation(type)
                 .price(price)
                 .price(price)
                 .build());
                 .build());
-        mint(asset, tokenHistory.getId());
-        return asset;
+        assetMintService.mint(asset, tokenHistory.getId());
+        return new AsyncResult<>(asset);
     }
     }
 
 
-    public Asset createAsset(BlindBoxItem winItem, User user, Long orderId, BigDecimal price, String type) {
+    @Async
+    public Future<Asset> createAsset(BlindBoxItem winItem, User user, Long orderId, BigDecimal price, String type) {
         Asset asset = Asset.create(winItem, user);
         Asset asset = Asset.create(winItem, user);
         asset.setOrderId(orderId);
         asset.setOrderId(orderId);
         asset.setPrice(price);
         asset.setPrice(price);
-        asset.setIpfsUrl(ipfsUpload(winItem.getPic().get(0).getUrl()));
+        asset.setIpfsUrl(assetMintService.ipfsUpload(winItem.getPic().get(0).getUrl()));
         assetRepo.save(asset);
         assetRepo.save(asset);
         TokenHistory tokenHistory = tokenHistoryRepo.save(TokenHistory.builder()
         TokenHistory tokenHistory = tokenHistoryRepo.save(TokenHistory.builder()
                 .tokenId(asset.getTokenId())
                 .tokenId(asset.getTokenId())
@@ -109,55 +115,10 @@ public class AssetService {
                 .operation(type)
                 .operation(type)
                 .price(price)
                 .price(price)
                 .build());
                 .build());
-        mint(asset, tokenHistory.getId());
-        return asset;
+        assetMintService.mint(asset, tokenHistory.getId());
+        return new AsyncResult<>(asset);
     }
     }
 
 
-    public void mint(Asset asset, Long historyId) {
-        User user = userRepo.findById(asset.getUserId()).orElseThrow(new BusinessException("用户不存在"));
-        if (StringUtils.isEmpty(user.getPublicKey())) {
-            NFTAccount account = nftService.createAccount(user.getUsername());
-            user.setNftAccount(account.getAccountId());
-            user.setKmsId(account.getAccountKmsId());
-            user.setPublicKey(account.getPublicKey());
-            userRepo.save(user);
-        }
-        try {
-            NFT nft = nftService.createToken(user.getNftAccount());
-            if (nft != null) {
-                asset.setTokenId(nft.getTokenId());
-                asset.setBlockNumber(nft.getBlockNumber());
-                asset.setTxHash(nft.getTxHash());
-                asset.setGasUsed(nft.getGasUsed());
-                asset.setIpfsUrl(ipfsUpload(asset.getPic().get(0).getUrl()));
-                assetRepo.save(asset);
-
-                tokenHistoryRepo.findById(historyId).ifPresent(tokenHistory -> {
-                    tokenHistory.setTokenId(nft.getTokenId());
-                    tokenHistoryRepo.save(tokenHistory);
-                });
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        applicationContext.publishEvent(new CreateAssetEvent(this, true, asset));
-    }
-
-    public String ipfsUpload(String url) {
-        try {
-            IPFS ipfs = new IPFS("112.74.34.84", 5001);
-            HttpRequest request = HttpRequest.get(url);
-            File file = File.createTempFile("ipfs", ".tmp");
-            request.receive(file);
-            NamedStreamable.FileWrapper file1 = new NamedStreamable.FileWrapper(file);
-            MerkleNode put = ipfs.add(file1).get(0);
-            Multihash multihash = ipfs.pin.add(put.hash).get(0);
-            log.info("上传ipfs成功 {}", multihash.toBase58());
-            return multihash.toBase58();
-        } catch (Exception e) {
-        }
-        return null;
-    }
 
 
     public void publicShow(Long id) {
     public void publicShow(Long id) {
         Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
         Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));

+ 3 - 0
src/main/java/com/izouma/nineth/service/CollectionService.java

@@ -243,6 +243,9 @@ public class CollectionService {
                 throw new BusinessException("盲盒抽卡失败");
                 throw new BusinessException("盲盒抽卡失败");
             }
             }
         }
         }
+        winItem.setStock(winItem.getStock() - 1);
+        winItem.setSale(winItem.getSale() + 1);
+        blindBoxItemRepo.save(winItem);
         return winItem;
         return winItem;
     }
     }
 
 

+ 52 - 17
src/main/java/com/izouma/nineth/service/OrderService.java

@@ -44,20 +44,21 @@ import java.util.*;
 @Slf4j
 @Slf4j
 public class OrderService {
 public class OrderService {
 
 
-    private OrderRepo        orderRepo;
-    private CollectionRepo   collectionRepo;
-    private UserAddressRepo  userAddressRepo;
-    private UserRepo         userRepo;
-    private Environment      env;
-    private AlipayClient     alipayClient;
-    private AlipayProperties alipayProperties;
-    private WxPayService     wxPayService;
-    private WxPayProperties  wxPayProperties;
-    private AssetService     assetService;
-    private SysConfigService sysConfigService;
-    private BlindBoxItemRepo blindBoxItemRepo;
-    private AssetRepo        assetRepo;
-    private UserCouponRepo   userCouponRepo;
+    private OrderRepo         orderRepo;
+    private CollectionRepo    collectionRepo;
+    private UserAddressRepo   userAddressRepo;
+    private UserRepo          userRepo;
+    private Environment       env;
+    private AlipayClient      alipayClient;
+    private AlipayProperties  alipayProperties;
+    private WxPayService      wxPayService;
+    private WxPayProperties   wxPayProperties;
+    private AssetService      assetService;
+    private SysConfigService  sysConfigService;
+    private BlindBoxItemRepo  blindBoxItemRepo;
+    private AssetRepo         assetRepo;
+    private UserCouponRepo    userCouponRepo;
+    private CollectionService collectionService;
 
 
     public Page<Order> all(PageQuery pageQuery) {
     public Page<Order> all(PageQuery pageQuery) {
         return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
         return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
@@ -232,7 +233,7 @@ public class OrderService {
 
 
     }
     }
 
 
-    public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
+    public void notifyOrder1(Long orderId, PayMethod payMethod, String transactionId) {
         Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
         Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
         Collection collection = collectionRepo.findById(order.getCollectionId())
         Collection collection = collectionRepo.findById(order.getCollectionId())
                 .orElseThrow(new BusinessException("藏品不存在"));
                 .orElseThrow(new BusinessException("藏品不存在"));
@@ -294,7 +295,41 @@ public class OrderService {
                 order.setTransactionId(transactionId);
                 order.setTransactionId(transactionId);
                 order.setPayMethod(payMethod);
                 order.setPayMethod(payMethod);
                 orderRepo.save(order);
                 orderRepo.save(order);
-                Asset asset = assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售");
+                assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售");
+            } else {
+                if (collection.getSource() == CollectionSource.TRANSFER) {
+                    Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
+                    assetService.transfer(asset, user);
+                    collectionRepo.delete(collection);
+                } else {
+                    order.setStatus(OrderStatus.PROCESSING);
+                    order.setPayTime(LocalDateTime.now());
+                    order.setTransactionId(transactionId);
+                    order.setPayMethod(payMethod);
+                    orderRepo.save(order);
+                    assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售");
+                }
+            }
+        } else if (order.getStatus() == OrderStatus.CANCELLED) {
+        }
+    }
+
+    @Transactional
+    public void notifyOrder(Long orderId, PayMethod payMethod, String transactionId) {
+        Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
+        Collection collection = collectionRepo.findById(order.getCollectionId())
+                .orElseThrow(new BusinessException("藏品不存在"));
+        User user = userRepo.findById(order.getUserId()).orElseThrow(new BusinessException("用户不存在"));
+        if (order.getStatus() == OrderStatus.NOT_PAID) {
+            if (order.getType() == CollectionType.BLIND_BOX) {
+                BlindBoxItem winItem = collectionService.draw(collection.getId());
+
+                order.setStatus(OrderStatus.PROCESSING);
+                order.setPayTime(LocalDateTime.now());
+                order.setTransactionId(transactionId);
+                order.setPayMethod(payMethod);
+                orderRepo.save(order);
+                assetService.createAsset(winItem, user, order.getId(), order.getPrice(), "出售");
             } else {
             } else {
                 if (collection.getSource() == CollectionSource.TRANSFER) {
                 if (collection.getSource() == CollectionSource.TRANSFER) {
                     Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
                     Asset asset = assetRepo.findById(collection.getAssetId()).orElse(null);
@@ -306,7 +341,7 @@ public class OrderService {
                     order.setTransactionId(transactionId);
                     order.setTransactionId(transactionId);
                     order.setPayMethod(payMethod);
                     order.setPayMethod(payMethod);
                     orderRepo.save(order);
                     orderRepo.save(order);
-                    Asset asset = assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售");
+                    assetService.createAsset(collection, user, order.getId(), order.getPrice(), "出售");
                 }
                 }
             }
             }
         } else if (order.getStatus() == OrderStatus.CANCELLED) {
         } else if (order.getStatus() == OrderStatus.CANCELLED) {

+ 3 - 3
src/main/vue/src/views/CollectionEdit.vue

@@ -81,6 +81,9 @@
                             </el-table-column>
                             </el-table-column>
                         </el-table>
                         </el-table>
                     </el-form-item>
                     </el-form-item>
+                    <el-form-item>
+                        <el-button size="mini" @click="addProperty" :disabled="!canEdit"> 添加特性 </el-button>
+                    </el-form-item>
                     <el-form-item label="特权" prop="privileges" style="width: calc(100vw - 450px)">
                     <el-form-item label="特权" prop="privileges" style="width: calc(100vw - 450px)">
                         <el-table :data="privilegeOptions">
                         <el-table :data="privilegeOptions">
                             <el-table-column prop="name" label="可选特权" width="150"></el-table-column>
                             <el-table-column prop="name" label="可选特权" width="150"></el-table-column>
@@ -106,9 +109,6 @@
                             </el-table-column>
                             </el-table-column>
                         </el-table>
                         </el-table>
                     </el-form-item>
                     </el-form-item>
-                    <el-form-item>
-                        <el-button size="mini" @click="addProperty" :disabled="!canEdit"> 添加特性 </el-button>
-                    </el-form-item>
                     <!-- <el-form-item prop="type" label="类型">
                     <!-- <el-form-item prop="type" label="类型">
                         <el-select v-model="formData.type" clearable filterable placeholder="请选择">
                         <el-select v-model="formData.type" clearable filterable placeholder="请选择">
                             <el-option
                             <el-option

+ 48 - 0
src/test/java/com/izouma/nineth/CommonTest.java

@@ -1,5 +1,8 @@
 package com.izouma.nineth;
 package com.izouma.nineth;
 
 
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClient;
+import com.aliyun.oss.model.SetBucketCORSRequest;
 import com.github.kevinsawicki.http.HttpRequest;
 import com.github.kevinsawicki.http.HttpRequest;
 import com.izouma.nineth.config.Constants;
 import com.izouma.nineth.config.Constants;
 import com.izouma.nineth.domain.BaseEntity;
 import com.izouma.nineth.domain.BaseEntity;
@@ -368,4 +371,49 @@ public class CommonTest {
         System.out.println(claims.getSubject());
         System.out.println(claims.getSubject());
         System.out.println(claims.getExpiration());
         System.out.println(claims.getExpiration());
     }
     }
+
+    @Test
+    public void setOSSCORS() {
+        // Endpoint以杭州为例,其它Region请按实际情况填写。
+        String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
+// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号
+        String accessKeyId = "LTAI5tCtRs8DXBLBsn49qRZX";
+        String accessKeySecret = "86uC18LZsfB9JU04BK7ImVXfOytEkG";
+        String bucketName = "9space-2021";
+
+// 创建OSSClient实例。
+        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
+
+        SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName);
+
+// 跨域资源共享规则的容器,每个存储空间最多允许10条规则。
+        ArrayList<SetBucketCORSRequest.CORSRule> putCorsRules = new ArrayList<>();
+
+        SetBucketCORSRequest.CORSRule corRule = new SetBucketCORSRequest.CORSRule();
+
+        ArrayList<String> allowedOrigin = new ArrayList<String>();
+// 指定允许跨域请求的来源。
+        allowedOrigin.add("*");
+
+        ArrayList<String> allowedMethod = new ArrayList<String>();
+        allowedMethod.add("PUT");
+        allowedMethod.add("GET");
+        allowedMethod.add("POST");
+        allowedMethod.add("HEAD");
+
+
+// 指定允许用户从应用程序中访问的响应头。
+// AllowedOrigins和AllowedMethods最多支持一个星号(*)通配符。星号(*)表示允许所有的域来源或者操作。
+        corRule.setAllowedMethods(allowedMethod);
+        corRule.setAllowedOrigins(allowedOrigin);
+
+// 最多允许10条规则。
+        putCorsRules.add(corRule);
+// 已存在的规则将被覆盖。
+        request.setCorsRules(putCorsRules);
+        client.setBucketCORS(request);
+
+// 关闭OSSClient。
+        client.shutdown();
+    }
 }
 }