Java SDK实例程序

更新时间:2020-06-01 21:08:52

JAVA示例程序

AliyunOASClient和ArchiveManager

AliyunOASClient和ArchiveManager分别是低阶接口、高级接口的入口对象,在每个功能中都会使用到它们,为避免实例程序的冗长,将AliyunOASClient和ArchiveManager的创建在这里单独介绍。

注:在本文档中出现的 aliyunOASClient 均是 AliyunOASClient 实例,archiveManager 均是 ArchiveManager实例

AliyunOASClient实例化

  1. // AccessId和AccessKey配置
  2. ServiceCredentials credentials = new ServiceCredentials(
  3. "[yourAccessId]", "[yourAccessKey]");
  4. // 配置客户端设置
  5. ClientConfiguration clientConf = new ClientConfiguration();
  6. // 指定要连接的服务地址
  7. ServiceHost serviceHost = new ServiceHost("http://cn-hangzhou.oas.aliyuncs.com");
  8. // 用OAS工厂获得AliyunOASClient对象
  9. AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
  10. serviceHost, credentials, clientConf);
  1. // 或者像下面这样,通过ServiceCredentials和url直接创建AliyunOASClient对象
  2. AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
  3. credentials, "http://cn-hangzhou.oas.aliyuncs.com");

ArchiveManager实例化

  1. // 使用默认配置
  2. ServiceCredentials credentials = new ServiceCredentials("[yourAccessKeyID]", "[yourAccessKeySecret]");
  3. ArchiveManager manager = OASFactory.archiveManagerFactory(
  4. credentials, "http://cn-hangzhou.oas.aliyuncs.com");
  1. // 自定义配置ClientConfiguration
  2. ServiceCredentials credentials = new ServiceCredentials("[yourAccessKeyID]", "[yourAccessKeySecret]");
  3. // 指定要连接的服务地址
  4. ServiceHost serviceHost = new ServiceHost("http://cn-hangzhou.oas.aliyuncs.com");
  5. // 配置客户端设置
  6. ClientConfiguration clientConf = new ClientConfiguration();
  7. ArchiveManager archiveManager = new ArchiveManager(serviceHost, credentials, clientConf);
  1. // 使用AliyunOASClient初始化
  2. AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
  3. credentials, clientConf).withLogger();
  4. ArchiveManager archiveManager = OASFactory.archiveManagerFactory(aliyunOASClient);

Vault操作

创建Vault

  • 如果指定名称的Vault不存在,则创建Vault;
  • 如果指定名称的Vault已存在,不执行创建动作,返回Vault的信息。
  1. // vaultName必须满足已下2个条件:
  2. // 1. 总长度在3~63之间(包括3和63);
  3. // 2. 只允许包含以下字符:
  4. // 0-9(数字),
  5. // a-z(小写英文字母),
  6. // -(短横线),
  7. // _(下划线)
  8. // 其中 短横线 和 下划线 不能作为vaultName的开头和结尾;
  9. String vaultName = "oas_demo";
  10. // 发送创建vault请求
  11. // 创建Vault的名称,用CreateVaultRequest来指定
  12. CreateVaultRequest createRequest = new CreateVaultRequest().
  13. withVaultName(vaultName);
  14. // 发起创建Vault的请求
  15. // 如果有同名的vault存在,OAS会返回已有的vault的vaultId,而不会执行创建动作
  16. try {
  17. CreateVaultResult result = aliyunOASClient.createVault(createRequest);
  18. logger.info("Vault created vaultId={}", result.getVaultId());
  19. logger.info("Vault created vaultLocation={}", result.getLocation());
  20. } catch (OASClientException e) {
  21. logger.error("OASClientException Occured:", e);
  22. } catch (OASServerException e) {
  23. logger.error("OASServerException Occured:", e);
  24. }

删除Vault

  1. // 删除vault是高危动作,因此只能通过vaultId来删除
  2. DeleteVaultRequest deleteVaultRequest = new DeleteVaultRequest().withVaultId(yourVaultId);
  3. try {
  4. OASResult result = aliyunOASClient.deleteVault(deleteVaultRequest);
  5. logger.info("Delete Success! {} {}", result.getRequestId(), result.getDate());
  6. } catch (OASClientException e) {
  7. logger.error("OASClientException Occured:", e);
  8. } catch (OASServerException e) {
  9. logger.error("OASServerException Occured:", e);
  10. }

上传Archive

快速上传

  • ArchiveManager的upload接口会根据文件大小判断是直接上传还是用Multipart上传,无须用户选择

关于高级接口ArchiveManager的详细文档,参考 OAS Java SDK高级接口文档

  1. // java sdk 会帮助用户完成 vaultName 到 vaultId 的转换
  2. // 由此避免了用户对一长串vaultId的记忆负担
  3. String yourVaultName = "oas_demo";
  4. File file = new File("oas_demo_data/random10M.bin");
  5. try {
  6. UploadResult uploadResult = archiveManager.upload(yourVaultName, file);
  7. logger.info("File {} uploaded complete. ArchiveId={},md5={},treeEtag={}",
  8. file.getAbsolutePath(), uploadResult.getArchiveId(),
  9. uploadResult.getHashValue(),
  10. uploadResult.getHashTreeValue());
  11. } catch (OASClientException e) {
  12. logger.error("OASClientException Occured:", e);
  13. } catch (OASServerException e) {
  14. logger.error("OASServerException Occured:", e);
  15. }

