Java SDK实例程序
更新时间:
JAVA示例程序
AliyunOASClient和ArchiveManager
AliyunOASClient和ArchiveManager分别是低阶接口、高级接口的入口对象,在每个功能中都会使用到它们,为避免实例程序的冗长,将AliyunOASClient和ArchiveManager的创建在这里单独介绍。
注:在本文档中出现的 aliyunOASClient 均是 AliyunOASClient 实例,archiveManager 均是 ArchiveManager实例
AliyunOASClient实例化
// AccessId和AccessKey配置
ServiceCredentials credentials = new ServiceCredentials(
"[yourAccessId]", "[yourAccessKey]");
// 配置客户端设置
ClientConfiguration clientConf = new ClientConfiguration();
// 指定要连接的服务地址
ServiceHost serviceHost = new ServiceHost("http://cn-hangzhou.oas.aliyuncs.com");
// 用OAS工厂获得AliyunOASClient对象
AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
serviceHost, credentials, clientConf);
// 或者像下面这样,通过ServiceCredentials和url直接创建AliyunOASClient对象
AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
credentials, "http://cn-hangzhou.oas.aliyuncs.com");
ArchiveManager实例化
// 使用默认配置
ServiceCredentials credentials = new ServiceCredentials("[yourAccessKeyID]", "[yourAccessKeySecret]");
ArchiveManager manager = OASFactory.archiveManagerFactory(
credentials, "http://cn-hangzhou.oas.aliyuncs.com");
// 自定义配置ClientConfiguration
ServiceCredentials credentials = new ServiceCredentials("[yourAccessKeyID]", "[yourAccessKeySecret]");
// 指定要连接的服务地址
ServiceHost serviceHost = new ServiceHost("http://cn-hangzhou.oas.aliyuncs.com");
// 配置客户端设置
ClientConfiguration clientConf = new ClientConfiguration();
ArchiveManager archiveManager = new ArchiveManager(serviceHost, credentials, clientConf);
// 使用AliyunOASClient初始化
AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
credentials, clientConf).withLogger();
ArchiveManager archiveManager = OASFactory.archiveManagerFactory(aliyunOASClient);
Vault操作
创建Vault
- 如果指定名称的Vault不存在,则创建Vault;
- 如果指定名称的Vault已存在,不执行创建动作,返回Vault的信息。
// vaultName必须满足已下2个条件:
// 1. 总长度在3~63之间(包括3和63);
// 2. 只允许包含以下字符:
// 0-9(数字),
// a-z(小写英文字母),
// -(短横线),
// _(下划线)
// 其中 短横线 和 下划线 不能作为vaultName的开头和结尾;
String vaultName = "oas_demo";
// 发送创建vault请求
// 创建Vault的名称,用CreateVaultRequest来指定
CreateVaultRequest createRequest = new CreateVaultRequest().
withVaultName(vaultName);
// 发起创建Vault的请求
// 如果有同名的vault存在,OAS会返回已有的vault的vaultId,而不会执行创建动作
try {
CreateVaultResult result = aliyunOASClient.createVault(createRequest);
logger.info("Vault created vaultId={}", result.getVaultId());
logger.info("Vault created vaultLocation={}", result.getLocation());
} catch (OASClientException e) {
logger.error("OASClientException Occured:", e);
} catch (OASServerException e) {
logger.error("OASServerException Occured:", e);
}
删除Vault
// 删除vault是高危动作,因此只能通过vaultId来删除
DeleteVaultRequest deleteVaultRequest = new DeleteVaultRequest().withVaultId(yourVaultId);
try {
OASResult result = aliyunOASClient.deleteVault(deleteVaultRequest);
logger.info("Delete Success! {} {}", result.getRequestId(), result.getDate());
} catch (OASClientException e) {
logger.error("OASClientException Occured:", e);
} catch (OASServerException e) {
logger.error("OASServerException Occured:", e);
}
上传Archive
快速上传
- ArchiveManager的upload接口会根据文件大小判断是直接上传还是用Multipart上传,无须用户选择
关于高级接口ArchiveManager的详细文档,参考 OAS Java SDK高级接口文档 。
// java sdk 会帮助用户完成 vaultName 到 vaultId 的转换
// 由此避免了用户对一长串vaultId的记忆负担
String yourVaultName = "oas_demo";
File file = new File("oas_demo_data/random10M.bin");
try {
UploadResult uploadResult = archiveManager.upload(yourVaultName, file);
logger.info("File {} uploaded complete. ArchiveId={},md5={},treeEtag={}",
file.getAbsolutePath(), uploadResult.getArchiveId(),
uploadResult.getHashValue(),
uploadResult.getHashTreeValue());
} catch (OASClientException e) {
logger.error("OASClientException Occured:", e);
} catch (OASServerException e) {
logger.error("OASServerException Occured:", e);
}
根据UploadId上传
File file = new File("oas_demo_data/random120M-2.bin");
//获得uploadId
//文件大小必须大于100MB,否则会抛异常提示用普通上传接口进行上传
String uploadId = archiveManager.initiateMultipartUpload(vaultName, file, "Hello OAS!");
//如果是已有的uploadId,直接使用之前获取过的uploadId
//String uploadId = "[yourUploadId]";
System.out.println("Get uploadId=" + uploadId);
UploadResult uploadResult = archiveManager.uploadWithUploadId(vaultName, file, uploadId);
System.out.println("Archive ID=" + uploadResult.getArchiveId());
任务执行
下载任务是通过提交任务、下载任务输出的异步过程执行的,任务的详细介绍,参考 OAS Java SDK高级接口文档。
提交提档任务
String yourVaultName = "oas_demo";
String yourArchiveId = "6086C62DBFFD4A68BAEE9D1B680EC77C8FE6AE617FF47BCD3DB3CB71AFAE29B33431AED14D06D9C4AD251F17C173F3CD";
JobMonitor jobMonitor = archiveManager.downloadAsync(yourVaultName, yourArchiveId);
执行Inventory
JobMonitor jobMonitor = archiveManager.downloadInventoryAsync("oas_demo");
下载Job输出
archiveManager.downloadJobOutput(yourVaultName, jobId,
new File("oas_demo_data/mySaveFile.bin"));
配置ProcessListener
以上传Archive为例:
ServiceCredentials credentials = new ServiceCredentials(
DemoConstants.ACCESS_ID,
DemoConstants.ACCESS_KEY);
// 通过工厂类获得archiveManager接口
ArchiveManager archiveManager = OASFactory.archiveManagerFactory(credentials);
File file = new File("[pathToYourFile]");
final BaseTransfer<UploadResult> bt = archiveManager.uploadAsync(
"[yourVaultName]", file);
//设置最大并发数,默认为3,最大为10
bt.setNumConcurrence(5);
bt.addProgressListener(new ProgressListener() {
@Override
public void onStart(String id) {
// 任务开始时调用,其中id为Multipart Upload任务ID,对于一般上传任务id为空
System.out.println("Start! Upload ID: " + id);
}
@Override
public boolean onError(Range range, Throwable t) {
// 出错时调用,range是出错的字节范围,t是相应的错误
// 当返回true时,BaseTransfer会进行重试,false则放弃
System.out.println("ERROR!!!");
return false;
}
@Override
public void onCompleted() {
// 任务完成时调用
System.out.println("Upload complete");
}
@Override
public void onProgressed(long current, long total) {
// 上传进度,total为文件字节大小,current为当前已上传字节数
System.out.println("Progress: " + current + " / " + total);
}
});
bt.start();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("Running time: " + bt.getRunningTime() + " seconds");
System.out.println("Completed size: " + bt.getSizeCompleted() + " bytes");
System.out.println("Total size: " + bt.getSizeTotal() + " bytes");
System.out.println("Average speed: " + bt.getAverageSpeedInBytesPerSecond()
+ " B/s");
if (bt.isComplete()) {
timer.cancel();
synchronized (bt) {
bt.notify();
}
}
}
}, 0, 1000);
synchronized (bt) {
try {
bt.wait();
} catch (InterruptedException e) {
logger.error("", e);
}
}
// 任务结束
System.out.println("=============================");
System.out.println("Running time: " + bt.getRunningTime() + " seconds");
System.out.println("Completed size: " + bt.getSizeCompleted() + " bytes");
System.out.println("Total size: " + bt.getSizeTotal() + " bytes");
System.out.println("Average speed: " + bt.getAverageSpeedInBytesPerSecond() + " B/s");
UploadResult uploadResult = bt.getResult();
System.out.println("Archive ID: " + uploadResult.getArchiveId());
System.out.println("Hash Value: " + uploadResult.getHashValue());
文档内容是否对您有帮助?