Java V2
IBM Cloud® Object Storage SDK for Java v2 は、 IBM Cloud Object Storage を最大限に活用するための機能を提供する。
IBM Cloud Object Storage SDK for Java v2 は包括的なものであり、本ガイドの範囲とスペースを超える多くの特徴と機能を備えている。 クラスとメソッドの詳細については、 Java API リファレンス・ドキュメントを 参照してください。 ソース・コードは、GitHub リポジトリーにあります。
新着情報 v2
IBM Cloud Object Storage SDK for Java v2 は、 AWS SDK v2 アーキテクチャ上に構築された近代化バージョンで、大幅な改良が加えられている:
- 不変ビルダー :すべてのリクエストおよびレスポンスオブジェクトは、スレッドセーフを向上させるため、イミュータブルビルダーパターンを使用します
- モダンなパッケージ構造 :新しい名前空間
com.ibm.cos.v2.*によるすっきりとした構成 - 非同期サポートの強化 :ノンブロッキング操作のための
S3AsyncClientの導入 - ストリーミングの改善 :ストリーミングAPIが改良され、
RequestBodyResponseTransformer - 自動IAMトークン管理 :SDKがIAMトークンのリフレッシュを自動的に処理
- 型の安全性 :ビルダーによるコンパイル時の型チェックの強化
- モダンな HTTP スタック : Apache HTTP クライアントと Netty の非同期操作のサポート
v1 から移行する開発者については、 移行ガイドを 参照してください。
SDK の取得
IBM Cloud Object Storage Java SDK v2 を使用する最も簡単な方法は、Maven を使用して依存関係を管理することです。 Mavenに慣れていない場合は、 Maven in 5-Minutes ガイドを使えばすぐに使い始めることができる。
Maven は、Java プロジェクトに必要なライブラリー (およびライブラリーのバージョン) を指定するために pom.xml というファイルを使用します。 以下は、 IBM Cloud Object Storage Java SDK v2 を使って Object Storage に接続するための pom.xml ファイルの例である。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cos</groupId>
<artifactId>docs</artifactId>
<packaging>jar</packaging>
<version>2.0-SNAPSHOT</version>
<name>docs</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>com.ibm.cos.v2</groupId>
<artifactId>cos-java-sdk</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
</project>
SDKリファレンス
コア・クラス
- S3Client- 同期 S3 クライアント
- S3AsyncClient- 非同期 S3 クライアント
- S3ClientBuilder- S3 クライアント用ビルダー
資格情報
- AwsCredentials- ベース・クレデンシャル・インターフェイス
- BasicIBMOAuthCredentials- IBM IAM資格情報
- AwsBasicCredentials- HMAC認証情報
- StaticCredentialsProvider- 静的資格情報プロバイダ
- AwsCredentialsProvider- クレデンシャル・プロバイダー・インターフェイス
構成
- 地域- AWS 地域代表
- ClientOverrideConfiguration- クライアント設定のオーバーライド
- S3Configuration- S3-specific 構成
ストリーミング
- RequestBody- アップロードのリクエストボディ
- ResponseTransformer- ダウンロード用レスポンス・トランス
- ResponseInputStream- 入力ストリームのレスポンス
例外
- S3Exception- ベース S3 例外
- NoSuchBucketException- バケットが見つかりません
- NoSuchKeyException- オブジェクトが見つかりません
- SdkClientException- クライアント側の例外
クライアントの作成と資格情報の入手
以下の例では、資格情報 (API キーとサービス・インスタンス ID) を指定することによりクライアント cos が作成および構成されます。 これらの値は、資格情報ファイルまたは環境変数から自動的に入手することもできます。
サービス資格情報を生成した後は、結果の JSON 文書を ~/.bluemix/cos_credentials に保存できます。 クライアントの作成時に他の資格情報が明示的に設定されない限り、SDK は、このファイルから資格情報を自動的に入手します。
cos_credentials ファイルに HMAC 鍵が含まれている場合、クライアントは署名を使用して認証を受けます。そうでない場合、クライアントはベアラー・トークンと提供される API キーを使用して認証を受けます。
AWS S3 からマイグレーションする場合は、~/.aws/credentials から資格情報データを以下の形式で入手することもできます。
[default]
aws_access_key_id = {API_KEY}
aws_secret_access_key = {SERVICE_INSTANCE_ID}
~/.bluemix/cos_credentials と ~/.aws/credentials の両方が存在する場合は、cos_credentials が優先されます。
クライアント構築の詳細については、 Java APIリファレンス・ドキュメントを 参照のこと。
コード例
まず、基本的な機能を実行する完全なサンプル・クラスから始めよう。 この CosExample クラスは、既存のバケツ内のオブジェクトを一覧表示し、新しいバケツを作成し、サービスインスタンス内のすべてのバケツを一覧表示します。
必要な情報の収集
bucketNameとnewBucketNameは、固有かつ DNS セーフのストリングです。 バケット名はシステム全体で固有であるため、この例を複数回実行する場合は、これらの値を変更する必要があります。 名前は削除後10~15分間予約される。apiKeyは、apikeyとして サービスクレデンシャルの 値である。serviceInstanceIdは、resource_instance_idとして サービスクレデンシャルの 値である。endpointUrlはサービスエンドポイント URL であり、https://プロトコルを含む。 これは サービスクレデンシャルのendpoints値ではない。 エンドポイントについて詳しくは、エンドポイントおよびストレージ・ロケーションを参照してください。locationは、storageClassのロケーション部分に設定しなければならない。us-south-standardの場合、これはus-southになります。 この変数は、HMAC 署名の計算のみに使用されますが、IAM API キーを使用するこのサンプルも含め、あらゆるクライアントに必要です。
package com.cos;
import java.net.URI;
import java.util.List;
import com.ibm.cos.v2.auth.credentials.AwsCredentials;
import com.ibm.cos.v2.auth.credentials.StaticCredentialsProvider;
import com.ibm.cos.v2.auth.credentials.ibmOAuth.BasicIBMOAuthCredentials;
import com.ibm.cos.v2.regions.Region;
import com.ibm.cos.v2.services.s3.S3Client;
import com.ibm.cos.v2.services.s3.model.*;
public class CosExample {
private static String COS_ENDPOINT = "<endpoint>";
private static String COS_API_KEY_ID = "<api-key>";
private static String COS_SERVICE_INSTANCE_ID = "<service-instance-id>";
private static String COS_LOCATION = "<location>";
public static void main(String[] args) {
System.out.println("Current time: " + new java.util.Date());
// Create IBM COS credentials using API key
AwsCredentials credentials = new BasicIBMOAuthCredentials(COS_API_KEY_ID, COS_SERVICE_INSTANCE_ID);
// Create the S3 client
S3Client cosClient = S3Client.builder()
.endpointOverride(URI.create(COS_ENDPOINT))
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.region(Region.of(COS_LOCATION))
.build();
listObjects("my-bucket", cosClient);
createBucket("my-new-bucket", cosClient);
listBuckets(cosClient);
cosClient.close();
}
public static void listObjects(String bucketName, S3Client cosClient) {
System.out.println("Listing objects in bucket: " + bucketName);
ListObjectsV2Request request = ListObjectsV2Request.builder()
.bucket(bucketName)
.build();
ListObjectsV2Response response = cosClient.listObjectsV2(request);
List<S3Object> objects = response.contents();
for (S3Object object : objects) {
System.out.println("Item: " + object.key() + " (" + object.size() + " bytes)");
}
}
public static void createBucket(String bucketName, S3Client cosClient) {
System.out.println("Creating bucket: " + bucketName);
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket(bucketName)
.build();
cosClient.createBucket(request);
System.out.println("Bucket created: " + bucketName);
}
public static void listBuckets(S3Client cosClient) {
System.out.println("Listing buckets:");
ListBucketsResponse response = cosClient.listBuckets();
List<Bucket> buckets = response.buckets();
for (Bucket bucket : buckets) {
System.out.println("Bucket Name: " + bucket.name());
}
}
}
主な参考文献
エンドポイントの決定
エンドポイントについて詳しくは、エンドポイントおよびストレージ・ロケーションを参照してください。
エンドポイントはこのパターンに従う: https://s3.{region}.cloud-object-storage.appdomain.cloud
例:
- 米国南部:
https://s3.us-south.cloud-object-storage.appdomain.cloud - 米国東部:
https://s3.us-east.cloud-object-storage.appdomain.cloud - EU イギリス
https://s3.eu-gb.cloud-object-storage.appdomain.cloud
新規バケットの作成
public static void createBucket(String bucketName, S3Client cosClient) {
System.out.println("Creating new bucket: " + bucketName);
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket(bucketName)
.build();
cosClient.createBucket(request);
System.out.println("Bucket: " + bucketName + " created!");
}
キー参照
異なるストレージ・クラスを使用するバケットの作成
public static void createBucketWithStorageClass(String bucketName, String storageClass, String location, S3Client cosClient) {
System.out.println("Creating bucket: " + bucketName + " with storage class: " + storageClass);
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket(bucketName)
.ibmServiceInstanceId(COS_SERVICE_INSTANCE_ID)
.build();
cosClient.createBucket(request);
System.out.println("Bucket: " + bucketName + " created with " + storageClass + " class storage!");
}
ストレージクラスのオプションは以下の通り:
us-south-standard/us-east-standard/eu-gb-standard- 標準ストレージus-south-vault/us-east-vault/eu-gb-vault- 保管庫us-south-cold/us-east-cold/eu-gb-cold- 低温保管庫us-south-flex/us-east-flex/eu-gb-flex- フレックス・ストレージ
キー参照
新規テキスト・ファイルの作成
public static void createTextFile(String bucketName, String itemName, String fileText, S3Client cosClient) {
System.out.println("Creating new item: " + itemName);
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(itemName)
.build();
cosClient.putObject(request, RequestBody.fromString(fileText));
System.out.println("Item: " + itemName + " created!");
}
主な参考文献
オブジェクトをファイルからアップロード
public static void putObject(String bucketName, String itemName, String filePath, S3Client cosClient) {
System.out.println("Creating new item: " + itemName);
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(itemName)
.build();
cosClient.putObject(request, RequestBody.fromFile(new File(filePath)));
System.out.println("Item: " + itemName + " created!");
}
主な参考文献
ストリームを使用したオブジェクトのアップロード
public static void putObjectStream(String bucketName, String itemName, InputStream inputStream, long contentLength, S3Client cosClient) {
System.out.println("Creating new item: " + itemName + " from input stream");
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(itemName)
.contentLength(contentLength)
.build();
cosClient.putObject(request, RequestBody.fromInputStream(inputStream, contentLength));
System.out.println("Item: " + itemName + " created!");
}
主な参考文献
ファイルへのオブジェクトのダウンロード
public static void getObject(String bucketName, String itemName, String filePath, S3Client cosClient) {
System.out.println("Retrieving item: " + itemName);
GetObjectRequest request = GetObjectRequest.builder()
.bucket(bucketName)
.key(itemName)
.build();
cosClient.getObject(request, ResponseTransformer.toFile(new File(filePath)));
System.out.println("Item: " + itemName + " downloaded to: " + filePath);
}
主な参考文献
ストリームを使用したオブジェクトのダウンロード
public static void getObjectStream(String bucketName, String itemName, S3Client cosClient) {
System.out.println("Retrieving item: " + itemName + " as stream");
GetObjectRequest request = GetObjectRequest.builder()
.bucket(bucketName)
.key(itemName)
.build();
ResponseInputStream<GetObjectResponse> response = cosClient.getObject(request);
try (InputStream inputStream = response) {
// Process the input stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// Process bytes
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.err.println("Error reading object: " + e.getMessage());
}
System.out.println("\nItem: " + itemName + " retrieved!");
}
主な参考文献
オブジェクトのコピー
public static void copyObject(String sourceBucketName, String sourceKey, String destinationBucketName, String destinationKey, S3Client cosClient) {
System.out.println("Copying item: " + sourceKey + " from bucket: " + sourceBucketName +
" to: " + destinationKey + " in bucket: " + destinationBucketName);
CopyObjectRequest request = CopyObjectRequest.builder()
.sourceBucket(sourceBucketName)
.sourceKey(sourceKey)
.destinationBucket(destinationBucketName)
.destinationKey(destinationKey)
.build();
cosClient.copyObject(request);
System.out.println("Item: " + sourceKey + " copied!");
}
主な参考文献
使用可能なバケットのリスト
public static void listBuckets(S3Client cosClient) {
System.out.println("Listing buckets:");
ListBucketsResponse response = cosClient.listBuckets();
List<Bucket> buckets = response.buckets();
for (Bucket bucket : buckets) {
System.out.println("Bucket Name: " + bucket.name());
}
}
主な参考文献
特定の項目のファイル内容の取得
public static void getItem(String bucketName, String itemName, S3Client cosClient) {
System.out.println("Retrieving item: " + itemName);
GetObjectRequest request = GetObjectRequest.builder()
.bucket(bucketName)
.key(itemName)
.build();
ResponseInputStream<GetObjectResponse> response = cosClient.getObject(request);
try {
String content = new String(response.readAllBytes(), StandardCharsets.UTF_8);
System.out.println("File Contents:\n" + content);
} catch (IOException e) {
System.err.println("Error reading object: " + e.getMessage());
}
}
主な参考文献
バケットから項目を削除
public static void deleteItem(String bucketName, String itemName, S3Client cosClient) {
System.out.println("Deleting item: " + itemName);
DeleteObjectRequest request = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(itemName)
.build();
cosClient.deleteObject(request);
System.out.println("Item: " + itemName + " deleted!");
}
主な参考文献
バケットから複数項目を削除
public static void deleteMultipleItems(String bucketName, List<String> itemNames, S3Client cosClient) {
System.out.println("Deleting multiple items from bucket: " + bucketName);
List<ObjectIdentifier> objectsToDelete = itemNames.stream()
.map(key -> ObjectIdentifier.builder().key(key).build())
.collect(Collectors.toList());
Delete delete = Delete.builder()
.objects(objectsToDelete)
.build();
DeleteObjectsRequest request = DeleteObjectsRequest.builder()
.bucket(bucketName)
.delete(delete)
.build();
DeleteObjectsResponse response = cosClient.deleteObjects(request);
System.out.println("Deleted " + response.deleted().size() + " items!");
}
主な参考文献
バケットの削除
バケツを削除するには、バケツが空でなければなりません。
public static void deleteBucket(String bucketName, S3Client cosClient) {
System.out.println("Deleting bucket: " + bucketName);
DeleteBucketRequest request = DeleteBucketRequest.builder()
.bucket(bucketName)
.build();
cosClient.deleteBucket(request);
System.out.println("Bucket: " + bucketName + " deleted!");
}
主な参考文献
オブジェクトがパブリックに読み取り可能かどうかのチェック
public static boolean isObjectPubliclyReadable(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Checking if object is publicly readable: " + objectKey);
try {
GetObjectAclRequest request = GetObjectAclRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
GetObjectAclResponse response = cosClient.getObjectAcl(request);
for (Grant grant : response.grants()) {
if (grant.grantee().type() == Type.GROUP &&
grant.grantee().uri() != null &&
grant.grantee().uri().contains("AllUsers") &&
grant.permission() == Permission.READ) {
System.out.println("Object is publicly readable");
return true;
}
}
System.out.println("Object is not publicly readable");
return false;
} catch (S3Exception e) {
System.err.println("Error checking object ACL: " + e.getMessage());
return false;
}
}
主な参考文献
複数パーツ・アップロードの実行
大きなオブジェクトを処理する場合、マルチパート・アップロード操作でオブジェクトを IBM Cloud Object Storage に書き込むことをお勧めします。 単一オブジェクトのアップロードは一連のパーツとして実行でき、これらのパーツは任意の順序で並行して個別にアップロードできます。 アップロードが完了した時点で、IBM Cloud Object Storage はすべてのパーツを単一オブジェクトとして表します。
複数パーツ・アップロードは、5 MB を超えるオブジェクトに対してのみ使用可能です。 50 GB より小さいオブジェクトの場合、最適なパフォーマンスを得るため、パートのサイズとして 20 MB から 100 MB が推奨されます。 それより大きいオブジェクトの場合、パーツのサイズを増やしてもパフォーマンスへの大きな影響はありません。
public static void multipartUpload(String bucketName, String itemName, String filePath, S3Client cosClient) {
System.out.println("Starting multipart upload for: " + itemName);
// Step 1: Initiate multipart upload
CreateMultipartUploadRequest initiateRequest = CreateMultipartUploadRequest.builder()
.bucket(bucketName)
.key(itemName)
.build();
CreateMultipartUploadResponse initiateResponse = cosClient.createMultipartUpload(initiateRequest);
String uploadId = initiateResponse.uploadId();
System.out.println("Upload ID: " + uploadId);
// Step 2: Upload parts
int partNumber = 1;
List<CompletedPart> completedParts = new ArrayList<>();
ByteBuffer buffer = ByteBuffer.allocate(5 * 1024 * 1024); // 5 MB parts
try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
long fileSize = file.length();
long position = 0;
while (position < fileSize) {
file.seek(position);
long bytesRead = file.getChannel().read(buffer);
buffer.flip();
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(bucketName)
.key(itemName)
.uploadId(uploadId)
.partNumber(partNumber)
.build();
UploadPartResponse partResponse = cosClient.uploadPart(
uploadPartRequest,
RequestBody.fromByteBuffer(buffer)
);
CompletedPart part = CompletedPart.builder()
.partNumber(partNumber)
.eTag(partResponse.eTag())
.build();
completedParts.add(part);
System.out.println("Uploaded part " + partNumber);
buffer.clear();
position += bytesRead;
partNumber++;
}
} catch (IOException e) {
System.err.println("Error during multipart upload: " + e.getMessage());
// Abort the multipart upload on error
AbortMultipartUploadRequest abortRequest = AbortMultipartUploadRequest.builder()
.bucket(bucketName)
.key(itemName)
.uploadId(uploadId)
.build();
cosClient.abortMultipartUpload(abortRequest);
return;
}
// Step 3: Complete multipart upload
CompletedMultipartUpload completedUpload = CompletedMultipartUpload.builder()
.parts(completedParts)
.build();
CompleteMultipartUploadRequest completeRequest = CompleteMultipartUploadRequest.builder()
.bucket(bucketName)
.key(itemName)
.uploadId(uploadId)
.multipartUpload(completedUpload)
.build();
cosClient.completeMultipartUpload(completeRequest);
System.out.println("Multipart upload completed for: " + itemName);
}
主な参考文献
Immutable Object Storage の使用
ユーザは、Immutable Object Storage ポリシーでバケットを設定し、オブジェクトが定義された期間変更または削除されないようにすることができます。 保存期間は、オブジェクトごとに指定することもできますし、バケツに設定されたデフォルトの保存期間をオブジェクトに継承させることもできます。
バケツに保護設定を追加する
PUT 操作のこの実装では、protection 照会パラメーターを使用して、既存のバケットに保存パラメーターを設定します。 この操作により、保存期間の最小、デフォルト、および最大を設定または変更できます。 また、この操作により、バケットの保護状態を変更することもできます。
保護対象のバケットに書き込まれたオブジェクトは、保護期間が満了し、オブジェクトに対するすべての法的保留が解除されるまで削除できません。 オブジェクトの作成時にオブジェクト固有の値が指定されない限り、バケットのデフォルトの保存期間値がオブジェクトにも適用されます。 保護されたバケツ内のオブジェクトで、もはや保持対象ではないもの(保持期間が終了し、オブジェクトに法的なホールドがないもの)は、上書きされると再び保持対象となります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。
保持期間設定 MinimumRetention、 DefaultRetention、 MaximumRetention の最小および最大サポート値は、最小0日、最大365243日(1000年)である。
public static void addProtectionConfigurationToBucket(String bucketName, S3Client cosClient) {
System.out.println("Adding protection configuration to bucket: " + bucketName);
BucketProtectionConfiguration protectionConfig = BucketProtectionConfiguration.builder()
.status(BucketProtectionStatus.RETENTION)
.minimumRetention(BucketProtectionMinimumRetention.builder()
.days(10)
.build())
.defaultRetention(BucketProtectionDefaultRetention.builder()
.days(100)
.build())
.maximumRetention(BucketProtectionMaximumRetention.builder()
.days(1000)
.build())
.build();
PutBucketProtectionConfigurationRequest request = PutBucketProtectionConfigurationRequest.builder()
.bucket(bucketName)
.protectionConfiguration(protectionConfig)
.build();
cosClient.putBucketProtectionConfiguration(request);
System.out.println("Protection configuration added!");
}
バケツの保護設定を取得する
public static void getProtectionConfigurationOnBucket(String bucketName, S3Client cosClient) {
System.out.println("Retrieving protection configuration for bucket: " + bucketName);
GetBucketProtectionConfigurationRequest request = GetBucketProtectionConfigurationRequest.builder()
.bucket(bucketName)
.build();
GetBucketProtectionConfigurationResponse response = cosClient.getBucketProtectionConfiguration(request);
System.out.println("Status: " + response.status());
System.out.println("Minimum Retention (days): " + response.minimumRetention().days());
System.out.println("Default Retention (days): " + response.defaultRetention().days());
System.out.println("Maximum Retention (days): " + response.maximumRetention().days());
}
リテンション付き保護オブジェクトのアップロード
保護されたバケツ内のオブジェクトで、もはや保持対象ではないもの(保持期間が終了し、オブジェクトに法的なホールドがないもの)は、上書きされると再び保持対象となります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。
保護されたバケットにオブジェクトをアップロードする際に、カスタムヘッダを使用して保持パラメータを指定することができます:
| ヘッダー | タイプ | 説明 |
|---|---|---|
Retention-Period |
非負整数(秒) | オブジェクトを保管する保存期間 (秒数)。 オブジェクトは、保存期間に指定された時間が経過するまで上書きも削除もできません。 このフィールドと Retention-Expiration-Date が指定された場合、400エラーが返される。 いずれも指定されない場合は、バケットの DefaultRetention 期間が使用されます。 ゼロ(0)は、バケツの最小保存期間も0であると仮定した場合の合法的な値である。 |
Retention-Expiration-Date |
日付 (ISO 8601 フォーマット) | オブジェクトの削除や変更が合法となる日付。 指定できるのは、このヘッダーか Retention-Period。 両方が指定された場合、400エラーが返される。 いずれも指定されない場合は、バケットの DefaultRetention 期間が使用されます。 |
Retention-Legal-Hold-Id |
ストリング | オブジェクトに適用される単一の法的保留。 リーガル・ホールドはY文字の長い文字列である。 オブジェクトに関連付けられたすべての法的保留が解除されるまで、オブジェクトは上書きも削除もできません。 |
public static void uploadProtectedObject(String bucketName, String objectKey, String filePath, S3Client cosClient) {
System.out.println("Uploading protected object with retention: " + objectKey);
// Option 1: Upload with retention period (in seconds)
PutObjectRequest requestWithPeriod = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.retentionPeriod(2592000L) // 30 days in seconds
.build();
cosClient.putObject(requestWithPeriod, RequestBody.fromFile(new File(filePath)));
System.out.println("Object uploaded with 30-day retention period");
}
public static void uploadProtectedObjectWithExpirationDate(String bucketName, String objectKey, String filePath, S3Client cosClient) {
System.out.println("Uploading protected object with expiration date: " + objectKey);
// Option 2: Upload with retention expiration date
Instant expirationDate = Instant.now().plus(90, ChronoUnit.DAYS);
PutObjectRequest requestWithDate = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.retentionExpirationDate(expirationDate)
.build();
cosClient.putObject(requestWithDate, RequestBody.fromFile(new File(filePath)));
System.out.println("Object uploaded with expiration date: " + expirationDate);
}
public static void uploadProtectedObjectWithLegalHold(String bucketName, String objectKey, String filePath, String legalHoldId, S3Client cosClient) {
System.out.println("Uploading protected object with legal hold: " + objectKey);
// Option 3: Upload with legal hold
PutObjectRequest requestWithLegalHold = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.retentionLegalHoldId(legalHoldId)
.build();
cosClient.putObject(requestWithLegalHold, RequestBody.fromFile(new File(filePath)));
System.out.println("Object uploaded with legal hold: " + legalHoldId);
}
public static void uploadProtectedObjectWithMultipleRetentionOptions(String bucketName, String objectKey, String filePath, String legalHoldId, S3Client cosClient) {
System.out.println("Uploading protected object with retention period and legal hold: " + objectKey);
// Option 4: Combine retention period with legal hold
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.retentionPeriod(2592000L) // 30 days
.retentionLegalHoldId(legalHoldId)
.build();
cosClient.putObject(request, RequestBody.fromFile(new File(filePath)));
System.out.println("Object uploaded with retention and legal hold");
}
重要なメモ:
- 同じリクエストで
Retention-PeriodとRetention-Expiration-Dateの両方を指定することはできない。 - どちらの保持パラメータも指定されていない場合、バケツのデフォルトの保持期間が適用されます。
- リーガル・ホールドは保存期間と組み合わせることができる。
- 保存期間中のオブジェクトやリーガル・ホールドが設定されているオブジェクトは、保存期間が終了し、リーガル・ホールドがすべて削除されるまで、削除や上書きができません。
主な参考文献
保護されたオブジェクトに法的ホールドを追加する
オブジェクトがサポートできる法的保留は 100 個です。
正規のホールド識別子は、最大64文字、最小1文字の文字列である。 有効な文字は英字、数字、 !、 _、 .、 *、 (、 )、 -、 '。 指定された法的保留を追加することで、オブジェクトに対する法的保留の合計数が 100 個を超える場合、新しい法的保留は追加されず、400 エラーが返されます。 識別子が長すぎる場合はオブジェクトに追加されず、 400 エラーが返される。 ID に無効文字が含まれている場合、ID はオブジェクトに追加されず、400 エラーが返されます。 ID がオブジェクトで既に使用中の場合、既存の法的保留は変更されず、ID が既に使用中であることを示す応答と 409 エラーが返されます。 オブジェクトに保存期間メタデータがない場合は、
400 エラーが返され、法的保留の追加または削除は許可されません。 保存期間ヘッダーが存在する必要があります。存在しない場合は、
400 エラーが返されます。
法的保留の追加または削除を行うユーザーには、このバケットに対するManager許可が必要です。
public static void addLegalHoldToObject(String bucketName, String objectKey, String legalHoldId, S3Client cosClient) {
System.out.println("Adding legal hold to object: " + objectKey);
AddLegalHoldRequest request = AddLegalHoldRequest.builder()
.bucket(bucketName)
.key(objectKey)
.legalHoldId(legalHoldId)
.build();
cosClient.addLegalHold(request);
System.out.println("Legal hold added!");
}
保護対象の保存期間の延長
オブジェクトの保存期間は延長のみが可能です。 現在構成されている値から減らすことはできません。
保存延長値は次の 3 つの方法のいずれかで設定されます。
- 現在値からの追加時間 (
additionalRetentionPeriodまたは同様の方法) - 新しい延長期間(秒 ) (
extendRetentionFromCurrentTimeまたは同様の方法) - オブジェクトの新しい保持期限 (
newRetentionExpirationDateまたは同様の方法)
オブジェクト・メタデータに保管されている現在の保存期間は、extendRetention 要求に設定されているパラメーターに応じて、指定された追加時間分増やされるか、新しい値に置き換えられます。 すべての場合において、拡張された保持パラメータは現在の保持期間と照合され、更新された保持期間が現在の保持期間より大きい場合にのみ、拡張パラメータが受け入れられる。
保護されたバケツ内のオブジェクトで、もはや保持対象ではないもの(保持期間が終了し、オブジェクトに法的なホールドがないもの)は、上書きされると再び保持対象となります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。
public static void extendRetentionPeriodOnObject(String bucketName, String objectName, Long additionalSeconds, S3Client cosClient) {
System.out.printf("Extending the retention period on %s in bucket %s by %s seconds.%n", objectName, bucketName, additionalSeconds);
ExtendObjectRetentionRequest request = ExtendObjectRetentionRequest.builder()
.bucket(bucketName)
.key(objectName)
.additionalRetentionPeriod(additionalSeconds)
.build();
cosClient.extendObjectRetention(request);
System.out.printf("Retention period extended on %s by %s seconds%n", objectName, additionalSeconds);
}
主な参考文献
保護されたオブジェクトの合法的なホールドをリストアップする
この操作で返される内容は以下のとおりです。
- オブジェクト作成日
- オブジェクト保存期間 (秒数)
- 期間と作成日に基づいて計算された保持期限
- 法的保留のリスト
- 法的保留 ID
- 法的保留が適用されたときのタイム・スタンプ
重要なメモ:
- オブジェクトに正当なホールドがない場合、空の
LegalHoldSetが返される - オブジェクトに指定された保持期間がない場合、
404エラーが返される
public static void listLegalHoldsOnObject(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Listing legal holds for object: " + objectKey);
ListLegalHoldsRequest request = ListLegalHoldsRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
ListLegalHoldsResponse response = cosClient.listLegalHolds(request);
for (LegalHold hold : response.legalHolds()) {
System.out.println("Legal Hold ID: " + hold.id());
System.out.println("Date: " + hold.date());
}
}
保護対象から法的ホールドを削除する
public static void deleteLegalHoldFromObject(String bucketName, String objectKey, String legalHoldId, S3Client cosClient) {
System.out.println("Deleting legal hold from object: " + objectKey);
DeleteLegalHoldRequest request = DeleteLegalHoldRequest.builder()
.bucket(bucketName)
.key(objectKey)
.legalHoldId(legalHoldId)
.build();
cosClient.deleteLegalHold(request);
System.out.println("Legal hold deleted!");
}
主な参考文献
Key Protect の使用
クラウド内の重要な Data at Rest (保存されたデータ) を暗号化するために、Key Protect をストレージ・バケットに追加できます。
でバケツを作る Key Protect
public static void createBucketWithKeyProtect(String bucketName, String kpRootKeyCrn, S3Client cosClient) {
System.out.println("Creating bucket with Key Protect: " + bucketName);
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket(bucketName)
.ibmSSEKPEncryptionAlgorithm("AES256")
.ibmSSEKPCustomerRootKeyCrn(kpRootKeyCrn)
.build();
cosClient.createBucket(request);
System.out.println("Bucket created with Key Protect encryption!");
}
Key Protect が有効なバケツへのオブジェクトのアップロード
public static void putObjectToKPBucket(String bucketName, String objectKey, String filePath, S3Client cosClient) {
System.out.println("Uploading object to Key Protect enabled bucket");
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
cosClient.putObject(request, RequestBody.fromFile(new File(filePath)));
System.out.println("Object uploaded with Key Protect encryption!");
}
Transfer Manager を使用したより大きなオブジェクトのアップロード
Transfer Manager は、 IBM Cloud Object Storage との間でオブジェクトをアップロードおよびダウンロードするためのシンプルな API を提供します。
import com.ibm.cos.v2.transfer.s3.S3TransferManager;
import com.ibm.cos.v2.transfer.s3.model.*;
public static void uploadWithTransferManager(String bucketName, String objectKey, String filePath, S3Client cosClient) {
System.out.println("Uploading with Transfer Manager: " + objectKey);
// Create Transfer Manager
S3TransferManager transferManager = S3TransferManager.builder()
.s3Client(cosClient)
.build();
try {
// Upload file
UploadFileRequest uploadRequest = UploadFileRequest.builder()
.putObjectRequest(req -> req.bucket(bucketName).key(objectKey))
.source(Paths.get(filePath))
.build();
FileUpload upload = transferManager.uploadFile(uploadRequest);
// Wait for upload to complete
CompletedFileUpload completedUpload = upload.completionFuture().join();
System.out.println("Upload completed: " + completedUpload.response().eTag());
} finally {
transferManager.close();
}
}
主な参考文献
メタデータの更新
既存のオブジェクトのメタデータを更新する
public static void updateObjectMetadata(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Updating metadata for object: " + objectKey);
// Create new metadata
Map<String, String> newMetadata = new HashMap<>();
newMetadata.put("updated-by", "admin");
newMetadata.put("update-date", LocalDate.now().toString());
// Copy object to itself with new metadata
CopyObjectRequest request = CopyObjectRequest.builder()
.sourceBucket(bucketName)
.sourceKey(objectKey)
.destinationBucket(bucketName)
.destinationKey(objectKey)
.metadata(newMetadata)
.metadataDirective(MetadataDirective.REPLACE)
.build();
cosClient.copyObject(request);
System.out.println("Metadata updated!");
}
主な参考文献
Aspera 高速転送の使用
Aspera 高速転送の統合は、 IBM Aspera SDK。 IBM Cloud Object Storage との統合の詳細については、 Aspera のドキュメントを 参照してください。
Java アプリケーションでは、 IBM Cloud Object Storage SDK v2 と一緒に Aspera Transfer SDK を使用することで、大容量ファイルの高速転送が可能になります。
オブジェクトロックの使用
オブジェクト・ロックでは、WORM(write-once-read-many)モデルを使用してオブジェクトを保存することができます。 オブジェクトロックは、オブジェクトが一定時間または無期限に削除されたり上書きされたりするのを防ぐのに役立ちます。
オブジェクトロックを有効にしてバケツを作成する
Object Lock はバケツ作成時に有効にする必要があり、既存のバケツに追加することはできません。
public static void createBucketWithObjectLock(String bucketName, S3Client cosClient) {
System.out.println("Creating bucket with Object Lock: " + bucketName);
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket(bucketName)
.objectLockEnabledForBucket(true)
.build();
cosClient.createBucket(request);
System.out.println("Bucket created with Object Lock enabled!");
}
オブジェクトにオブジェクトロック保持を設定する
オブジェクトに保持を設定して、削除や上書きを防ぐことができます。 2つの保持モードがある:
- コンプライアンス :オブジェクトは、ルート・ユーザーを含むいかなるユーザーによっても、上書きまたは削除することはできません。
- 管理 :特別な権限を持つユーザーは、保持設定を変更したり、オブジェクトを削除することができます。
public static void putObjectRetention(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Setting object retention for: " + objectKey);
// Create retention period of 90 days
Instant retainUntil = Instant.now().plus(90, ChronoUnit.DAYS);
// Create object lock retention with COMPLIANCE mode
ObjectLockRetention retention = ObjectLockRetention.builder()
.mode(ObjectLockRetentionMode.COMPLIANCE)
.retainUntilDate(retainUntil)
.build();
// Apply retention to object
PutObjectRetentionRequest request = PutObjectRetentionRequest.builder()
.bucket(bucketName)
.key(objectKey)
.retention(retention)
.build();
cosClient.putObjectRetention(request);
System.out.println("Object retention set until: " + retainUntil);
}
オブジェクトロックの保持情報の取得
public static void getObjectRetention(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Getting object retention for: " + objectKey);
GetObjectRetentionRequest request = GetObjectRetentionRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
GetObjectRetentionResponse response = cosClient.getObjectRetention(request);
System.out.println("Retention Mode: " + response.retention().mode());
System.out.println("Retain Until: " + response.retention().retainUntilDate());
}
オブジェクト・ロック・リーガル・ホールドの設定
リーガル・ホールドは、保存期間と同じ保護を提供するが、有効期限はない。 法的保留は、明示的に解除されるまで有効です。
public static void putObjectLegalHold(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Setting legal hold on: " + objectKey);
ObjectLockLegalHold legalHold = ObjectLockLegalHold.builder()
.status(ObjectLockLegalHoldStatus.ON)
.build();
PutObjectLegalHoldRequest request = PutObjectLegalHoldRequest.builder()
.bucket(bucketName)
.key(objectKey)
.legalHold(legalHold)
.build();
cosClient.putObjectLegalHold(request);
System.out.println("Legal hold applied!");
}
オブジェクト・ロックの法的保留状態の取得
public static void getObjectLegalHold(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Getting legal hold status for: " + objectKey);
GetObjectLegalHoldRequest request = GetObjectLegalHoldRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
GetObjectLegalHoldResponse response = cosClient.getObjectLegalHold(request);
System.out.println("Legal Hold Status: " + response.legalHold().status());
}
主な参考文献
バケットのライフサイクル設定の使用
ライフサイクル構成では、 IBM Cloud Object Storage オブジェクトのグループに適用するアクションを定義できます。 ライフサイクル・ポリシーを使用して、オブジェクトを異なるストレージ・クラスに移行させたり、指定期間後にオブジェクトを失効させたりすることができます。
バケットにライフサイクル設定を行う
public static void putBucketLifecycle(String bucketName, S3Client cosClient) {
System.out.println("Setting lifecycle configuration on bucket: " + bucketName);
// Create a transition to move objects to GLACIER after 30 days
Transition transition = Transition.builder()
.days(30)
.storageClass(StorageClass.GLACIER)
.build();
// Create lifecycle rule filter
LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder()
.prefix("archive/") // Apply to objects with this prefix
.build();
// Create lifecycle rule
LifecycleRule rule = LifecycleRule.builder()
.id("archive-old-objects")
.filter(ruleFilter)
.transitions(transition)
.status(ExpirationStatus.ENABLED)
.build();
// Create lifecycle configuration
BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder()
.rules(rule)
.build();
// Apply lifecycle configuration to bucket
PutBucketLifecycleConfigurationRequest request = PutBucketLifecycleConfigurationRequest.builder()
.bucket(bucketName)
.lifecycleConfiguration(lifecycleConfig)
.build();
cosClient.putBucketLifecycleConfiguration(request);
System.out.println("Lifecycle configuration applied!");
}
バケツのライフサイクル設定の取得
public static void getBucketLifecycle(String bucketName, S3Client cosClient) {
System.out.println("Getting lifecycle configuration for bucket: " + bucketName);
GetBucketLifecycleConfigurationRequest request = GetBucketLifecycleConfigurationRequest.builder()
.bucket(bucketName)
.build();
GetBucketLifecycleConfigurationResponse response = cosClient.getBucketLifecycleConfiguration(request);
System.out.println("Found " + response.rules().size() + " lifecycle rules:");
for (LifecycleRule rule : response.rules()) {
System.out.println(" Rule ID: " + rule.id());
System.out.println(" Status: " + rule.status());
if (rule.hasTransitions()) {
for (Transition t : rule.transitions()) {
System.out.println(" Transition after " + t.days() + " days to " + t.storageClass());
}
}
}
}
バケツのライフサイクル設定の削除
public static void deleteBucketLifecycle(String bucketName, S3Client cosClient) {
System.out.println("Deleting lifecycle configuration from bucket: " + bucketName);
DeleteBucketLifecycleRequest request = DeleteBucketLifecycleRequest.builder()
.bucket(bucketName)
.build();
cosClient.deleteBucketLifecycle(request);
System.out.println("Lifecycle configuration deleted!");
}
主な参考文献
バケツ・バージョニングの使用
バージョニングによって、オブジェクトの複数のバージョンを同じバケツに保管することができます。 これは、意図しないユーザー操作やアプリケーションの障害から回復するのに役立ちます。
バケットでバージョニングを有効にする
public static void enableBucketVersioning(String bucketName, S3Client cosClient) {
System.out.println("Enabling versioning on bucket: " + bucketName);
VersioningConfiguration versioningConfig = VersioningConfiguration.builder()
.status(BucketVersioningStatus.ENABLED)
.build();
PutBucketVersioningRequest request = PutBucketVersioningRequest.builder()
.bucket(bucketName)
.versioningConfiguration(versioningConfig)
.build();
cosClient.putBucketVersioning(request);
System.out.println("Versioning enabled!");
}
バケツのバージョン管理状況の取得
public static void getBucketVersioning(String bucketName, S3Client cosClient) {
System.out.println("Getting versioning status for bucket: " + bucketName);
GetBucketVersioningRequest request = GetBucketVersioningRequest.builder()
.bucket(bucketName)
.build();
GetBucketVersioningResponse response = cosClient.getBucketVersioning(request);
System.out.println("Versioning Status: " + response.status());
}
オブジェクト・バージョンのリスト
public static void listObjectVersions(String bucketName, S3Client cosClient) {
System.out.println("Listing object versions in bucket: " + bucketName);
ListObjectVersionsRequest request = ListObjectVersionsRequest.builder()
.bucket(bucketName)
.build();
ListObjectVersionsResponse response = cosClient.listObjectVersions(request);
System.out.println("Versions:");
for (ObjectVersion version : response.versions()) {
System.out.println(" Key: " + version.key());
System.out.println(" Version ID: " + version.versionId());
System.out.println(" Is Latest: " + version.isLatest());
System.out.println(" Last Modified: " + version.lastModified());
System.out.println();
}
}
特定のバージョンのオブジェクトを削除する
public static void deleteObjectVersion(String bucketName, String objectKey, String versionId, S3Client cosClient) {
System.out.println("Deleting version " + versionId + " of object: " + objectKey);
DeleteObjectRequest request = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.versionId(versionId)
.build();
cosClient.deleteObject(request);
System.out.println("Object version deleted!");
}
主な参考文献
拡張バケットリストの使用
IBM Cloud Object Storage は、場所やストレージクラス情報など、バケツに関する追加のメタデータを返す拡張リスト API を提供します。
public static void listBucketsExtended(S3Client cosClient) {
System.out.println("Listing buckets with extended information:");
ListBucketsExtendedRequest request = ListBucketsExtendedRequest.builder().build();
ListBucketsExtendedResponse response = cosClient.listBucketsExtended(request);
for (Bucket bucket : response.buckets()) {
System.out.println("Bucket Name: " + bucket.name());
System.out.println(" Creation Date: " + bucket.creationDate());
// Extended metadata (IBM-specific)
if (bucket.locationConstraint() != null) {
System.out.println(" Location: " + bucket.locationConstraint());
}
}
}
主な参考文献
アーカイブ階層とオブジェクトリストアの使用
IBM Cloud Object Storage は、長期的なデータ保持のためのアーカイブ・ストレージ・クラス(Glacier)を低コストで提供する。 アーカイブストレージ内のオブジェクトは、アクセスする前にリストアする必要があります。
アーカイブ・ストレージへのオブジェクトの移行
ライフサイクル ポリシーを使用すると、指定した期間が経過したオブジェクトを自動的にアーカイブ ストレージに移行できます。
public static void setArchiveRule(String bucketName, S3Client cosClient) {
System.out.println("Setting archive rule on bucket: " + bucketName);
// Create transition to Glacier after 30 days
Transition transition = Transition.builder()
.days(30)
.storageClass(StorageClass.GLACIER)
.build();
// Create lifecycle rule
LifecycleRuleFilter filter = LifecycleRuleFilter.builder()
.prefix("archive/")
.build();
LifecycleRule rule = LifecycleRule.builder()
.id("archive-rule")
.filter(filter)
.transitions(transition)
.status(ExpirationStatus.ENABLED)
.build();
// Apply lifecycle configuration
BucketLifecycleConfiguration config = BucketLifecycleConfiguration.builder()
.rules(rule)
.build();
PutBucketLifecycleConfigurationRequest request = PutBucketLifecycleConfigurationRequest.builder()
.bucket(bucketName)
.lifecycleConfiguration(config)
.build();
cosClient.putBucketLifecycleConfiguration(request);
System.out.println("Archive rule configured!");
}
アーカイブされたオブジェクトのリストア
アーカイブストレージ内のオブジェクトは、ダウンロードする前にリストアする必要があります。 リストアされたコピーが利用可能でなければならない日数を指定できます。
public static void restoreArchivedObject(String bucketName, String objectKey, int days, S3Client cosClient) {
System.out.println("Restoring archived object: " + objectKey);
// Create restore request with duration
RestoreRequest restoreRequest = RestoreRequest.builder()
.days(days)
.glacierJobParameters(GlacierJobParameters.builder()
.tier(Tier.STANDARD) // Options: STANDARD (12 hours), EXPEDITED (2 hours), BULK (5-12 hours)
.build())
.build();
RestoreObjectRequest request = RestoreObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.restoreRequest(restoreRequest)
.build();
cosClient.restoreObject(request);
System.out.println("Restore initiated. Object will be available for " + days + " days once restored.");
}
復旧状況の確認
public static void checkRestoreStatus(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Checking restore status for: " + objectKey);
HeadObjectRequest request = HeadObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
HeadObjectResponse response = cosClient.headObject(request);
if (response.restore() != null) {
System.out.println("Restore Status: " + response.restore());
// Parse restore status
String restoreStatus = response.restore();
if (restoreStatus.contains("ongoing-request=\"true\"")) {
System.out.println("Restoration in progress...");
} else if (restoreStatus.contains("ongoing-request=\"false\"")) {
System.out.println("Object has been restored and is available for download");
}
} else {
System.out.println("Object is not archived or no restore in progress");
}
}
アーカイブ検索の高速化
IBM Cloud Object Storage アーカイブ検索を高速化し、アーカイブデータへのアクセスを高速化:
- エクスペディット :2時間
- 標準 :検索時間3~5時間(デフォルト)
- バルク :回収時間5~12時間(最低コスト)
public static void restoreWithExpeditedRetrieval(String bucketName, String objectKey, S3Client cosClient) {
System.out.println("Restoring with expedited retrieval: " + objectKey);
RestoreRequest restoreRequest = RestoreRequest.builder()
.days(1)
.glacierJobParameters(GlacierJobParameters.builder()
.tier(Tier.EXPEDITED) // 2-hour retrieval
.build())
.build();
RestoreObjectRequest request = RestoreObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.restoreRequest(restoreRequest)
.build();
cosClient.restoreObject(request);
System.out.println("Expedited restore initiated (2-hour retrieval)");
}
主な参考文献
CORS (クロスオリジン・リソース共有)の使用
CORS 構成によって、あるドメインで実行されているウェブ・アプリケーションが、別のドメインから IBM Cloud Object Storage のリソースにアクセスできるようになります。
バケットに CORS の設定を行う
public static void setCorsConfiguration(String bucketName, S3Client cosClient) {
System.out.println("Setting CORS configuration on bucket: " + bucketName);
// Create CORS rule
CORSRule corsRule = CORSRule.builder()
.allowedMethods("GET", "PUT", "POST", "DELETE")
.allowedOrigins("https://example.com")
.allowedHeaders("*")
.maxAgeSeconds(3000)
.exposeHeaders("ETag", "x-amz-request-id")
.build();
// Create CORS configuration
CORSConfiguration corsConfig = CORSConfiguration.builder()
.corsRules(corsRule)
.build();
PutBucketCorsRequest request = PutBucketCorsRequest.builder()
.bucket(bucketName)
.corsConfiguration(corsConfig)
.build();
cosClient.putBucketCors(request);
System.out.println("CORS configuration applied!");
}
CORS コンフィギュレーションの取得
public static void getCorsConfiguration(String bucketName, S3Client cosClient) {
System.out.println("Getting CORS configuration for bucket: " + bucketName);
GetBucketCorsRequest request = GetBucketCorsRequest.builder()
.bucket(bucketName)
.build();
GetBucketCorsResponse response = cosClient.getBucketCors(request);
System.out.println("CORS Rules:");
for (CORSRule rule : response.corsRules()) {
System.out.println(" Allowed Methods: " + rule.allowedMethods());
System.out.println(" Allowed Origins: " + rule.allowedOrigins());
System.out.println(" Allowed Headers: " + rule.allowedHeaders());
System.out.println(" Max Age: " + rule.maxAgeSeconds());
}
}
CORS 設定の削除
public static void deleteCorsConfiguration(String bucketName, S3Client cosClient) {
System.out.println("Deleting CORS configuration from bucket: " + bucketName);
DeleteBucketCorsRequest request = DeleteBucketCorsRequest.builder()
.bucket(bucketName)
.build();
cosClient.deleteBucketCors(request);
System.out.println("CORS configuration deleted!");
}
主な参考文献
バケットポリシーの使用
バケットポリシーは、バケットとオブジェクトのアクセス制御管理を提供する。 これらはJSONで記述され、ユーザーやサービスにパーミッションを付与したり拒否したりすることができる。
バケットポリシーの設定
public static void setBucketPolicy(String bucketName, S3Client cosClient) {
System.out.println("Setting bucket policy on: " + bucketName);
// Create policy document (JSON format)
String policyText = "{"
+ "\"Version\": \"2012-10-17\","
+ "\"Statement\": [{"
+ " \"Effect\": \"Allow\","
+ " \"Principal\": {\"AWS\": \"*\"},"
+ " \"Action\": \"s3:GetObject\","
+ " \"Resource\": \"arn:aws:s3:::" + bucketName + "/*\""
+ "}]"
+ "}";
PutBucketPolicyRequest request = PutBucketPolicyRequest.builder()
.bucket(bucketName)
.policy(policyText)
.build();
cosClient.putBucketPolicy(request);
System.out.println("Bucket policy applied!");
}
バケット・ポリシーの取得
public static void getBucketPolicy(String bucketName, S3Client cosClient) {
System.out.println("Getting bucket policy for: " + bucketName);
GetBucketPolicyRequest request = GetBucketPolicyRequest.builder()
.bucket(bucketName)
.build();
GetBucketPolicyResponse response = cosClient.getBucketPolicy(request);
System.out.println("Policy: " + response.policy());
}
バケットポリシーの削除
public static void deleteBucketPolicy(String bucketName, S3Client cosClient) {
System.out.println("Deleting bucket policy from: " + bucketName);
DeleteBucketPolicyRequest request = DeleteBucketPolicyRequest.builder()
.bucket(bucketName)
.build();
cosClient.deleteBucketPolicy(request);
System.out.println("Bucket policy deleted!");
}
主な参考文献
静的ウェブサイトの作成
IBM Cloud Object Storage は、バケットから静的ウェブサイトを直接ホスティングすることをサポートしています。 インデックスドキュメントとエラードキュメントを指定することで、静的コンテンツを提供するようにバケットを設定することができます。
この操作には、以下のインポート文が必要である:
import com.ibm.cos.v2.services.s3.model.BucketWebsiteConfiguration;
バケットウェブサイトの設定
この操作は、コンフィギュレーションによって以下のようになり、正しくコンフィギュレーションされたクライアントを必要とする:
- サフィックスのバケット構成 (インデックス文書)
- キーのバケット設定 (エラー文書)
public static void setBucketWebsiteConfiguration(String bucketName, S3Client cosClient) {
System.out.println("Setting website configuration for bucket: " + bucketName);
// Create website configuration with index and error documents
IndexDocument indexDocument = IndexDocument.builder()
.suffix("index.html")
.build();
ErrorDocument errorDocument = ErrorDocument.builder()
.key("error.html")
.build();
WebsiteConfiguration websiteConfig = WebsiteConfiguration.builder()
.indexDocument(indexDocument)
.errorDocument(errorDocument)
.build();
PutBucketWebsiteRequest request = PutBucketWebsiteRequest.builder()
.bucket(bucketName)
.websiteConfiguration(websiteConfig)
.build();
cosClient.putBucketWebsite(request);
System.out.println("Website configuration set successfully!");
}
バケットウェブサイトの設定の取得
public static void getBucketWebsiteConfiguration(String bucketName, S3Client cosClient) {
System.out.println("Getting website configuration for bucket: " + bucketName);
GetBucketWebsiteRequest request = GetBucketWebsiteRequest.builder()
.bucket(bucketName)
.build();
GetBucketWebsiteResponse response = cosClient.getBucketWebsite(request);
System.out.println("Index Document: " + response.indexDocument().suffix());
System.out.println("Error Document: " + response.errorDocument().key());
}
バケットウェブサイトの設定を削除する
public static void deleteBucketWebsiteConfiguration(String bucketName, S3Client cosClient) {
System.out.println("Deleting website configuration from bucket: " + bucketName);
DeleteBucketWebsiteRequest request = DeleteBucketWebsiteRequest.builder()
.bucket(bucketName)
.build();
cosClient.deleteBucketWebsite(request);
System.out.println("Website configuration deleted!");
}
主な参考文献
エラー処理とベストプラクティス
SDKの例外処理
v2 SDKは、さまざまなエラーシナリオに対して特定の例外タイプを使用します。
import com.ibm.cos.v2.services.s3.model.S3Exception;
import com.ibm.cos.v2.services.s3.model.NoSuchBucketException;
import com.ibm.cos.v2.services.s3.model.NoSuchKeyException;
public static void handleExceptions(String bucketName, String objectKey, S3Client cosClient) {
try {
GetObjectRequest request = GetObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
cosClient.getObject(request, ResponseTransformer.toBytes());
} catch (NoSuchBucketException e) {
System.err.println("Bucket does not exist: " + bucketName);
System.err.println("Error Code: " + e.awsErrorDetails().errorCode());
} catch (NoSuchKeyException e) {
System.err.println("Object does not exist: " + objectKey);
System.err.println("Error Code: " + e.awsErrorDetails().errorCode());
} catch (S3Exception e) {
System.err.println("S3 Error: " + e.awsErrorDetails().errorMessage());
System.err.println("Error Code: " + e.awsErrorDetails().errorCode());
System.err.println("Status Code: " + e.statusCode());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
}
v2 SDK のベストプラクティス
- S3Client インスタンスを再利用する :クライアントの作成にはコストがかかる。 リクエスト間で再利用する。
// Good: Create once, reuse
S3Client client = S3Client.builder()
.endpointOverride(URI.create(endpoint))
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.region(Region.of(region))
.build();
// Use client for multiple operations
client.listBuckets();
client.putObject(...);
client.getObject(...);
// Close when done
client.close();
- try-with-resourcesを使用する :リソースのクリーンアップを確実に行う。
try (S3Client client = S3Client.builder()
.endpointOverride(URI.create(endpoint))
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.region(Region.of(region))
.build()) {
// Perform operations
client.listBuckets();
} // Client automatically closed
-
マルチパートアップロードで大きなファイルを扱う :5MBを超えるファイルについては、マルチパートアップロードを使用してください。
-
大規模な転送にはTransfer Managerを使用します:自動マルチパートアップロード、再試行ロジック、進捗追跡を提供します。
-
適切なタイムアウトを設定する:クライアントのタイムアウトを設定します。
S3Client client = S3Client.builder()
.endpointOverride(URI.create(endpoint))
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.region(Region.of(region))
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofMinutes(5))
.apiCallAttemptTimeout(Duration.ofMinutes(2))
.build())
.build();
主な参考文献
追加のリソース
サポート情報
- Stack Overflow でタグ
ibmを付けて質問する。object-storage - IBM Cloud サポートチケット
- GitHub Issuesで バグを報告したり、機能をリクエストする
このドキュメントは、 IBM Cloud Object Storage Java SDK v2 の構造とSDKリファレンスを提供します。 すべての操作の完全な動作コード例については、 GitHub リポジトリの examples ディレクトリと 移行ガイドを 参照してください。