根据UploadId上传

  1. File file = new File("oas_demo_data/random120M-2.bin");
  2. //获得uploadId
  3. //文件大小必须大于100MB,否则会抛异常提示用普通上传接口进行上传
  4. String uploadId = archiveManager.initiateMultipartUpload(vaultName, file, "Hello OAS!");
  5. //如果是已有的uploadId,直接使用之前获取过的uploadId
  6. //String uploadId = "[yourUploadId]";
  7. System.out.println("Get uploadId=" + uploadId);
  8. UploadResult uploadResult = archiveManager.uploadWithUploadId(vaultName, file, uploadId);
  9. System.out.println("Archive ID=" + uploadResult.getArchiveId());

任务执行

下载任务是通过提交任务、下载任务输出的异步过程执行的,任务的详细介绍,参考 OAS Java SDK高级接口文档

提交提档任务

  1. String yourVaultName = "oas_demo";
  2. String yourArchiveId = "6086C62DBFFD4A68BAEE9D1B680EC77C8FE6AE617FF47BCD3DB3CB71AFAE29B33431AED14D06D9C4AD251F17C173F3CD";
  3. JobMonitor jobMonitor = archiveManager.downloadAsync(yourVaultName, yourArchiveId);

执行Inventory

  1. JobMonitor jobMonitor = archiveManager.downloadInventoryAsync("oas_demo");

下载Job输出

  1. archiveManager.downloadJobOutput(yourVaultName, jobId,
  2. new File("oas_demo_data/mySaveFile.bin"));

配置ProcessListener

以上传Archive为例:

  1. ServiceCredentials credentials = new ServiceCredentials(
  2. DemoConstants.ACCESS_ID,
  3. DemoConstants.ACCESS_KEY);
  4. // 通过工厂类获得archiveManager接口
  5. ArchiveManager archiveManager = OASFactory.archiveManagerFactory(credentials);
  6. File file = new File("[pathToYourFile]");
  7. final BaseTransfer<UploadResult> bt = archiveManager.uploadAsync(
  8. "[yourVaultName]", file);
  9. //设置最大并发数,默认为3,最大为10
  10. bt.setNumConcurrence(5);
  11. bt.addProgressListener(new ProgressListener() {
  12. @Override
  13. public void onStart(String id) {
  14. // 任务开始时调用,其中id为Multipart Upload任务ID,对于一般上传任务id为空
  15. System.out.println("Start! Upload ID: " + id);
  16. }
  17. @Override
  18. public boolean onError(Range range, Throwable t) {
  19. // 出错时调用,range是出错的字节范围,t是相应的错误
  20. // 当返回true时,BaseTransfer会进行重试,false则放弃
  21. System.out.println("ERROR!!!");
  22. return false;
  23. }
  24. @Override
  25. public void onCompleted() {
  26. // 任务完成时调用
  27. System.out.println("Upload complete");
  28. }
  29. @Override
  30. public void onProgressed(long current, long total) {
  31. // 上传进度,total为文件字节大小,current为当前已上传字节数
  32. System.out.println("Progress: " + current + " / " + total);
  33. }
  34. });
  35. bt.start();
  36. final Timer timer = new Timer();
  37. timer.scheduleAtFixedRate(new TimerTask() {
  38. @Override
  39. public void run() {
  40. System.out.println("Running time: " + bt.getRunningTime() + " seconds");
  41. System.out.println("Completed size: " + bt.getSizeCompleted() + " bytes");
  42. System.out.println("Total size: " + bt.getSizeTotal() + " bytes");
  43. System.out.println("Average speed: " + bt.getAverageSpeedInBytesPerSecond()
  44. + " B/s");
  45. if (bt.isComplete()) {
  46. timer.cancel();
  47. synchronized (bt) {
  48. bt.notify();
  49. }
  50. }
  51. }
  52. }, 0, 1000);
  53. synchronized (bt) {
  54. try {
  55. bt.wait();
  56. } catch (InterruptedException e) {
  57. logger.error("", e);
  58. }
  59. }
  60. // 任务结束
  61. System.out.println("=============================");
  62. System.out.println("Running time: " + bt.getRunningTime() + " seconds");
  63. System.out.println("Completed size: " + bt.getSizeCompleted() + " bytes");
  64. System.out.println("Total size: " + bt.getSizeTotal() + " bytes");
  65. System.out.println("Average speed: " + bt.getAverageSpeedInBytesPerSecond() + " B/s");
  66. UploadResult uploadResult = bt.getResult();
  67. System.out.println("Archive ID: " + uploadResult.getArchiveId());
  68. System.out.println("Hash Value: " + uploadResult.getHashValue());