S3 Http: Multipart Upload with Checksums and Checkpoint
See more S3 - HTTP Examples
Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.
Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.
Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.
Uses a private checkpoint directory for one upload and an immutable source file. Run one process per checkpoint; never run upload/resume concurrently with abort. The fixed 8 MiB part size limits this demonstration to nonempty files of at most 10,000 parts (78.125 GiB). It does not impose that limit on S3 itself; choose larger valid part sizes for larger objects.
Uses SHA-256 COMPOSITE multipart checksums, validates part checksums, and verifies the returned composite checksum. ETags are retained for completion but never treated as MD5. Completion can return an error inside HTTP 200; the XML result is checked. Source identity is SHA-256, not just filename/length. The checkpoint contains no AWS credentials.
Requires s3:PutObject, s3:ListMultipartUploadParts for resume, and s3:GetObject for uncertain-completion recovery, plus relevant KMS permissions if bucket defaults use KMS. Incomplete parts incur storage charges until completed or aborted. Configure a suitable incomplete-multipart lifecycle rule as an operational safeguard. Timeout during initiation may leave an upload without a checkpoint; list uploads and investigate before initiating another.
Starts, transfers and completes one upload. Saves state before parts and a pending completion record before completion. Run the resume companion after interruptions; do not rerun start against an existing cache. Metadata binds an uncertain completion to a random upload identity.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.DirTree;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.Hashtable;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Prng;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
StringBuilder stringCompare = new StringBuilder();
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load private credentials; never put access keys or session tokens in source.
JsonObject credentials = new JsonObject();
credentials.setStrict(true);
try {
credentials.loadFile("qa_data/aws/s3.json");
} catch (ChilkatException e) {
System.out.println("Could not load private S3 credentials.");
return;
}
stringCompare.setString(credentials.stringOf("access_key"));
boolean stringMatch1 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("access_key") != 1) || (stringMatch1)) {
System.out.println("Missing or invalid access_key.");
return;
}
stringCompare.setString(credentials.stringOf("secret_key"));
boolean stringMatch2 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("secret_key") != 1) || (stringMatch2)) {
System.out.println("Missing or invalid secret_key.");
return;
}
Http http = new Http();
http.setAwsAccessKey(credentials.stringOf("access_key"));
http.setAwsSecretKey(credentials.stringOf("secret_key"));
if (credentials.hasMember("session_token")) {
stringCompare.setString(credentials.stringOf("session_token"));
boolean stringMatch3 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("session_token") != 1) || (stringMatch3)) {
System.out.println("session_token must be a nonempty string when supplied.");
return;
}
http.setAwsSessionToken(credentials.stringOf("session_token"));
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
String region = "us-west-2";
http.setAwsRegion(region);
StringBuilder endpoint = new StringBuilder();
endpoint.append("s3.");
endpoint.append(region);
endpoint.append(".amazonaws.com");
http.setAwsEndpoint(endpoint.getAsString());
http.setRequireSslCertVerify(true);
http.setFollowRedirects(false);
// A region redirect is not success. Correct the endpoint and signing region.
String bucketName = "your-bucket-name";
String objectKey = "examples/archive.bin";
HttpResponse response = new HttpResponse();
Crypt2 signer = new Crypt2();
signer.setCharset("utf-8");
signer.setHashAlgorithm("sha256");
signer.setEncodingMode("hexlower");
signer.setMacAlgorithm("hmac");
DateTime now = new DateTime();
StringBuilder timestamp = new StringBuilder();
StringBuilder canonical = new StringBuilder();
StringBuilder canonicalHeaders = new StringBuilder();
StringBuilder signedHeaders = new StringBuilder();
StringBuilder scope = new StringBuilder();
StringBuilder stringToSign = new StringBuilder();
StringBuilder signingKey = new StringBuilder();
StringBuilder authorization = new StringBuilder();
StringBuilder url = new StringBuilder();
StringBuilder query = new StringBuilder();
StringBuilder number = new StringBuilder();
StringBuilder host = new StringBuilder();
StringBuilder uri = new StringBuilder();
Xml xml = new Xml();
String payloadHash = "";
String canonicalHash = "";
String derivedKey = "";
String signature = "";
host.append(bucketName);
host.append(".");
host.append(endpoint.getAsString());
// Encode the original key exactly once, preserving S3 path separators.
uri.setString(http.urlEncode(objectKey));
int replaceCount = uri.replaceNoCase("%2f", "/");
if ((uri.startsWith("/", true)) || ((uri.contains("/../", true)) || (uri.contains("/./", true)))) {
System.out.println("Use a key without a leading slash or dot path segments for these examples.");
return;
}
uri.prepend("/");
FileAccess files = new FileAccess();
String filePath = "qa_data/bin/archive.bin";
String fileSize;
try {
fileSize = files.fileSizeStr(filePath);
} catch (ChilkatException e) {
System.out.println("Could not read source file size.");
return;
}
Crypt2 digest = new Crypt2();
digest.setHashAlgorithm("sha256");
digest.setEncodingMode("hexlower");
String sourceHash;
try {
sourceHash = digest.hashFileENC(filePath);
} catch (ChilkatException e) {
System.out.println("Could not hash source file.");
return;
}
digest.setEncodingMode("base64");
String sourceChecksum;
try {
sourceChecksum = digest.hashFileENC(filePath);
} catch (ChilkatException e) {
System.out.println("Could not compute checksum.");
return;
}
String cacheDir = "qa_output/s3-multipart";
String statePath = "qa_output/s3-multipart/state.json";
String pendingPath = "qa_output/s3-multipart/completion.json";
String receiptPath = "qa_output/s3-multipart/completed.json";
JsonObject state = new JsonObject();
state.setStrict(true);
JsonObject pending = new JsonObject();
pending.setStrict(true);
String uploadToken = "";
String compositeChecksum = "";
try {
files.openForRead(filePath);
} catch (ChilkatException e) {
System.out.println("Could not open immutable source file.");
return;
}
int partSize = 8388608;
int numParts = files.getNumBlocks(partSize);
if ((numParts < 1) || (numParts > 10000)) {
System.out.println("Use a nonempty source of at most 10,000 fixed 8 MiB parts.");
return;
}
Hashtable remoteEtags = new Hashtable();
Hashtable remoteSizes = new Hashtable();
Hashtable remoteChecksums = new Hashtable();
Hashtable partNumbers = new Hashtable();
StringBuilder partNumberText = new StringBuilder();
try {
files.dirEnsureExists(cacheDir);
} catch (ChilkatException e) {
System.out.println("Could not create private checkpoint directory.");
return;
}
DirTree entries = new DirTree();
entries.setBaseDir(cacheDir);
entries.setRecurse(false);
try {
entries.beginIterate();
success = true;
} catch (ChilkatException e) {
success = false;
}
if ((success) || (!entries.getDoneIterating())) {
System.out.println("Start requires an empty checkpoint directory; use resume for an existing upload.");
return;
}
Prng random = new Prng();
try {
uploadToken = random.genRandom(16, "hex");
} catch (ChilkatException e) {
System.out.println("Could not create upload identity.");
return;
}
query.clear();
if (query.getLength() > 0) {
query.append("&");
}
query.append("uploads=");
query.append(http.urlEncode(""));
http.clearHeaders();
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read system time.");
return;
}
timestamp.setString(now.getAsTimestamp(false));
replaceCount = timestamp.replace("-", "");
replaceCount = timestamp.replace(":", "");
String amzDate = timestamp.getAsString();
String dateStamp = timestamp.getRange(0, 8, false);
try {
payloadHash = signer.hashStringENC("");
} catch (ChilkatException e) {
System.out.println("Could not hash payload.");
return;
}
canonicalHeaders.clear();
signedHeaders.clear();
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("host");
canonicalHeaders.append("host:");
canonicalHeaders.append(host.getAsString());
canonicalHeaders.append("\n");
http.setRequestHeader("host", host.getAsString());
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-checksum-algorithm");
canonicalHeaders.append("x-amz-checksum-algorithm:");
canonicalHeaders.append("SHA256");
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-checksum-algorithm", "SHA256");
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-checksum-type");
canonicalHeaders.append("x-amz-checksum-type:");
canonicalHeaders.append("COMPOSITE");
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-checksum-type", "COMPOSITE");
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-content-sha256");
canonicalHeaders.append("x-amz-content-sha256:");
canonicalHeaders.append(payloadHash);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-content-sha256", payloadHash);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-date");
canonicalHeaders.append("x-amz-date:");
canonicalHeaders.append(amzDate);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-date", amzDate);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-meta-source-sha256");
canonicalHeaders.append("x-amz-meta-source-sha256:");
canonicalHeaders.append(sourceHash);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-meta-source-sha256", sourceHash);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-meta-upload-token");
canonicalHeaders.append("x-amz-meta-upload-token:");
canonicalHeaders.append(uploadToken);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-meta-upload-token", uploadToken);
if (credentials.hasMember("session_token")) {
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-security-token");
canonicalHeaders.append("x-amz-security-token:");
canonicalHeaders.append(credentials.stringOf("session_token"));
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-security-token", credentials.stringOf("session_token"));
}
canonical.clear();
canonical.append("POST\n");
canonical.append(uri.getAsString());
canonical.append("\n");
canonical.append(query.getAsString());
canonical.append("\n");
canonical.append(canonicalHeaders.getAsString());
canonical.append("\n");
canonical.append(signedHeaders.getAsString());
canonical.append("\n");
canonical.append(payloadHash);
try {
canonicalHash = signer.hashStringENC(canonical.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not hash canonical request.");
return;
}
scope.clear();
scope.append(dateStamp);
scope.append("/");
scope.append(region);
scope.append("/s3/aws4_request");
stringToSign.clear();
stringToSign.append("AWS4-HMAC-SHA256\n");
stringToSign.append(amzDate);
stringToSign.append("\n");
stringToSign.append(scope.getAsString());
stringToSign.append("\n");
stringToSign.append(canonicalHash);
signingKey.setString("AWS4");
signingKey.append(credentials.stringOf("secret_key"));
try {
signer.setMacKeyString(signingKey.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(dateStamp);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(region);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("s3");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("aws4_request");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
signature = signer.macStringENC(stringToSign.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not sign request.");
return;
}
authorization.clear();
authorization.append("AWS4-HMAC-SHA256 Credential=");
authorization.append(credentials.stringOf("access_key"));
authorization.append("/");
authorization.append(scope.getAsString());
authorization.append(", SignedHeaders=");
authorization.append(signedHeaders.getAsString());
authorization.append(", Signature=");
authorization.append(signature);
http.setRequestHeader("Authorization", authorization.getAsString());
url.setString("https://");
url.append(host.getAsString());
url.append(uri.getAsString());
if (query.getLength() > 0) {
url.append("?");
url.append(query.getAsString());
}
try {
http.httpNoBody("POST", url.getAsString(), response);
success = true;
} catch (ChilkatException e) {
success = false;
}
if ((!success) || (response.getStatusCode() != 200)) {
System.out.println("Request failed or returned unexpected HTTP status: " + response.getStatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
try {
xml.loadXml(response.getBodyStr());
} catch (ChilkatException e) {
System.out.println("Invalid XML response.");
return;
}
stringCompare.setString(xml.getTag());
boolean stringMatch4 = stringCompare.contentsEqual("InitiateMultipartUploadResult", true);
if (!stringMatch4) {
System.out.println("Unexpected XML result, possibly an embedded S3 error. Inspect privately.");
return;
}
String uploadId = xml.getChildContent("UploadId");
stringCompare.setString(uploadId);
boolean stringMatch5 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch5)) {
System.out.println("Missing required UploadId.");
return;
}
System.out.println("Created upload ID: " + uploadId);
// Save the upload ID before sending parts. If saving fails, retain the printed ID.
try {
state.updateString("schema", "1");
} catch (ChilkatException e) {
System.out.println("Could not save schema.");
return;
}
try {
state.updateString("bucket", bucketName);
} catch (ChilkatException e) {
System.out.println("Could not save bucket.");
return;
}
try {
state.updateString("key", objectKey);
} catch (ChilkatException e) {
System.out.println("Could not save key.");
return;
}
try {
state.updateString("region", region);
} catch (ChilkatException e) {
System.out.println("Could not save region.");
return;
}
try {
state.updateString("filePath", filePath);
} catch (ChilkatException e) {
System.out.println("Could not save filePath.");
return;
}
try {
state.updateString("fileSize", fileSize);
} catch (ChilkatException e) {
System.out.println("Could not save fileSize.");
return;
}
try {
state.updateString("sourceHash", sourceHash);
} catch (ChilkatException e) {
System.out.println("Could not save sourceHash.");
return;
}
try {
state.updateString("partSize", "8388608");
} catch (ChilkatException e) {
System.out.println("Could not save partSize.");
return;
}
try {
state.updateString("uploadId", uploadId);
} catch (ChilkatException e) {
System.out.println("Could not save uploadId.");
return;
}
try {
state.updateString("uploadToken", uploadToken);
} catch (ChilkatException e) {
System.out.println("Could not save uploadToken.");
return;
}
try {
state.writeFile("qa_output/s3-multipart/state.json.tmp");
} catch (ChilkatException e) {
System.out.println("Upload was initiated but checkpoint could not be saved; retain its ID.");
return;
}
try {
files.fileRename("qa_output/s3-multipart/state.json.tmp", statePath);
} catch (ChilkatException e) {
System.out.println("Checkpoint rename failed; preserve the temporary checkpoint and upload ID.");
return;
}
BinData part = new BinData();
BinData concatenatedDigests = new BinData();
Xml completion = new Xml();
completion.setTag("CompleteMultipartUpload");
completion.addAttribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
int partIndex = 0;
String partChecksum = "";
String partEtag = "";
String partHash = "";
String confirmed = "";
String sizeText = "";
while (partIndex < numParts) {
part.clear();
try {
files.readBlockBd(partIndex, partSize, part);
} catch (ChilkatException e) {
System.out.println("Could not read source part; preserve checkpoint.");
return;
}
if ((part.getNumBytes() == 0) || ((partIndex < numParts - 1) && (part.getNumBytes() != partSize))) {
System.out.println("Source changed or part read was incomplete.");
return;
}
try {
partChecksum = digest.hashBdENC(part);
} catch (ChilkatException e) {
System.out.println("Could not checksum part.");
return;
}
try {
partHash = signer.hashBdENC(part);
} catch (ChilkatException e) {
System.out.println("Could not hash part.");
return;
}
try {
concatenatedDigests.appendEncoded(partChecksum, "base64");
} catch (ChilkatException e) {
System.out.println("Could not accumulate part digests.");
return;
}
partNumberText.clear();
partNumberText.appendInt(partIndex + 1);
number.clear();
number.appendInt(part.getNumBytes());
sizeText = number.getAsString();
String partNumberKey = partNumberText.getAsString();
boolean reuse = false;
partEtag = "";
if (remoteChecksums.contains(partNumberKey)) {
stringCompare.setString(remoteChecksums.lookupStr(partNumberKey));
boolean stringMatch6 = stringCompare.contentsEqual(partChecksum, true);
stringCompare.setString(remoteSizes.lookupStr(partNumberKey));
boolean stringMatch7 = stringCompare.contentsEqual(sizeText, true);
if ((stringMatch6) && (stringMatch7)) {
partEtag = remoteEtags.lookupStr(partNumberKey);
stringCompare.setString(partEtag);
boolean stringMatch8 = stringCompare.contentsEqual("", true);
if ((remoteEtags.getLastMethodSuccess()) && (!stringMatch8)) {
reuse = true;
}
}
}
if (!reuse) {
query.clear();
if (query.getLength() > 0) {
query.append("&");
}
query.append("partNumber=");
query.append(http.urlEncode(partNumberText.getAsString()));
if (query.getLength() > 0) {
query.append("&");
}
query.append("uploadId=");
query.append(http.urlEncode(uploadId));
http.clearHeaders();
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read system time.");
return;
}
timestamp.setString(now.getAsTimestamp(false));
replaceCount = timestamp.replace("-", "");
replaceCount = timestamp.replace(":", "");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0, 8, false);
payloadHash = partHash;
canonicalHeaders.clear();
signedHeaders.clear();
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("host");
canonicalHeaders.append("host:");
canonicalHeaders.append(host.getAsString());
canonicalHeaders.append("\n");
http.setRequestHeader("host", host.getAsString());
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-checksum-sha256");
canonicalHeaders.append("x-amz-checksum-sha256:");
canonicalHeaders.append(partChecksum);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-checksum-sha256", partChecksum);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-content-sha256");
canonicalHeaders.append("x-amz-content-sha256:");
canonicalHeaders.append(payloadHash);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-content-sha256", payloadHash);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-date");
canonicalHeaders.append("x-amz-date:");
canonicalHeaders.append(amzDate);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-date", amzDate);
if (credentials.hasMember("session_token")) {
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-security-token");
canonicalHeaders.append("x-amz-security-token:");
canonicalHeaders.append(credentials.stringOf("session_token"));
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-security-token", credentials.stringOf("session_token"));
}
canonical.clear();
canonical.append("PUT\n");
canonical.append(uri.getAsString());
canonical.append("\n");
canonical.append(query.getAsString());
canonical.append("\n");
canonical.append(canonicalHeaders.getAsString());
canonical.append("\n");
canonical.append(signedHeaders.getAsString());
canonical.append("\n");
canonical.append(payloadHash);
try {
canonicalHash = signer.hashStringENC(canonical.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not hash canonical request.");
return;
}
scope.clear();
scope.append(dateStamp);
scope.append("/");
scope.append(region);
scope.append("/s3/aws4_request");
stringToSign.clear();
stringToSign.append("AWS4-HMAC-SHA256\n");
stringToSign.append(amzDate);
stringToSign.append("\n");
stringToSign.append(scope.getAsString());
stringToSign.append("\n");
stringToSign.append(canonicalHash);
signingKey.setString("AWS4");
signingKey.append(credentials.stringOf("secret_key"));
try {
signer.setMacKeyString(signingKey.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(dateStamp);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(region);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("s3");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("aws4_request");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
signature = signer.macStringENC(stringToSign.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not sign request.");
return;
}
authorization.clear();
authorization.append("AWS4-HMAC-SHA256 Credential=");
authorization.append(credentials.stringOf("access_key"));
authorization.append("/");
authorization.append(scope.getAsString());
authorization.append(", SignedHeaders=");
authorization.append(signedHeaders.getAsString());
authorization.append(", Signature=");
authorization.append(signature);
http.setRequestHeader("Authorization", authorization.getAsString());
url.setString("https://");
url.append(host.getAsString());
url.append(uri.getAsString());
if (query.getLength() > 0) {
url.append("?");
url.append(query.getAsString());
}
try {
http.httpBd("PUT", url.getAsString(), part, "application/octet-stream", response);
success = true;
} catch (ChilkatException e) {
success = false;
}
if ((!success) || (response.getStatusCode() != 200)) {
System.out.println("Request failed or returned unexpected HTTP status: " + response.getStatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
confirmed = response.getHeaderField("x-amz-checksum-sha256");
stringCompare.setString(confirmed);
boolean stringMatch9 = stringCompare.contentsEqual("", true);
if ((!response.getLastMethodSuccess()) || (stringMatch9)) {
System.out.println("Missing required response header x-amz-checksum-sha256.");
return;
}
stringCompare.setString(confirmed);
boolean stringMatch10 = stringCompare.contentsEqual(partChecksum, true);
if (!stringMatch10) {
System.out.println("Part checksum mismatch; preserve checkpoint.");
return;
}
partEtag = response.getHeaderField("ETag");
stringCompare.setString(partEtag);
boolean stringMatch11 = stringCompare.contentsEqual("", true);
if ((!response.getLastMethodSuccess()) || (stringMatch11)) {
System.out.println("Missing required response header ETag.");
return;
}
} else {
System.out.println("Reusing verified remote part: " + partNumberText.getAsString());
}
completion.setI(partIndex);
completion.updateChildContent("Part[i]|PartNumber", partNumberText.getAsString());
completion.updateChildContent("Part[i]|ETag", partEtag);
completion.updateChildContent("Part[i]|ChecksumSHA256", partChecksum);
partIndex = partIndex + 1;
}
files.fileClose();
// Recheck the entire immutable source before committing its parts.
String finalSourceHash = signer.hashFileENC(filePath);
stringCompare.setString(finalSourceHash);
boolean stringMatch12 = stringCompare.contentsEqual(sourceHash, true);
if ((!signer.getLastMethodSuccess()) || (!stringMatch12)) {
System.out.println("Source changed; completion was not sent.");
return;
}
try {
compositeChecksum = digest.hashBdENC(concatenatedDigests);
} catch (ChilkatException e) {
System.out.println("Could not compute composite checksum.");
return;
}
number.setString(compositeChecksum);
number.append("-");
number.appendInt(numParts);
compositeChecksum = number.getAsString();
try {
pending.updateString("uploadId", uploadId);
} catch (ChilkatException e) {
System.out.println("Could not save uploadId.");
return;
}
try {
pending.updateString("sourceHash", sourceHash);
} catch (ChilkatException e) {
System.out.println("Could not save sourceHash.");
return;
}
try {
pending.updateString("uploadToken", uploadToken);
} catch (ChilkatException e) {
System.out.println("Could not save uploadToken.");
return;
}
try {
pending.updateString("checksum", compositeChecksum);
} catch (ChilkatException e) {
System.out.println("Could not save checksum.");
return;
}
try {
pending.writeFile(pendingPath);
} catch (ChilkatException e) {
System.out.println("Could not save completion recovery record.");
return;
}
String requestBody = completion.getXml();
query.clear();
if (query.getLength() > 0) {
query.append("&");
}
query.append("uploadId=");
query.append(http.urlEncode(uploadId));
http.clearHeaders();
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read system time.");
return;
}
timestamp.setString(now.getAsTimestamp(false));
replaceCount = timestamp.replace("-", "");
replaceCount = timestamp.replace(":", "");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0, 8, false);
try {
payloadHash = signer.hashStringENC(requestBody);
} catch (ChilkatException e) {
System.out.println("Could not hash payload.");
return;
}
canonicalHeaders.clear();
signedHeaders.clear();
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("host");
canonicalHeaders.append("host:");
canonicalHeaders.append(host.getAsString());
canonicalHeaders.append("\n");
http.setRequestHeader("host", host.getAsString());
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-checksum-type");
canonicalHeaders.append("x-amz-checksum-type:");
canonicalHeaders.append("COMPOSITE");
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-checksum-type", "COMPOSITE");
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-content-sha256");
canonicalHeaders.append("x-amz-content-sha256:");
canonicalHeaders.append(payloadHash);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-content-sha256", payloadHash);
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-date");
canonicalHeaders.append("x-amz-date:");
canonicalHeaders.append(amzDate);
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-date", amzDate);
if (credentials.hasMember("session_token")) {
if (signedHeaders.getLength() > 0) {
signedHeaders.append(";");
}
signedHeaders.append("x-amz-security-token");
canonicalHeaders.append("x-amz-security-token:");
canonicalHeaders.append(credentials.stringOf("session_token"));
canonicalHeaders.append("\n");
http.setRequestHeader("x-amz-security-token", credentials.stringOf("session_token"));
}
canonical.clear();
canonical.append("POST\n");
canonical.append(uri.getAsString());
canonical.append("\n");
canonical.append(query.getAsString());
canonical.append("\n");
canonical.append(canonicalHeaders.getAsString());
canonical.append("\n");
canonical.append(signedHeaders.getAsString());
canonical.append("\n");
canonical.append(payloadHash);
try {
canonicalHash = signer.hashStringENC(canonical.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not hash canonical request.");
return;
}
scope.clear();
scope.append(dateStamp);
scope.append("/");
scope.append(region);
scope.append("/s3/aws4_request");
stringToSign.clear();
stringToSign.append("AWS4-HMAC-SHA256\n");
stringToSign.append(amzDate);
stringToSign.append("\n");
stringToSign.append(scope.getAsString());
stringToSign.append("\n");
stringToSign.append(canonicalHash);
signingKey.setString("AWS4");
signingKey.append(credentials.stringOf("secret_key"));
try {
signer.setMacKeyString(signingKey.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(dateStamp);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC(region);
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("s3");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
derivedKey = signer.macStringENC("aws4_request");
} catch (ChilkatException e) {
System.out.println("Could not derive signing key.");
return;
}
try {
signer.setMacKeyEncoded(derivedKey, "hex");
} catch (ChilkatException e) {
System.out.println("Could not set signing key.");
return;
}
try {
signature = signer.macStringENC(stringToSign.getAsString());
} catch (ChilkatException e) {
System.out.println("Could not sign request.");
return;
}
authorization.clear();
authorization.append("AWS4-HMAC-SHA256 Credential=");
authorization.append(credentials.stringOf("access_key"));
authorization.append("/");
authorization.append(scope.getAsString());
authorization.append(", SignedHeaders=");
authorization.append(signedHeaders.getAsString());
authorization.append(", Signature=");
authorization.append(signature);
http.setRequestHeader("Authorization", authorization.getAsString());
url.setString("https://");
url.append(host.getAsString());
url.append(uri.getAsString());
if (query.getLength() > 0) {
url.append("?");
url.append(query.getAsString());
}
try {
http.httpStr("POST", url.getAsString(), requestBody, "utf-8", "application/xml", response);
success = true;
} catch (ChilkatException e) {
success = false;
}
if ((!success) || (response.getStatusCode() != 200)) {
System.out.println("Request failed or returned unexpected HTTP status: " + response.getStatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
try {
xml.loadXml(response.getBodyStr());
} catch (ChilkatException e) {
System.out.println("Invalid XML response.");
return;
}
stringCompare.setString(xml.getTag());
boolean stringMatch13 = stringCompare.contentsEqual("CompleteMultipartUploadResult", true);
if (!stringMatch13) {
System.out.println("Unexpected XML result, possibly an embedded S3 error. Inspect privately.");
return;
}
confirmed = xml.getChildContent("ChecksumSHA256");
stringCompare.setString(confirmed);
boolean stringMatch14 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch14)) {
System.out.println("Missing required ChecksumSHA256.");
return;
}
stringCompare.setString(confirmed);
boolean stringMatch15 = stringCompare.contentsEqual(compositeChecksum, true);
if (!stringMatch15) {
System.out.println("Completion checksum differs; preserve checkpoint and inspect object.");
return;
}
try {
state.updateString("compositeChecksum", compositeChecksum);
} catch (ChilkatException e) {
System.out.println("Could not save compositeChecksum.");
return;
}
try {
state.writeFile("qa_output/s3-multipart/completed.json.tmp");
} catch (ChilkatException e) {
System.out.println("Completion succeeded but receipt could not be saved; preserve the checkpoint.");
return;
}
try {
files.fileRename("qa_output/s3-multipart/completed.json.tmp", receiptPath);
} catch (ChilkatException e) {
System.out.println("Completion receipt remains at its temporary path.");
return;
}
System.out.println("Multipart upload completed and verified.");
}
}