Java 2.x용 SDK를 사용한 S3 Glacier 예제 - AWS SDK 코드 예제

AWS Doc SDK ExamplesWord AWS SDK 리포지토리에는 더 많은 GitHub 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Java 2.x용 SDK를 사용한 S3 Glacier 예제

다음 코드 예제에서는 S3 Glacier와 AWS SDK for Java 2.x 함께를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.

주제

작업

다음 코드 예시에서는 CreateVault을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.glacier.model.CreateVaultRequest; import software.amazon.awssdk.services.glacier.model.CreateVaultResponse; import software.amazon.awssdk.services.glacier.model.GlacierException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateVault { public static void main(String[] args) { final String usage = """ Usage: <vaultName> Where: vaultName - The name of the vault to create. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String vaultName = args[0]; GlacierClient glacier = GlacierClient.builder() .region(Region.US_EAST_1) .build(); createGlacierVault(glacier, vaultName); glacier.close(); } public static void createGlacierVault(GlacierClient glacier, String vaultName) { try { CreateVaultRequest vaultRequest = CreateVaultRequest.builder() .vaultName(vaultName) .build(); CreateVaultResponse createVaultResult = glacier.createVault(vaultRequest); System.out.println("The URI of the new vault is " + createVaultResult.location()); } catch (GlacierException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API 세부 정보는 CreateVault AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 DeleteArchive을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.glacier.model.DeleteArchiveRequest; import software.amazon.awssdk.services.glacier.model.GlacierException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteArchive { public static void main(String[] args) { final String usage = """ Usage: <vaultName> <accountId> <archiveId> Where: vaultName - The name of the vault that contains the archive to delete. accountId - The account ID value. archiveId - The archive ID value. """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String vaultName = args[0]; String accountId = args[1]; String archiveId = args[2]; GlacierClient glacier = GlacierClient.builder() .region(Region.US_EAST_1) .build(); deleteGlacierArchive(glacier, vaultName, accountId, archiveId); glacier.close(); } public static void deleteGlacierArchive(GlacierClient glacier, String vaultName, String accountId, String archiveId) { try { DeleteArchiveRequest delArcRequest = DeleteArchiveRequest.builder() .vaultName(vaultName) .accountId(accountId) .archiveId(archiveId) .build(); glacier.deleteArchive(delArcRequest); System.out.println("The archive was deleted."); } catch (GlacierException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API 세부 정보는 DeleteArchive AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 DeleteVault을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.glacier.model.DeleteVaultRequest; import software.amazon.awssdk.services.glacier.model.GlacierException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteVault { public static void main(String[] args) { final String usage = """ Usage: <vaultName> Where: vaultName - The name of the vault to delete.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String vaultName = args[0]; GlacierClient glacier = GlacierClient.builder() .region(Region.US_EAST_1) .build(); deleteGlacierVault(glacier, vaultName); glacier.close(); } public static void deleteGlacierVault(GlacierClient glacier, String vaultName) { try { DeleteVaultRequest delVaultRequest = DeleteVaultRequest.builder() .vaultName(vaultName) .build(); glacier.deleteVault(delVaultRequest); System.out.println("The vault was deleted!"); } catch (GlacierException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API 세부 정보는 DeleteVault AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 InitiateJob을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

볼트 인벤토리를 검색합니다.

import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.glacier.model.JobParameters; import software.amazon.awssdk.services.glacier.model.InitiateJobResponse; import software.amazon.awssdk.services.glacier.model.GlacierException; import software.amazon.awssdk.services.glacier.model.InitiateJobRequest; import software.amazon.awssdk.services.glacier.model.DescribeJobRequest; import software.amazon.awssdk.services.glacier.model.DescribeJobResponse; import software.amazon.awssdk.services.glacier.model.GetJobOutputRequest; import software.amazon.awssdk.services.glacier.model.GetJobOutputResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ArchiveDownload { public static void main(String[] args) { final String usage = """ Usage: <vaultName> <accountId> <path> Where: vaultName - The name of the vault. accountId - The account ID value. path - The path where the file is written to. """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String vaultName = args[0]; String accountId = args[1]; String path = args[2]; GlacierClient glacier = GlacierClient.builder() .region(Region.US_EAST_1) .build(); String jobNum = createJob(glacier, vaultName, accountId); checkJob(glacier, jobNum, vaultName, accountId, path); glacier.close(); } public static String createJob(GlacierClient glacier, String vaultName, String accountId) { try { JobParameters job = JobParameters.builder() .type("inventory-retrieval") .build(); InitiateJobRequest initJob = InitiateJobRequest.builder() .jobParameters(job) .accountId(accountId) .vaultName(vaultName) .build(); InitiateJobResponse response = glacier.initiateJob(initJob); System.out.println("The job ID is: " + response.jobId()); System.out.println("The relative URI path of the job is: " + response.location()); return response.jobId(); } catch (GlacierException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } // Poll S3 Glacier = Polling a Job may take 4-6 hours according to the // Documentation. public static void checkJob(GlacierClient glacier, String jobId, String name, String account, String path) { try { boolean finished = false; String jobStatus; int yy = 0; while (!finished) { DescribeJobRequest jobRequest = DescribeJobRequest.builder() .jobId(jobId) .accountId(account) .vaultName(name) .build(); DescribeJobResponse response = glacier.describeJob(jobRequest); jobStatus = response.statusCodeAsString(); if (jobStatus.compareTo("Succeeded") == 0) finished = true; else { System.out.println(yy + " status is: " + jobStatus); Thread.sleep(1000); } yy++; } System.out.println("Job has Succeeded"); GetJobOutputRequest jobOutputRequest = GetJobOutputRequest.builder() .jobId(jobId) .vaultName(name) .accountId(account) .build(); ResponseBytes<GetJobOutputResponse> objectBytes = glacier.getJobOutputAsBytes(jobOutputRequest); // Write the data to a local file. byte[] data = objectBytes.asByteArray(); File myFile = new File(path); OutputStream os = new FileOutputStream(myFile); os.write(data); System.out.println("Successfully obtained bytes from a Glacier vault"); os.close(); } catch (GlacierException | InterruptedException | IOException e) { System.out.println(e.getMessage()); System.exit(1); } } }
  • API 세부 정보는 InitiateJob AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 ListVaults을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.model.ListVaultsRequest; import software.amazon.awssdk.services.glacier.model.ListVaultsResponse; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.glacier.model.DescribeVaultOutput; import software.amazon.awssdk.services.glacier.model.GlacierException; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListVaults { public static void main(String[] args) { GlacierClient glacier = GlacierClient.builder() .region(Region.US_EAST_1) .build(); listAllVault(glacier); glacier.close(); } public static void listAllVault(GlacierClient glacier) { boolean listComplete = false; String newMarker = null; int totalVaults = 0; System.out.println("Your Amazon Glacier vaults:"); try { while (!listComplete) { ListVaultsResponse response = null; if (newMarker != null) { ListVaultsRequest request = ListVaultsRequest.builder() .marker(newMarker) .build(); response = glacier.listVaults(request); } else { ListVaultsRequest request = ListVaultsRequest.builder() .build(); response = glacier.listVaults(request); } List<DescribeVaultOutput> vaultList = response.vaultList(); for (DescribeVaultOutput v : vaultList) { totalVaults += 1; System.out.println("* " + v.vaultName()); } // Check for further results. newMarker = response.marker(); if (newMarker == null) { listComplete = true; } } if (totalVaults == 0) { System.out.println("No vaults found."); } } catch (GlacierException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API 세부 정보는 ListVaults AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 UploadArchive을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.glacier.model.UploadArchiveRequest; import software.amazon.awssdk.services.glacier.model.UploadArchiveResponse; import software.amazon.awssdk.services.glacier.model.GlacierException; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class UploadArchive { static final int ONE_MB = 1024 * 1024; public static void main(String[] args) { final String usage = """ Usage: <strPath> <vaultName>\s Where: strPath - The path to the archive to upload (for example, C:\\AWS\\test.pdf). vaultName - The name of the vault. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String strPath = args[0]; String vaultName = args[1]; File myFile = new File(strPath); Path path = Paths.get(strPath); GlacierClient glacier = GlacierClient.builder() .region(Region.US_EAST_1) .build(); String archiveId = uploadContent(glacier, path, vaultName, myFile); System.out.println("The ID of the archived item is " + archiveId); glacier.close(); } public static String uploadContent(GlacierClient glacier, Path path, String vaultName, File myFile) { // Get an SHA-256 tree hash value. String checkVal = computeSHA256(myFile); try { UploadArchiveRequest uploadRequest = UploadArchiveRequest.builder() .vaultName(vaultName) .checksum(checkVal) .build(); UploadArchiveResponse res = glacier.uploadArchive(uploadRequest, path); return res.archiveId(); } catch (GlacierException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } private static String computeSHA256(File inputFile) { try { byte[] treeHash = computeSHA256TreeHash(inputFile); System.out.printf("SHA-256 tree hash = %s\n", toHex(treeHash)); return toHex(treeHash); } catch (IOException ioe) { System.err.format("Exception when reading from file %s: %s", inputFile, ioe.getMessage()); System.exit(-1); } catch (NoSuchAlgorithmException nsae) { System.err.format("Cannot locate MessageDigest algorithm for SHA-256: %s", nsae.getMessage()); System.exit(-1); } return ""; } public static byte[] computeSHA256TreeHash(File inputFile) throws IOException, NoSuchAlgorithmException { byte[][] chunkSHA256Hashes = getChunkSHA256Hashes(inputFile); return computeSHA256TreeHash(chunkSHA256Hashes); } /** * Computes an SHA256 checksum for each 1 MB chunk of the input file. This * includes the checksum for the last chunk, even if it's smaller than 1 MB. */ public static byte[][] getChunkSHA256Hashes(File file) throws IOException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); long numChunks = file.length() / ONE_MB; if (file.length() % ONE_MB > 0) { numChunks++; } if (numChunks == 0) { return new byte[][] { md.digest() }; } byte[][] chunkSHA256Hashes = new byte[(int) numChunks][]; FileInputStream fileStream = null; try { fileStream = new FileInputStream(file); byte[] buff = new byte[ONE_MB]; int bytesRead; int idx = 0; while ((bytesRead = fileStream.read(buff, 0, ONE_MB)) > 0) { md.reset(); md.update(buff, 0, bytesRead); chunkSHA256Hashes[idx++] = md.digest(); } return chunkSHA256Hashes; } finally { if (fileStream != null) { try { fileStream.close(); } catch (IOException ioe) { System.err.printf("Exception while closing %s.\n %s", file.getName(), ioe.getMessage()); } } } } /** * Computes the SHA-256 tree hash for the passed array of 1 MB chunk * checksums. */ public static byte[] computeSHA256TreeHash(byte[][] chunkSHA256Hashes) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[][] prevLvlHashes = chunkSHA256Hashes; while (prevLvlHashes.length > 1) { int len = prevLvlHashes.length / 2; if (prevLvlHashes.length % 2 != 0) { len++; } byte[][] currLvlHashes = new byte[len][]; int j = 0; for (int i = 0; i < prevLvlHashes.length; i = i + 2, j++) { // If there are at least two elements remaining. if (prevLvlHashes.length - i > 1) { // Calculate a digest of the concatenated nodes. md.reset(); md.update(prevLvlHashes[i]); md.update(prevLvlHashes[i + 1]); currLvlHashes[j] = md.digest(); } else { // Take care of the remaining odd chunk currLvlHashes[j] = prevLvlHashes[i]; } } prevLvlHashes = currLvlHashes; } return prevLvlHashes[0]; } /** * Returns the hexadecimal representation of the input byte array */ public static String toHex(byte[] data) { StringBuilder sb = new StringBuilder(data.length * 2); for (byte datum : data) { String hex = Integer.toHexString(datum & 0xFF); if (hex.length() == 1) { // Append leading zero. sb.append("0"); } sb.append(hex); } return sb.toString().toLowerCase(); } }
  • API 세부 정보는 UploadArchive AWS SDK for Java 2.x 참조의 API를 참조하세요.