Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions google-cloud-storage/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
<pubsub-proto.version>1.123.5</pubsub-proto.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.cloud.storage;

import com.google.api.core.BetaApi;
import com.google.api.core.InternalExtensionOnly;
import com.google.cloud.storage.multipartupload.model.CreateMultipartUploadRequest;
import com.google.cloud.storage.multipartupload.model.CreateMultipartUploadResponse;
import java.io.IOException;
import java.net.URI;

/**
* A client for interacting with Google Cloud Storage's Multipart Upload API.
*
* <p>This class is for internal use only and is not intended for public consumption. It provides a
* low-level interface for creating and managing multipart uploads.
*
* @see <a href="https://cloud.google.com/storage/docs/multipart-uploads">Multipart Uploads</a>
*/
@BetaApi
@InternalExtensionOnly
public abstract class MultipartUploadClient {

MultipartUploadClient() {}

@BetaApi
public abstract CreateMultipartUploadResponse createMultipartUpload(
CreateMultipartUploadRequest request) throws IOException;

@BetaApi
public static MultipartUploadClient create(MultipartUploadSettings config) {
HttpStorageOptions options = config.getOptions();
return new MultipartUploadClientImpl(
URI.create(options.getHost()),
options.createRetrier(),
MultipartUploadHttpRequestManager.createFrom(options));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.storage;

import com.google.api.core.BetaApi;
import com.google.cloud.storage.Retrying.Retrier;
import com.google.cloud.storage.multipartupload.model.CreateMultipartUploadRequest;
import com.google.cloud.storage.multipartupload.model.CreateMultipartUploadResponse;
import java.io.IOException;
import java.net.URI;

/**
* This class is an implementation of {@link MultipartUploadClient} that uses the Google Cloud
* Storage XML API to perform multipart uploads.
*/
@BetaApi
final class MultipartUploadClientImpl extends MultipartUploadClient {

private final MultipartUploadHttpRequestManager httpRequestManager;
private final Retrier retrier;
private final URI uri;

MultipartUploadClientImpl(
URI uri,
Retrier retrier,
MultipartUploadHttpRequestManager multipartUploadHttpRequestManager) {
this.httpRequestManager = multipartUploadHttpRequestManager;
this.retrier = retrier;
this.uri = uri;
}

@BetaApi
public CreateMultipartUploadResponse createMultipartUpload(CreateMultipartUploadRequest request)
throws IOException {
return httpRequestManager.sendCreateMultipartUploadRequest(uri, request);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.storage;

import static com.google.cloud.storage.Utils.ifNonNull;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.util.ObjectParser;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.api.services.storage.Storage;
import com.google.cloud.storage.multipartupload.model.CreateMultipartUploadRequest;
import com.google.cloud.storage.multipartupload.model.CreateMultipartUploadResponse;
import com.google.common.base.StandardSystemProperty;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final class MultipartUploadHttpRequestManager {

private final HttpRequestFactory requestFactory;
private final ObjectParser objectParser;
private final HeaderProvider headerProvider;

MultipartUploadHttpRequestManager(
HttpRequestFactory requestFactory, ObjectParser objectParser, HeaderProvider headerProvider) {
this.requestFactory = requestFactory;
this.objectParser = objectParser;
this.headerProvider = headerProvider;
}

CreateMultipartUploadResponse sendCreateMultipartUploadRequest(
URI uri, CreateMultipartUploadRequest request) throws IOException {

String encodedBucket = urlEncode(request.bucket());
String encodedKey = urlEncode(request.key());
String resourcePath = "/" + encodedBucket + "/" + encodedKey;
String createUri = uri.toString() + resourcePath + "?uploads";

HttpRequest httpRequest =
requestFactory.buildPostRequest(
new GenericUrl(createUri), new ByteArrayContent(request.getContentType(), new byte[0]));
httpRequest.getHeaders().putAll(headerProvider.getHeaders());
addHeadersForCreateMultipartUpload(request, httpRequest.getHeaders());
httpRequest.setParser(objectParser);
httpRequest.setThrowExceptionOnExecuteError(true);
return httpRequest.execute().parseAs(CreateMultipartUploadResponse.class);
}

@SuppressWarnings("DataFlowIssue")
static MultipartUploadHttpRequestManager createFrom(HttpStorageOptions options) {
Storage storage = options.getStorageRpcV1().getStorage();
ImmutableMap.Builder<String, String> stableHeaders =
ImmutableMap.<String, String>builder()
// http-java-client will automatically append its own version to the user-agent
.put("User-Agent", "gcloud-java/" + options.getLibraryVersion())
.put(
"x-goog-api-client",
String.format(
"gl-java/%s gccl/%s %s/%s",
GaxProperties.getJavaVersion(),
options.getLibraryVersion(),
formatName(StandardSystemProperty.OS_NAME.value()),
formatSemver(StandardSystemProperty.OS_VERSION.value())));
ifNonNull(options.getProjectId(), pid -> stableHeaders.put("x-goog-user-project", pid));
return new MultipartUploadHttpRequestManager(
storage.getRequestFactory(),
new XmlObjectParser(new XmlMapper()),
options.getMergedHeaderProvider(FixedHeaderProvider.create(stableHeaders.build())));
}

private void addHeadersForCreateMultipartUpload(
CreateMultipartUploadRequest request, HttpHeaders headers) {
// TODO(shreyassinha): add a PredefinedAcl::getXmlEntry with the corresponding value from
// https://cloud.google.com/storage/docs/xml-api/reference-headers#xgoogacl
if (request.getCannedAcl() != null) {
headers.put("x-goog-acl", request.getCannedAcl().toString());
}
// TODO(shreyassinha) Add encoding for x-goog-meta-* headers
if (request.getMetadata() != null) {
for (Map.Entry<String, String> entry : request.getMetadata().entrySet()) {
if (entry.getKey() != null || entry.getValue() != null) {
headers.put("x-goog-meta-" + entry.getKey(), entry.getValue());
}
}
}
if (request.getStorageClass() != null) {
headers.put("x-goog-storage-class", request.getStorageClass().toString());
}
if (request.getKmsKeyName() != null && !request.getKmsKeyName().isEmpty()) {
headers.put("x-goog-encryption-kms-key-name", request.getKmsKeyName());
}
if (request.getObjectLockMode() != null) {
headers.put("x-goog-object-lock-mode", request.getObjectLockMode().toString());
}
if (request.getObjectLockRetainUntilDate() != null) {
headers.put(
"x-goog-object-lock-retain-until-date",
Utils.offsetDateTimeRfc3339Codec.encode(request.getObjectLockRetainUntilDate()));
}
if (request.getCustomTime() != null) {
headers.put(
"x-goog-custom-time", Utils.offsetDateTimeRfc3339Codec.encode(request.getCustomTime()));
}
}

private static String urlEncode(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
}

private static String formatName(String name) {
// Only lowercase letters, digits, and "-" are allowed
return name.toLowerCase().replaceAll("[^\\w\\d\\-]", "-");
}

private static String formatSemver(String version) {
return formatSemver(version, version);
}

private static String formatSemver(String version, String defaultValue) {
if (version == null) {
return null;
}

// Take only the semver version: x.y.z-a_b_c -> x.y.z
Matcher m = Pattern.compile("(\\d+\\.\\d+\\.\\d+).*").matcher(version);
if (m.find()) {
return m.group(1);
} else {
return defaultValue;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.storage;

import com.google.api.core.BetaApi;

/**
* Settings for configuring the {@link MultipartUploadClient}.
*
* <p>This class is for internal use only and is not intended for public consumption.
*/
@BetaApi
public final class MultipartUploadSettings {
private final HttpStorageOptions options;

/**
* Constructs a {@code MultipartUploadSettings} instance.
*
* @param options The {@link HttpStorageOptions} to use for multipart uploads.
*/
private MultipartUploadSettings(HttpStorageOptions options) {
this.options = options;
}

/**
* Returns the {@link HttpStorageOptions} configured for multipart uploads.
*
* @return The {@link HttpStorageOptions}.
*/
@BetaApi
public HttpStorageOptions getOptions() {
return options;
}

/**
* Creates a new {@code MultipartUploadSettings} instance with the specified {@link
* HttpStorageOptions}.
*
* @param options The {@link HttpStorageOptions} to use.
* @return A new {@code MultipartUploadSettings} instance.
*/
@BetaApi
public static MultipartUploadSettings of(HttpStorageOptions options) {
return new MultipartUploadSettings(options);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ final class Utils {
static final Codec<Duration, Long> durationSecondsCodec =
Codec.of(Duration::getSeconds, Duration::ofSeconds);

static final Codec<OffsetDateTime, String> offsetDateTimeRfc3339Codec =
Codec.of(
RFC_3339_DATE_TIME_FORMATTER::format,
s -> OffsetDateTime.parse(s, RFC_3339_DATE_TIME_FORMATTER));

@VisibleForTesting
static final Codec<OffsetDateTime, DateTime> dateTimeCodec =
Codec.of(
Expand Down
Loading