This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 1ca4c74b43 feat(bindings/java): support additional read options (#8474)
1ca4c74b43 is described below
commit 1ca4c74b43d44e52f7aa95347b2901f702dde1b0
Author: 纪华裕 <[email protected]>
AuthorDate: Sun Nov 22 05:27:34 2026 +0800
feat(bindings/java): support additional read options (#8474)
* feat(bindings/java): complete ReadOptions bindings
* test(bindings/java): streamline ReadOptions tests
* docs(java): simplify ReadOptions guidance
* feat(bindings/java): expose all core capability fields
* fix(bindings/java): scope capability additions to read options
* refactor(bindings/java): keep a single capability constructor
* refactor(bindings/java): share read execution option validation
* update
* fix(bindings/java): initialize read capabilities in constructor
* test(bindings/java): finish requests before bodyless read responses
Close the request body before sending HEAD and precondition responses so
the HTTP fixture can reuse connections for subsequent concurrent range requests.
* fix(bindings/java): retain the existing Capability constructor
Keep the original constructor descriptor for Java callers and delegate with
the new read capability flags disabled. JNI continues to supply the flags
through the expanded constructor.
---------
Co-authored-by: Xuanwo <[email protected]>
---
bindings/java/src/async_operator.rs | 5 +-
bindings/java/src/lib.rs | 99 ++++--
.../main/java/org/apache/opendal/Capability.java | 129 ++++++++
.../org/apache/opendal/OperatorInputStream.java | 14 +-
.../main/java/org/apache/opendal/ReadOptions.java | 79 ++++-
.../org/apache/opendal/test/OperatorInfoTest.java | 44 +++
.../org/apache/opendal/test/ReadOptionsTest.java | 343 +++++++++++++++++++++
website/docs/20-bindings/java/04-tasks.md | 26 ++
8 files changed, 706 insertions(+), 33 deletions(-)
diff --git a/bindings/java/src/async_operator.rs
b/bindings/java/src/async_operator.rs
index 438a9efd18..c174814a56 100644
--- a/bindings/java/src/async_operator.rs
+++ b/bindings/java/src/async_operator.rs
@@ -204,14 +204,15 @@ fn intern_read(
options: JObject,
) -> Result<jlong> {
// Prepare inputs before spawning
- let id = request_id(env)?;
let path_str = jstring_to_string(env, &path)?;
let read_opts = make_read_options(env, &options)?;
// Clone operator handle to move into the task
let op_cloned = unsafe { &*op }.clone();
- executor_or_default(env, executor)?.spawn(async move {
+ let executor = executor_or_default(env, executor)?;
+ let id = request_id(env)?;
+ executor.spawn(async move {
let result = op_cloned.read_options(&path_str, read_opts).await;
complete_future(id, move |env| {
let buffer = result?;
diff --git a/bindings/java/src/lib.rs b/bindings/java/src/lib.rs
index de7839548d..c3bc1e9656 100644
--- a/bindings/java/src/lib.rs
+++ b/bindings/java/src/lib.rs
@@ -95,7 +95,7 @@ fn make_operator_info<'a>(env: &mut Env<'a>, info:
OperatorInfo) -> Result<JObje
fn make_capability<'a>(env: &mut Env<'a>, cap: Capability) ->
Result<JObject<'a>> {
let capability = env.new_object(
jni_str!("org/apache/opendal/Capability"),
- jni_sig!("(ZZZZZZZZZZZZZZZZZZZZZZZZJJZZZZZZZZZZZZZZZ)V"),
+ jni_sig!("(ZZZZZZZZZZZZZZZZZZZZZZZZJJZZZZZZZZZZZZZZZZZZZZ)V"),
&[
JValue::Bool(cap.stat),
JValue::Bool(cap.stat_with_if_match),
@@ -138,6 +138,11 @@ fn make_capability<'a>(env: &mut Env<'a>, cap: Capability)
-> Result<JObject<'a>
JValue::Bool(cap.presign_stat),
JValue::Bool(cap.presign_write),
JValue::Bool(cap.shared),
+ JValue::Bool(cap.read_with_version),
+ JValue::Bool(cap.read_with_if_version_match),
+ JValue::Bool(cap.read_with_if_version_not_match),
+ JValue::Bool(cap.read_with_if_modified_since),
+ JValue::Bool(cap.read_with_if_unmodified_since),
],
)?;
Ok(capability)
@@ -287,6 +292,41 @@ fn make_stat_options(env: &mut Env, options: &JObject) ->
Result<opendal::option
})
}
+fn validate_read_execution_options(
+ concurrent: i32,
+ chunk: i64,
+ content_length_hint: i64,
+) -> Result<(usize, Option<usize>, Option<u64>)> {
+ if concurrent <= 0 {
+ return Err(Error::new(ErrorKind::ConfigInvalid, "concurrent must be
positive").into());
+ }
+ let concurrent = usize::try_from(concurrent)
+ .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "concurrent is too
large"))?;
+ let chunk = match chunk {
+ -1 => None,
+ value if value > 0 => Some(
+ usize::try_from(value)
+ .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "chunk is
too large"))?,
+ ),
+ _ => {
+ return Err(
+ Error::new(ErrorKind::ConfigInvalid, "chunk must be -1 or
positive").into(),
+ );
+ }
+ };
+ let content_length_hint = match content_length_hint {
+ -1 => None,
+ value => Some(u64::try_from(value).map_err(|_| {
+ Error::new(
+ ErrorKind::ConfigInvalid,
+ "contentLengthHint must be -1 or non-negative",
+ )
+ })?),
+ };
+
+ Ok((concurrent, chunk, content_length_hint))
+}
+
fn make_read_options<'a>(
env: &mut Env<'a>,
options: &JObject,
@@ -294,8 +334,35 @@ fn make_read_options<'a>(
let offset = convert::read_int64_field(env, options, "offset")?;
let length = convert::read_int64_field(env, options, "length")?;
+ let concurrent = convert::read_int_field(env, options, "concurrent")?;
+ let chunk = convert::read_int64_field(env, options, "chunk")?;
+ let content_length_hint = convert::read_int64_field(env, options,
"contentLengthHint")?;
+
+ let (concurrent, chunk, content_length_hint) =
+ validate_read_execution_options(concurrent, chunk,
content_length_hint)?;
+
Ok(opendal::options::ReadOptions {
range: convert::offset_length_to_range(offset, length)?.into(),
+ limit: None,
+ version: convert::read_string_field(env, options, "version")?,
+ if_match: convert::read_string_field(env, options, "ifMatch")?,
+ if_none_match: convert::read_string_field(env, options,
"ifNoneMatch")?,
+ if_version_match: convert::read_string_field(env, options,
"ifVersionMatch")?,
+ if_version_not_match: convert::read_string_field(env, options,
"ifVersionNotMatch")?,
+ if_modified_since: convert::read_instant_field_to_timestamp(
+ env,
+ options,
+ "ifModifiedSince",
+ )?,
+ if_unmodified_since: convert::read_instant_field_to_timestamp(
+ env,
+ options,
+ "ifUnmodifiedSince",
+ )?,
+ concurrent,
+ chunk,
+ gap: None,
+ content_length_hint,
override_content_type: convert::read_string_field(env, options,
"overrideContentType")?,
override_cache_control: convert::read_string_field(env, options,
"overrideCacheControl")?,
override_content_disposition: convert::read_string_field(
@@ -303,7 +370,6 @@ fn make_read_options<'a>(
options,
"overrideContentDisposition",
)?,
- ..Default::default()
})
}
@@ -316,34 +382,11 @@ fn make_reader_options(
let prefetch = convert::read_int_field(env, options, "prefetch")?;
let content_length_hint = convert::read_int64_field(env, options,
"contentLengthHint")?;
- if concurrent <= 0 {
- return Err(Error::new(ErrorKind::ConfigInvalid, "concurrent must be
positive").into());
- }
- let concurrent = usize::try_from(concurrent)
- .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "concurrent is too
large"))?;
- let chunk = match chunk {
- -1 => None,
- value if value > 0 => Some(
- usize::try_from(value)
- .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "chunk is
too large"))?,
- ),
- _ => {
- return Err(
- Error::new(ErrorKind::ConfigInvalid, "chunk must be -1 or
positive").into(),
- );
- }
- };
+ let (concurrent, chunk, content_length_hint) =
+ validate_read_execution_options(concurrent, chunk,
content_length_hint)?;
+
let prefetch = usize::try_from(prefetch)
.map_err(|_| Error::new(ErrorKind::ConfigInvalid, "prefetch must be
non-negative"))?;
- let content_length_hint = match content_length_hint {
- -1 => None,
- value => Some(u64::try_from(value).map_err(|_| {
- Error::new(
- ErrorKind::ConfigInvalid,
- "contentLengthHint must be -1 or non-negative",
- )
- })?),
- };
Ok(opendal::options::ReaderOptions {
version: convert::read_string_field(env, options, "version")?,
diff --git a/bindings/java/src/main/java/org/apache/opendal/Capability.java
b/bindings/java/src/main/java/org/apache/opendal/Capability.java
index 53617057bb..6c36dac27a 100644
--- a/bindings/java/src/main/java/org/apache/opendal/Capability.java
+++ b/bindings/java/src/main/java/org/apache/opendal/Capability.java
@@ -79,6 +79,31 @@ public class Capability {
*/
public final boolean readWithIfNoneMatch;
+ /**
+ * If operator supports reads with stored version selection.
+ */
+ public final boolean readWithVersion;
+
+ /**
+ * If operator supports reads with a version match condition.
+ */
+ public final boolean readWithIfVersionMatch;
+
+ /**
+ * If operator supports reads with a version non-match condition.
+ */
+ public final boolean readWithIfVersionNotMatch;
+
+ /**
+ * If operator supports reads with an If-Modified-Since condition.
+ */
+ public final boolean readWithIfModifiedSince;
+
+ /**
+ * If operator supports reads with an If-Unmodified-Since condition.
+ */
+ public final boolean readWithIfUnmodifiedSince;
+
/**
* If operator supports read with override cache control.
*/
@@ -232,6 +257,9 @@ public class Capability {
*/
public final boolean shared;
+ /**
+ * Creates capabilities with the read version and timestamp flags set to
false.
+ */
public Capability(
boolean stat,
boolean statWithIfMatch,
@@ -274,6 +302,102 @@ public class Capability {
boolean presignStat,
boolean presignWrite,
boolean shared) {
+ this(
+ stat,
+ statWithIfMatch,
+ statWithIfNoneMatch,
+ statWithIfVersionMatch,
+ statWithIfVersionNotMatch,
+ statWithIfModifiedSince,
+ statWithIfUnmodifiedSince,
+ statWithVersion,
+ read,
+ readWithIfMatch,
+ readWithIfNoneMatch,
+ readWithOverrideCacheControl,
+ readWithOverrideContentDisposition,
+ readWithOverrideContentType,
+ write,
+ writeCanMulti,
+ writeCanAppend,
+ writeWithContentType,
+ writeWithContentDisposition,
+ writeWithCacheControl,
+ writeWithIfMatch,
+ writeWithIfNoneMatch,
+ writeWithIfNotExists,
+ writeWithUserMetadata,
+ writeMultiMaxSize,
+ writeMultiMinSize,
+ createDir,
+ delete,
+ copy,
+ rename,
+ list,
+ listWithLimit,
+ listWithStartAfter,
+ listWithRecursive,
+ listWithVersions,
+ listWithDeleted,
+ presign,
+ presignRead,
+ presignStat,
+ presignWrite,
+ shared,
+ false,
+ false,
+ false,
+ false,
+ false);
+ }
+
+ public Capability(
+ boolean stat,
+ boolean statWithIfMatch,
+ boolean statWithIfNoneMatch,
+ boolean statWithIfVersionMatch,
+ boolean statWithIfVersionNotMatch,
+ boolean statWithIfModifiedSince,
+ boolean statWithIfUnmodifiedSince,
+ boolean statWithVersion,
+ boolean read,
+ boolean readWithIfMatch,
+ boolean readWithIfNoneMatch,
+ boolean readWithOverrideCacheControl,
+ boolean readWithOverrideContentDisposition,
+ boolean readWithOverrideContentType,
+ boolean write,
+ boolean writeCanMulti,
+ boolean writeCanAppend,
+ boolean writeWithContentType,
+ boolean writeWithContentDisposition,
+ boolean writeWithCacheControl,
+ boolean writeWithIfMatch,
+ boolean writeWithIfNoneMatch,
+ boolean writeWithIfNotExists,
+ boolean writeWithUserMetadata,
+ long writeMultiMaxSize,
+ long writeMultiMinSize,
+ boolean createDir,
+ boolean delete,
+ boolean copy,
+ boolean rename,
+ boolean list,
+ boolean listWithLimit,
+ boolean listWithStartAfter,
+ boolean listWithRecursive,
+ boolean listWithVersions,
+ boolean listWithDeleted,
+ boolean presign,
+ boolean presignRead,
+ boolean presignStat,
+ boolean presignWrite,
+ boolean shared,
+ boolean readWithVersion,
+ boolean readWithIfVersionMatch,
+ boolean readWithIfVersionNotMatch,
+ boolean readWithIfModifiedSince,
+ boolean readWithIfUnmodifiedSince) {
this.stat = stat;
this.statWithIfMatch = statWithIfMatch;
this.statWithIfNoneMatch = statWithIfNoneMatch;
@@ -315,5 +439,10 @@ public class Capability {
this.presignStat = presignStat;
this.presignWrite = presignWrite;
this.shared = shared;
+ this.readWithVersion = readWithVersion;
+ this.readWithIfVersionMatch = readWithIfVersionMatch;
+ this.readWithIfVersionNotMatch = readWithIfVersionNotMatch;
+ this.readWithIfModifiedSince = readWithIfModifiedSince;
+ this.readWithIfUnmodifiedSince = readWithIfUnmodifiedSince;
}
}
diff --git
a/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
b/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
index 395911d6e3..e755a2efd6 100644
--- a/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
+++ b/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
@@ -51,7 +51,19 @@ public class OperatorInputStream extends InputStream {
public OperatorInputStream(Operator operator, String path, ReadOptions
options) {
Objects.requireNonNull(options, "options");
- try (OperatorReader source = operator.createReader(path)) {
+ ReaderOptions readerOptions = ReaderOptions.builder()
+ .version(options.version)
+ .ifMatch(options.ifMatch)
+ .ifNoneMatch(options.ifNoneMatch)
+ .ifVersionMatch(options.ifVersionMatch)
+ .ifVersionNotMatch(options.ifVersionNotMatch)
+ .ifModifiedSince(options.ifModifiedSince)
+ .ifUnmodifiedSince(options.ifUnmodifiedSince)
+ .concurrent(options.concurrent)
+ .chunk(options.chunk)
+ .contentLengthHint(options.contentLengthHint)
+ .build();
+ try (OperatorReader source = operator.createReader(path,
readerOptions)) {
this.iterator = new
NativeIterator(source.createBytesIterator(options.offset, options.length));
}
}
diff --git a/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
b/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
index d3acb431fa..3e74cfce82 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
@@ -19,21 +19,96 @@
package org.apache.opendal;
+import java.time.Instant;
import lombok.Builder;
+/**
+ * Options for a single read or a compatibility input stream.
+ * Version selection and conditions require service support and apply to every
chunk.
+ * Unsupported conditions fail with {@code Unsupported}; a failed condition on
an existing
+ * file fails with {@code ConditionNotMatch}. Optional reference fields
default to null.
+ * Invalid execution values fail with {@code ConfigInvalid}; an Instant
outside the
+ * Rust core timestamp range fails with {@code Unexpected}.
+ */
@Builder
public class ReadOptions {
/**
- * Sets the offset of the read operation.
+ * Starting byte offset. Must be non-negative; defaults to zero.
*/
public final long offset;
/**
- * Sets the length of the read operation.
+ * Number of bytes to read. The default of -1 reads to the end; zero
selects an empty range.
*/
@Builder.Default
public final long length = -1;
+ /**
+ * Selects a stored file version instead of the current one. This is not a
condition.
+ * Requires service support for reading versions; a missing version fails
with NotFound.
+ */
+ public final String version;
+
+ /**
+ * Reads only when the file has this exact ETag. Requires service support
for if-match reads.
+ * Only concrete ETags are portable; a wildcard such as "*" has no
portable meaning.
+ */
+ public final String ifMatch;
+
+ /**
+ * Reads only when the file exists with a different ETag. Requires service
support for
+ * if-none-match reads. Only concrete ETags are portable; "*" has no
portable meaning.
+ */
+ public final String ifNoneMatch;
+
+ /**
+ * Reads only when the file has this exact version. Requires service
support for version-match reads.
+ * This checks the selected file's identity rather than selecting a stored
version.
+ */
+ public final String ifVersionMatch;
+
+ /**
+ * Reads only when the file exists with a different version.
+ * Requires service support for version-not-match reads.
+ */
+ public final String ifVersionNotMatch;
+
+ /**
+ * Reads only when the file was modified after this time.
+ * Requires service support for if-modified-since reads.
+ */
+ public final Instant ifModifiedSince;
+
+ /**
+ * Reads only when the file was not modified after this time.
+ * Requires service support for if-unmodified-since reads.
+ */
+ public final Instant ifUnmodifiedSince;
+
+ /**
+ * Maximum number of internal chunk requests executed concurrently. Must
be positive.
+ * This is not the number of application transfers or Java threads and
only affects chunked reads.
+ */
+ @Builder.Default
+ public final int concurrent = 1;
+
+ /**
+ * Target size of each internal range request, in bytes. A positive value
enables chunked reads.
+ * The default of -1 keeps unchunked streaming. Zero and other negative
values are invalid.
+ * The value must fit the native platform's unsigned pointer-sized integer.
+ */
+ @Builder.Default
+ public final long chunk = -1L;
+
+ /**
+ * Known full object content length in bytes, independent of the requested
range.
+ * The default of -1 means unknown; zero is valid for an empty object.
+ * This hint can avoid a metadata request and is not a consistency
condition.
+ * An incorrect hint can cause incomplete reads or errors. Values below -1
are invalid.
+ */
+ @Builder.Default
+ public final long contentLengthHint = -1L;
+
/**
* Overrides the Content-Type response header when the service supports it.
* Also applies to presigned read requests.
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInfoTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInfoTest.java
index 7fa8c5afe8..1a33cdfa3c 100644
--- a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInfoTest.java
+++ b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInfoTest.java
@@ -22,6 +22,7 @@ package org.apache.opendal.test;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.file.Path;
import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.Capability;
import org.apache.opendal.Operator;
import org.apache.opendal.OperatorInfo;
import org.apache.opendal.ServiceConfig;
@@ -91,4 +92,47 @@ public class OperatorInfoTest {
assertThat(notMatchOp.info.capability.statWithIfVersionNotMatch).isTrue();
}
}
+
+ @Test
+ public void testReadConditionCapabilities() {
+ String[] flags = {
+ "read_with_version",
+ "read_with_if_version_match",
+ "read_with_if_version_not_match",
+ "read_with_if_modified_since",
+ "read_with_if_unmodified_since"
+ };
+ String allDisabled = String.join("=false,", flags) + "=false";
+ try (AsyncOperator base =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ AsyncOperator none = base.layer(new
CapabilityOverrideLayer(allDisabled))) {
+ for (int i = 0; i < flags.length; i++) {
+ boolean[] expected = new boolean[flags.length];
+ expected[i] = true;
+ try (AsyncOperator enabled = none.layer(new
CapabilityOverrideLayer(flags[i] + "=true"));
+ AsyncOperator disabled = enabled.layer(new
CapabilityOverrideLayer(flags[i] + "=false"))) {
+ Capability enabledCapability = enabled.info.capability;
+ assertThat(new boolean[] {
+ enabledCapability.readWithVersion,
+ enabledCapability.readWithIfVersionMatch,
+ enabledCapability.readWithIfVersionNotMatch,
+ enabledCapability.readWithIfModifiedSince,
+ enabledCapability.readWithIfUnmodifiedSince
+ })
+ .as("enabling %s", flags[i])
+ .containsExactly(expected);
+ Capability disabledCapability = disabled.info.capability;
+ assertThat(new boolean[] {
+ disabledCapability.readWithVersion,
+ disabledCapability.readWithIfVersionMatch,
+ disabledCapability.readWithIfVersionNotMatch,
+ disabledCapability.readWithIfModifiedSince,
+ disabledCapability.readWithIfUnmodifiedSince
+ })
+ .as("disabling %s", flags[i])
+ .containsOnly(false);
+ }
+ }
+ }
+ }
}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/ReadOptionsTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/ReadOptionsTest.java
new file mode 100644
index 0000000000..8b0b1226af
--- /dev/null
+++ b/bindings/java/src/test/java/org/apache/opendal/test/ReadOptionsTest.java
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.opendal.test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import com.sun.net.httpserver.Headers;
+import com.sun.net.httpserver.HttpServer;
+import java.lang.reflect.Field;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.stream.Stream;
+import org.apache.commons.io.IOUtils;
+import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.OpenDALException;
+import org.apache.opendal.Operator;
+import org.apache.opendal.OperatorInputStream;
+import org.apache.opendal.ReadOptions;
+import org.apache.opendal.ServiceConfig;
+import org.apache.opendal.test.condition.OpenDALExceptionCondition;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Verifies option forwarding through blocking, async, and compatibility
stream reads. */
+@Timeout(10)
+public class ReadOptionsTest {
+ private static final byte[] CONTENT =
"0123456789".getBytes(StandardCharsets.UTF_8);
+ private final List<Headers> requests = new CopyOnWriteArrayList<>();
+ private final List<String> methods = new CopyOnWriteArrayList<>();
+ private final List<URI> urls = new CopyOnWriteArrayList<>();
+ private HttpServer server;
+ private String endpoint;
+
+ private void startServer() throws Exception {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext("/", exchange -> {
+ try {
+ requests.add(exchange.getRequestHeaders());
+ methods.add(exchange.getRequestMethod());
+ urls.add(exchange.getRequestURI());
+ if
("changed".equals(exchange.getRequestHeaders().getFirst("If-Match"))) {
+ // Finish the request before the bodyless response
completes the exchange.
+ exchange.getRequestBody().close();
+ exchange.sendResponseHeaders(412, -1);
+ return;
+ }
+ if ("HEAD".equals(exchange.getRequestMethod())) {
+ exchange.getRequestBody().close();
+ exchange.getResponseHeaders().set("Content-Length",
Integer.toString(CONTENT.length));
+ exchange.sendResponseHeaders(200, -1);
+ return;
+ }
+ final String range =
exchange.getRequestHeaders().getFirst("Range");
+ final byte[] body;
+ if (range != null) {
+ String[] bounds =
range.substring("bytes=".length()).split("-", -1);
+ int start = Integer.parseInt(bounds[0]);
+ int end = bounds[1].isEmpty() ? CONTENT.length - 1 :
Integer.parseInt(bounds[1]);
+ body = Arrays.copyOfRange(CONTENT, start, end + 1);
+ exchange.getResponseHeaders()
+ .set("Content-Range", "bytes " + start + "-" + end
+ "/" + CONTENT.length);
+ } else {
+ body = CONTENT;
+ }
+ exchange.getResponseHeaders().set("ETag", "\"etag\"");
+ exchange.sendResponseHeaders(range == null ? 200 : 206,
body.length);
+ exchange.getResponseBody().write(body);
+ } finally {
+ exchange.close();
+ }
+ });
+ server.start();
+ endpoint = "http://127.0.0.1:" + server.getAddress().getPort();
+ }
+
+ @AfterEach
+ void stopServer() {
+ if (server != null) {
+ server.stop(0);
+ }
+ }
+
+ @Test
+ void testConditionsAndRangeReachEveryChunk() throws Exception {
+ startServer();
+ ReadOptions options = ReadOptions.builder()
+ .offset(2)
+ .length(4)
+ .ifMatch("\"etag\"")
+ .ifNoneMatch("\"other\"")
+ .ifModifiedSince(Instant.parse("2024-01-01T00:00:00Z"))
+ .ifUnmodifiedSince(Instant.parse("2024-01-02T00:00:00Z"))
+ .chunk(2)
+ .concurrent(2)
+ .contentLengthHint(CONTENT.length)
+ .build();
+ try (AsyncOperator async = AsyncOperator.of(
+
ServiceConfig.Http.builder().endpoint(endpoint).build());
+ Operator op = async.blocking()) {
+ assertReads(op, async, "file", options, "2345");
+ }
+ assertThat(methods).containsOnly("GET").hasSize(6);
+ assertThat(requests)
+ .extracting(headers -> headers.getFirst("Range"))
+ .containsExactlyInAnyOrder(
+ "bytes=2-3", "bytes=4-5", "bytes=2-3", "bytes=4-5",
"bytes=2-3", "bytes=4-5");
+ for (Headers headers : requests) {
+ assertThat(headers.getFirst("If-Match")).isEqualTo("\"etag\"");
+
assertThat(headers.getFirst("If-None-Match")).isEqualTo("\"other\"");
+ assertThat(headers.getFirst("If-Modified-Since")).isEqualTo("Mon,
01 Jan 2024 00:00:00 GMT");
+
assertThat(headers.getFirst("If-Unmodified-Since")).isEqualTo("Tue, 02 Jan 2024
00:00:00 GMT");
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {-1, 10})
+ void testUnboundedChunkedReadsUseContentLengthHint(long hint) throws
Exception {
+ startServer();
+ ReadOptions options = ReadOptions.builder()
+ .chunk(2)
+ .concurrent(2)
+ .contentLengthHint(hint)
+ .build();
+ try (AsyncOperator async = AsyncOperator.of(
+
ServiceConfig.Http.builder().endpoint(endpoint).build());
+ Operator op = async.blocking()) {
+ assertThat(op.read("file", options)).isEqualTo(CONTENT);
+
assertThat(methods.stream().filter("HEAD"::equals).count()).isEqualTo(hint ==
-1 ? 1 : 0);
+ assertThat(async.read("file", options).join()).isEqualTo(CONTENT);
+
assertThat(methods.stream().filter("HEAD"::equals).count()).isEqualTo(hint ==
-1 ? 2 : 0);
+ try (OperatorInputStream in = op.createInputStream("file",
options)) {
+ assertThat(IOUtils.toByteArray(in)).isEqualTo(CONTENT);
+ }
+ }
+
assertThat(methods.stream().filter("GET"::equals).count()).isEqualTo(15);
+
assertThat(methods.stream().filter("HEAD"::equals).count()).isEqualTo(hint ==
-1 ? 3 : 0);
+ for (String range : Arrays.asList("bytes=0-1", "bytes=2-3",
"bytes=4-5", "bytes=6-7", "bytes=8-9")) {
+ assertThat(requests.stream()
+ .filter(headers ->
range.equals(headers.getFirst("Range")))
+ .count())
+ .isEqualTo(3);
+ }
+ }
+
+ @Test
+ void testVersionSelection() throws Exception {
+ startServer();
+ try (AsyncOperator async = AsyncOperator.of(ServiceConfig.S3
+ .builder()
+ .bucket("bucket")
+ .region("us-east-1")
+ .endpoint(endpoint)
+ .skipSignature(true)
+ .build());
+ Operator op = async.blocking()) {
+ assertReads(
+ op,
+ async,
+ "file",
+
ReadOptions.builder().version("version-one").length(2).build(),
+ "01");
+ }
+ assertThat(urls).hasSize(3);
+ for (URI uri : urls) {
+ assertThat(uri.getQuery()).contains("versionId=version-one");
+ }
+ }
+
+ @Test
+ void testVersionConditions() throws Exception {
+ startServer();
+ try (AsyncOperator async = AsyncOperator.of(ServiceConfig.Gcs.builder()
+ .bucket("bucket")
+ .endpoint(endpoint)
+ .skipSignature(true)
+ .build());
+ Operator op = async.blocking()) {
+ assertReads(
+ op,
+ async,
+ "file",
+ ReadOptions.builder()
+ .ifVersionMatch("17")
+ .ifVersionNotMatch("18")
+ .length(2)
+ .build(),
+ "01");
+ }
+ assertThat(urls).hasSize(3);
+ for (URI uri : urls) {
+ assertThat(uri.getQuery()).contains("ifGenerationMatch=17",
"ifGenerationNotMatch=18");
+ }
+ }
+
+ @Test
+ void testConditionFailureKeepsErrorCode() throws Exception {
+ startServer();
+ try (AsyncOperator async = AsyncOperator.of(
+
ServiceConfig.Http.builder().endpoint(endpoint).build());
+ Operator op = async.blocking()) {
+ assertReadErrors(
+ op,
+ async,
+ ReadOptions.builder().ifMatch("changed").length(2).build(),
+ OpenDALException.Code.ConditionNotMatch);
+ }
+ assertThat(methods).containsExactly("GET", "GET", "GET");
+ }
+
+ @Test
+ void testUnsupportedConditionReachesCore() {
+ ReadOptions options = ReadOptions.builder().ifMatch("etag").build();
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ op.write("file", CONTENT);
+ assertReadErrors(op, async, options,
OpenDALException.Code.Unsupported);
+ }
+ }
+
+ @Test
+ void testDefaultsAndRangeBoundaries() throws Exception {
+ ReadOptions defaults = ReadOptions.builder().build();
+ assertThat(defaults.offset).isZero();
+ assertThat(defaults.length).isEqualTo(-1);
+ assertThat(defaults.concurrent).isEqualTo(1);
+ assertThat(defaults.chunk).isEqualTo(-1);
+ assertThat(defaults.contentLengthHint).isEqualTo(-1);
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ op.write("file", CONTENT);
+ op.write("empty", new byte[0]);
+ assertReads(op, async, "file", defaults, "0123456789");
+ assertReads(op, async, "file",
ReadOptions.builder().offset(8).build(), "89");
+ assertReads(op, async, "file",
ReadOptions.builder().length(0).build(), "");
+ assertReads(
+ op,
+ async,
+ "empty",
+
ReadOptions.builder().contentLengthHint(0).chunk(2).build(),
+ "");
+ }
+ }
+
+ static Stream<Arguments> invalidOptions() {
+ return Stream.of(
+ Arguments.of(ReadOptions.builder().concurrent(0).build(),
OpenDALException.Code.ConfigInvalid),
+ Arguments.of(ReadOptions.builder().concurrent(-1).build(),
OpenDALException.Code.ConfigInvalid),
+ Arguments.of(ReadOptions.builder().chunk(0).build(),
OpenDALException.Code.ConfigInvalid),
+ Arguments.of(ReadOptions.builder().chunk(-2).build(),
OpenDALException.Code.ConfigInvalid),
+
Arguments.of(ReadOptions.builder().contentLengthHint(-2).build(),
OpenDALException.Code.ConfigInvalid),
+ Arguments.of(ReadOptions.builder().offset(-1).build(),
OpenDALException.Code.RangeNotSatisfied),
+ Arguments.of(ReadOptions.builder().length(-2).build(),
OpenDALException.Code.RangeNotSatisfied),
+ Arguments.of(
+
ReadOptions.builder().ifModifiedSince(Instant.MIN).build(),
OpenDALException.Code.Unexpected),
+ Arguments.of(
+
ReadOptions.builder().ifUnmodifiedSince(Instant.MIN).build(),
+ OpenDALException.Code.Unexpected));
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidOptions")
+ void testInvalidOptions(ReadOptions options, OpenDALException.Code code) {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ op.write("file", CONTENT);
+ assertReadErrors(op, async, options, code);
+ }
+ }
+
+ @Test
+ void testInvalidAsyncOptionsDoNotRegisterFutures() throws Exception {
+ // Invalid inputs throw before Java can take a registered future, so
inspect pending IDs.
+ Class<?> registryType = Class.forName(AsyncOperator.class.getName() +
"$AsyncRegistry");
+ Field registryField = registryType.getDeclaredField("registry");
+ registryField.setAccessible(true);
+ Map<?, ?> registry = (Map<?, ?>)
registryField.get(registryType.getEnumConstants()[0]);
+ Set<?> pendingBefore = new HashSet<>(registry.keySet());
+ try (AsyncOperator async =
+ AsyncOperator.of(ServiceConfig.Memory.builder().build())) {
+ ReadOptions invalid = ReadOptions.builder().chunk(0).build();
+ assertThatThrownBy(() -> async.read("file", invalid))
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid));
+ }
+ assertThat(pendingBefore.containsAll(registry.keySet()))
+ .as("invalid options must not leave registered futures")
+ .isTrue();
+ }
+
+ private static void assertReads(Operator op, AsyncOperator async, String
path, ReadOptions options, String expected)
+ throws Exception {
+ byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
+ assertThat(op.read(path, options)).isEqualTo(bytes);
+ assertThat(async.read(path, options).join()).isEqualTo(bytes);
+ try (OperatorInputStream in = op.createInputStream(path, options)) {
+ assertThat(IOUtils.toByteArray(in)).isEqualTo(bytes);
+ }
+ }
+
+ private static void assertReadErrors(
+ Operator op, AsyncOperator async, ReadOptions options,
OpenDALException.Code code) {
+ assertThatThrownBy(() -> op.read("file",
options)).is(OpenDALExceptionCondition.ofSync(code));
+ assertThatThrownBy(() -> async.read("file",
options).join()).is(OpenDALExceptionCondition.ofAsync(code));
+ assertThatThrownBy(() -> {
+ try (OperatorInputStream in = op.createInputStream("file",
options)) {
+ IOUtils.toByteArray(in);
+ }
+ })
+ .is(OpenDALExceptionCondition.ofSync(code));
+ }
+}
diff --git a/website/docs/20-bindings/java/04-tasks.md
b/website/docs/20-bindings/java/04-tasks.md
index 351c2b2847..dbc51fcb77 100644
--- a/website/docs/20-bindings/java/04-tasks.md
+++ b/website/docs/20-bindings/java/04-tasks.md
@@ -34,6 +34,32 @@ String text = new String(data);
byte[] data = op.read("path/to/file", 0, 1024);
```
+Pass `ReadOptions` to `op.read(path, options)` or
+`op.createInputStream(path, options)` to configure a single read. Async reads
accept
+the same options:
+
+```java
+import org.apache.opendal.ReadOptions;
+
+ReadOptions options = ReadOptions.builder()
+ .offset(1024)
+ .length(4096)
+ .ifMatch("\"etag\"")
+ .chunk(2048)
+ .concurrent(2)
+ .build();
+byte[] data = op.read("path/to/file", options);
+```
+
+`ReadOptions` supports the version and condition fields described below for
+`ReaderOptions`. Use `chunk` to set the size of each read request and
+`concurrent` to limit parallel requests.
+
+`contentLengthHint` specifies the total object size in bytes, not the length of
+the requested range. It can avoid a metadata request when OpenDAL needs the
+object length to plan a read. An incorrect hint may cause incomplete reads or
+errors.
+
For repeated reads from the same file, create an `OperatorReader`. It uses a
Rust core reader and lets each call select an independent byte range: