Sample code for 30+ languages & platforms
Java Requires Chilkat v11.6.0+

Amazon Glacier: Upload Archive from a File

See more Amazon Glacier Examples

For existing Amazon Glacier vault customers. The standalone vault service is closed to new customers. These examples use its REST API version 2012-06-01, not the S3 bucket APIs used by S3 Glacier storage classes. See AWS service guidance.

Computes both SHA-256 hashes, uploads immutable archive bytes, checks HTTP 201 and the returned tree hash, and prints the archive ID for durable storage in your catalog. A description is optional, must be printable ASCII, and is limited to 1,024 characters; it is not a lookup key. Single-request uploads support up to 4 GiB; use multipart upload for larger archives. This variant hashes and streams a file without buffering the full upload; the file must remain unchanged.

Uses AWS Signature Version 4 with service glacier. Set the region once; the example builds the commercial AWS endpoint. Other partitions require the appropriate endpoint suffix. /-/ selects the signing account; change the vault name and IDs to your own resources. Load private qa_data/aws/glacier.json with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles or refresh credentials. TLS certificate verification is enabled explicitly.

Checks transport completion, the operation-specific HTTP status, and parsed data separately. Inspect full diagnostics privately. Renew expired credentials; use bounded backoff with jitter for retryable reads. Uploads and job initiation can succeed before a connection fails, so do not blindly resubmit them. Configure IAM permissions for only the required operations and vault resources.

AWS reference

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Socket;
import com.chilkatsoft.chilkat2.Stream;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // Assumes Chilkat is unlocked. See Global Unlock Sample.
        boolean success = false;
        // Private configuration, not a file in public web content or source control.
        // Load current IAM credentials authorized for the Glacier operation.
        JsonObject credentials = new JsonObject();
        credentials.setStrict(true);
        try {
            credentials.loadFile("qa_data/aws/glacier.json");
        } catch (ChilkatException e) {
            System.out.println("Could not load private AWS credentials.");
            return;
        }

        if ((credentials.jsonTypeOf("access_key") != 1) || ("".equals(credentials.stringOf("access_key")))) {
            System.out.println("Missing or invalid access_key.");
            return;
        }

        if ((credentials.jsonTypeOf("secret_key") != 1) || ("".equals(credentials.stringOf("secret_key")))) {
            System.out.println("Missing or invalid secret_key.");
            return;
        }

        // Set this once to the region containing the vault.
        String region = "us-west-2";
        StringBuilder endpoint = new StringBuilder();
        endpoint.append("glacier.");
        endpoint.append(region);
        endpoint.append(".amazonaws.com");
        AuthAws aws = new AuthAws();
        aws.setAccessKey(credentials.stringOf("access_key"));
        aws.setSecretKey(credentials.stringOf("secret_key"));
        aws.setRegion(region);
        aws.setServiceName("glacier");
        aws.setSignatureVersion(4);
        Rest rest = new Rest();
        rest.setConnectTimeoutMs(20000);
        rest.setIdleTimeoutMs(60000);
        try {
            rest.setAuthAws(aws);
        } catch (ChilkatException e) {
            System.out.println("Could not configure AWS signing.");
            return;
        }

        // Temporary IAM/STS credentials require their session token on every signed request.
        // Include the token in the signed query. Keep request URLs and diagnostics private.
        // Leave session_token absent or empty only for credentials that do not have one.
        if (credentials.hasMember("session_token")) {
            if (credentials.jsonTypeOf("session_token") != 1) {
                System.out.println("session_token must be a string.");
                return;
            }

            if (!"".equals(credentials.stringOf("session_token"))) {
                try {
                    rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
                } catch (ChilkatException e) {
                    System.out.println("Could not set the session-token parameter.");
                    return;
                }
            }
        }

        // Supply a Socket to explicitly enable TLS certificate verification.
        Socket connection = new Socket();
        connection.setRequireSslCertVerify(true);
        connection.setMaxReadIdleMs(60000);
        connection.setMaxSendIdleMs(60000);
        try {
            connection.connect(endpoint.getAsString(), 443, true, 20000);
        } catch (ChilkatException e) {
            System.out.println("TLS connection failed; inspect diagnostics privately.");
            return;
        }

        try {
            rest.useConnection(connection, true);
        } catch (ChilkatException e) {
            System.out.println("Could not attach the TLS connection.");
            return;
        }

        try {
            rest.addHeader("x-amz-glacier-version", "2012-06-01");
        } catch (ChilkatException e) {
            System.out.println("Could not set x-amz-glacier-version.");
            return;
        }

        // A hyphen selects the account belonging to the signing credentials.
        // Use the original, URL-safe vault name and IDs returned by Glacier.
        try {
            rest.addPathParam("{vault}", "chilkat");
        } catch (ChilkatException e) {
            System.out.println("Could not set vault name.");
            return;
        }

        JsonObject body = new JsonObject();
        JsonObject result = new JsonObject();
        result.setStrict(true);
        JsonObject error = new JsonObject();
        error.setStrict(true);
        StringBuilder requestBody = new StringBuilder();
        StringBuilder responseBody = new StringBuilder();
        String filePath = "qa_data/zips/somethingBig.zip";
        // Keep this file unchanged during BOTH hashing passes and the upload.
        Crypt2 crypt = new Crypt2();
        crypt.setHashAlgorithm("sha256-tree-hash");
        crypt.setEncodingMode("hexlower");
        FileAccess files = new FileAccess();
        String fileSize;
        try {
            fileSize = files.fileSizeStr(filePath);
        } catch (ChilkatException e) {
            System.out.println("Could not read archive file size.");
            return;
        }

        if ("0".equals(fileSize)) {
            crypt.setHashAlgorithm("sha256");
        }

        String treeHash;
        try {
            treeHash = crypt.hashFileENC(filePath);
        } catch (ChilkatException e) {
            System.out.println("Could not compute tree hash.");
            return;
        }

        try {
            rest.addHeader("x-amz-sha256-tree-hash", treeHash);
        } catch (ChilkatException e) {
            System.out.println("Could not set x-amz-sha256-tree-hash.");
            return;
        }

        crypt.setHashAlgorithm("sha256");
        String linearHash;
        try {
            linearHash = crypt.hashFileENC(filePath);
        } catch (ChilkatException e) {
            System.out.println("Could not compute payload hash.");
            return;
        }

        aws.setPrecomputedSha256(linearHash);
        // Set the precomputed hash before attaching the signing configuration again.
        try {
            rest.setAuthAws(aws);
        } catch (ChilkatException e) {
            System.out.println("Could not update AWS signing.");
            return;
        }

        try {
            rest.addHeader("x-amz-content-sha256", linearHash);
        } catch (ChilkatException e) {
            System.out.println("Could not set x-amz-content-sha256.");
            return;
        }

        try {
            rest.addHeader("x-amz-archive-description", "Example archive");
        } catch (ChilkatException e) {
            System.out.println("Could not set x-amz-archive-description.");
            return;
        }

        Stream fileStream = new Stream();
        fileStream.setSourceFile(filePath);
        rest.setStreamNonChunked(true);
        rest.setIdleTimeoutMs(120000);
        connection.setMaxReadIdleMs(120000);
        connection.setMaxSendIdleMs(120000);
        String response;
        try {
            response = rest.fullRequestStream("POST", "/-/vaults/{vault}/archives", fileStream);
        } catch (ChilkatException e) {
            System.out.println("Upload did not complete; check for an accepted archive before retrying.");
            return;
        }

        responseBody.append(response);
        if (rest.getResponseStatusCode() != 201) {
            System.out.println("Glacier HTTP status: " + rest.getResponseStatusCode());
            try {
                error.loadSb(responseBody);
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (success) {
                if (error.jsonTypeOf("code") == 1) {
                    System.out.println("AWS error code: " + error.stringOf("code"));
                }
            }

            System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
            // Inspect full errors privately. An HTTP error is not a successful operation.
            return;
        }

        String archiveId = rest.responseHdrByName("x-amz-archive-id");
        if ((!rest.getLastMethodSuccess()) || ("".equals(archiveId))) {
            System.out.println("Missing archive ID; investigate the accepted upload before retrying.");
            return;
        }

        // Save this ID even if subsequent checksum verification fails.
        System.out.println("Archive ID: " + archiveId);
        System.out.println("Location: " + rest.responseHdrByName("Location"));
        String returnedHash = rest.responseHdrByName("x-amz-sha256-tree-hash");
        if (!returnedHash.equals(treeHash)) {
            System.out.println("Upload response checksum mismatch; preserve the archive ID and investigate.");
            return;
        }

        System.out.println("Archive upload verified. Persist its ID and checksum in your archive catalog.");
    }
}