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 e58e78bd6e fix(bindings/java)!: pass map-valued ServiceConfig fields 
as JSON objects (#9330)
e58e78bd6e is described below

commit e58e78bd6e365f26a427b0e5e843f6e5f2947fe3
Author: Chitral Verma <[email protected]>
AuthorDate: Sat Nov 28 21:33:12 2026 +0530

    fix(bindings/java)!: pass map-valued ServiceConfig fields as JSON objects 
(#9330)
    
    * fix(bindings/java)!: pass map-valued ServiceConfig fields as JSON objects
    
    ServiceConfig.configMap() merged the entries of S3.assumeRoleSessionTags
    and HdfsNative.options into the top-level options, so core never received
    either map and a tag such as `Region` competed with `region`. Core reads a
    map-valued option from a JSON object string, so emit one entry per map
    field through a package-private ConfigJson encoder.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fix(bindings/java): report a null map key as ConfigInvalid
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    ---------
    
    Signed-off-by: Chitral Verma <[email protected]>
---
 .../main/java/org/apache/opendal/ConfigJson.java   | 105 ++++++++++++++++
 .../java/org/apache/opendal/ServiceConfig.java     |  11 +-
 .../opendal/test/ServiceConfigMapFieldTest.java    | 139 +++++++++++++++++++++
 bindings/java/upgrade.md                           |  18 +++
 dev/src/generate/java.j2                           |   5 +
 dev/src/generate/java.rs                           |  30 +++--
 6 files changed, 290 insertions(+), 18 deletions(-)

diff --git a/bindings/java/src/main/java/org/apache/opendal/ConfigJson.java 
b/bindings/java/src/main/java/org/apache/opendal/ConfigJson.java
new file mode 100644
index 0000000000..c7c9250dde
--- /dev/null
+++ b/bindings/java/src/main/java/org/apache/opendal/ConfigJson.java
@@ -0,0 +1,105 @@
+/*
+ * 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;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * Encodes map-valued {@link ServiceConfig} fields as the JSON object strings 
that core parses.
+ *
+ * <p>The binding has no runtime dependencies and the JDK has no JSON encoder, 
so this class
+ * implements the string escaping that RFC 8259 requires and nothing else.
+ */
+final class ConfigJson {
+    private ConfigJson() {}
+
+    /**
+     * Encode a string map as a JSON object with keys sorted by {@link 
String#compareTo}.
+     *
+     * <p>A null value becomes JSON {@code null}, which core rejects with 
{@code ConfigInvalid}. A
+     * null key has no JSON form, so it throws {@link OpenDALException} with 
{@code ConfigInvalid}
+     * here, as the native options map does for a null key.
+     *
+     * @param option the option name, used in the error for a null key
+     * @param map the map to encode
+     */
+    static String encodeObject(String option, Map<String, String> map) {
+        for (Map.Entry<String, String> entry : map.entrySet()) {
+            if (entry.getKey() == null) {
+                throw new OpenDALException(
+                        OpenDALException.Code.ConfigInvalid, "config '" + 
option + "' has a null map key");
+            }
+        }
+        final StringBuilder sb = new StringBuilder("{");
+        boolean first = true;
+        for (Map.Entry<String, String> entry : new TreeMap<>(map).entrySet()) {
+            if (!first) {
+                sb.append(',');
+            }
+            first = false;
+            appendString(sb, entry.getKey());
+            sb.append(':');
+            if (entry.getValue() == null) {
+                sb.append("null");
+            } else {
+                appendString(sb, entry.getValue());
+            }
+        }
+        return sb.append('}').toString();
+    }
+
+    private static void appendString(StringBuilder sb, String s) {
+        sb.append('"');
+        for (int i = 0; i < s.length(); i++) {
+            final char c = s.charAt(i);
+            switch (c) {
+                case '"':
+                    sb.append("\\\"");
+                    break;
+                case '\\':
+                    sb.append("\\\\");
+                    break;
+                case '\b':
+                    sb.append("\\b");
+                    break;
+                case '\f':
+                    sb.append("\\f");
+                    break;
+                case '\n':
+                    sb.append("\\n");
+                    break;
+                case '\r':
+                    sb.append("\\r");
+                    break;
+                case '\t':
+                    sb.append("\\t");
+                    break;
+                default:
+                    if (c < 0x20) {
+                        sb.append(String.format("\\u%04x", (int) c));
+                    } else {
+                        sb.append(c);
+                    }
+            }
+        }
+        sb.append('"');
+    }
+}
diff --git a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java 
b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
index 294f89fcb0..4f964e1d0d 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
@@ -46,6 +46,11 @@ public interface ServiceConfig {
     /**
      * Convert the structured config to a type erased config map.
      *
+     * <p>A map-valued field becomes one entry, under the field's option name, 
whose value is a JSON
+     * object string, such as {@code assume_role_session_tags} = {@code 
{"Team":"data"}}. The map's
+     * entries are not flattened into top-level entries. Its keys are sorted, 
an empty map becomes
+     * {@code {}}, and an unset field has no entry.
+     *
      * @return the config map
      */
     Map<String, String> configMap();
@@ -2269,7 +2274,7 @@ public interface ServiceConfig {
                 map.put("name_node", nameNode);
             }
             if (options != null) {
-                map.putAll(options);
+                map.put("options", ConfigJson.encodeObject("options", 
options));
             }
             if (root != null) {
                 map.put("root", root);
@@ -5046,7 +5051,9 @@ public interface ServiceConfig {
                 map.put("assume_role_duration_seconds", 
String.valueOf(assumeRoleDurationSeconds));
             }
             if (assumeRoleSessionTags != null) {
-                map.putAll(assumeRoleSessionTags);
+                map.put(
+                        "assume_role_session_tags",
+                        ConfigJson.encodeObject("assume_role_session_tags", 
assumeRoleSessionTags));
             }
             if (batchMaxOperations != null) {
                 map.put("batch_max_operations", 
String.valueOf(batchMaxOperations));
diff --git 
a/bindings/java/src/test/java/org/apache/opendal/test/ServiceConfigMapFieldTest.java
 
b/bindings/java/src/test/java/org/apache/opendal/test/ServiceConfigMapFieldTest.java
new file mode 100644
index 0000000000..671fb4510b
--- /dev/null
+++ 
b/bindings/java/src/test/java/org/apache/opendal/test/ServiceConfigMapFieldTest.java
@@ -0,0 +1,139 @@
+/*
+ * 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 java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.OpenDALException;
+import org.apache.opendal.Operator;
+import org.apache.opendal.ServiceConfig;
+import org.apache.opendal.test.condition.OpenDALExceptionCondition;
+import org.junit.jupiter.api.Test;
+
+public class ServiceConfigMapFieldTest {
+    private static ServiceConfig.S3 s3WithTags(Map<String, String> tags) {
+        return ServiceConfig.S3
+                .builder()
+                .bucket("b")
+                .region("us-east-1")
+                .assumeRoleSessionTags(tags)
+                .build();
+    }
+
+    private static Map<String, String> trickyTags() {
+        final Map<String, String> tags = new LinkedHashMap<>();
+        tags.put("q\"", "b\\");
+        tags.put("nl", "a\nb");
+        tags.put("ctl", "\u0001");
+        tags.put("\u00fc", "\u00df");
+        return tags;
+    }
+
+    @Test
+    void s3SessionTagsBecomeOneJsonEntry() {
+        final Map<String, String> map =
+                s3WithTags(Collections.singletonMap("Team", "x")).configMap();
+        assertThat(map).containsEntry("assume_role_session_tags", 
"{\"Team\":\"x\"}");
+        assertThat(map).doesNotContainKey("Team");
+    }
+
+    @Test
+    void mapEntriesDoNotBecomeServiceOptions() {
+        final Map<String, String> map =
+                s3WithTags(Collections.singletonMap("Region", 
"eu-west-1")).configMap();
+        assertThat(map).containsEntry("region", "us-east-1");
+        assertThat(map).containsEntry("assume_role_session_tags", 
"{\"Region\":\"eu-west-1\"}");
+        assertThat(map).doesNotContainKey("Region");
+    }
+
+    @Test
+    void keysAreSortedAndKeepTheirCase() {
+        final Map<String, String> tags = new LinkedHashMap<>();
+        tags.put("b", "2");
+        tags.put("a", "1");
+        tags.put("Fs.DefaultFS", "x");
+        assertThat(s3WithTags(tags).configMap())
+                .containsEntry("assume_role_session_tags", 
"{\"Fs.DefaultFS\":\"x\",\"a\":\"1\",\"b\":\"2\"}");
+    }
+
+    @Test
+    void jsonEscapesQuotesBackslashesAndControlCharacters() {
+        assertThat(s3WithTags(trickyTags()).configMap())
+                .containsEntry(
+                        "assume_role_session_tags",
+                        
"{\"ctl\":\"\\u0001\",\"nl\":\"a\\nb\",\"q\\\"\":\"b\\\\\",\"\u00fc\":\"\u00df\"}");
+    }
+
+    @Test
+    void emptyMapIsExplicitAndNullIsOmitted() {
+        
assertThat(s3WithTags(Collections.emptyMap()).configMap()).containsEntry("assume_role_session_tags",
 "{}");
+        assertThat(ServiceConfig.S3.builder().bucket("b").build().configMap())
+                .doesNotContainKey("assume_role_session_tags");
+    }
+
+    @Test
+    void hdfsNativeOptionsBecomeOneJsonEntry() {
+        // The default native library does not enable services-hdfs-native, so 
check the map only.
+        final Map<String, String> map = ServiceConfig.HdfsNative.builder()
+                .nameNode("default")
+                .options(Collections.singletonMap("fs.defaultFS", "hdfs://ns"))
+                .build()
+                .configMap();
+        assertThat(map).containsEntry("options", 
"{\"fs.defaultFS\":\"hdfs://ns\"}");
+        assertThat(map).doesNotContainKey("fs.defaultFS");
+    }
+
+    @Test
+    void coreAcceptsEncodedTags() {
+        final ServiceConfig.S3 config = s3WithTags(trickyTags());
+        try (Operator op = Operator.of(config)) {
+            assertThat(op.info.scheme).isEqualTo("s3");
+        }
+        try (AsyncOperator op = AsyncOperator.of(config)) {
+            assertThat(op.info.scheme).isEqualTo("s3");
+        }
+    }
+
+    @Test
+    void coreRejectsNullTagValue() {
+        final ServiceConfig.S3 config = 
s3WithTags(Collections.singletonMap("Team", null));
+        assertThatThrownBy(() -> Operator.of(config))
+                
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid))
+                .hasMessageContaining("assume_role_session_tags");
+    }
+
+    @Test
+    void nullTagKeyFailsWithConfigInvalid() {
+        final Map<String, String> tags = new HashMap<>();
+        tags.put(null, "x");
+        final ServiceConfig.S3 config = s3WithTags(tags);
+        assertThatThrownBy(() -> Operator.of(config))
+                
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid))
+                .hasMessageContaining("assume_role_session_tags");
+        assertThatThrownBy(() -> AsyncOperator.of(config))
+                
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid))
+                .hasMessageContaining("assume_role_session_tags");
+    }
+}
diff --git a/bindings/java/upgrade.md b/bindings/java/upgrade.md
index 435f3f71c8..28bd9ff7b4 100644
--- a/bindings/java/upgrade.md
+++ b/bindings/java/upgrade.md
@@ -1,3 +1,21 @@
+# Unreleased
+
+## Map-valued `ServiceConfig` fields
+
+`ServiceConfig.configMap()` now passes 
`ServiceConfig.S3.assumeRoleSessionTags` and
+`ServiceConfig.HdfsNative.options` as one option each, whose value is a JSON 
object string,
+such as `assume_role_session_tags` = `{"Team":"data"}`. Earlier versions 
merged the map's
+entries into the top-level options. The service ignored most entries, and an 
entry whose key
+matched another option after lowercasing, such as `Region`, could replace that 
option.
+
+- S3 session tags now reach STS `AssumeRole` when `roleArn` is set. The role's 
trust policy
+  must allow `sts:TagSession`, or `AssumeRole` fails. If it does not, leave
+  `assumeRoleSessionTags` unset.
+- If you relied on a merged entry to set a service option, set that option 
directly.
+- Code that reads `configMap()` directly no longer finds the map's entries as 
top-level
+  entries. It finds one entry per map field, under `assume_role_session_tags` 
or `options`,
+  and must decode that JSON object string to read the map.
+
 # Upgrade to v0.50
 
 ## Moka and MiniMoka configuration durations
diff --git a/dev/src/generate/java.j2 b/dev/src/generate/java.j2
index fc741d85b1..7e2e48baa4 100644
--- a/dev/src/generate/java.j2
+++ b/dev/src/generate/java.j2
@@ -46,6 +46,11 @@ public interface ServiceConfig {
     /**
      * Convert the structured config to a type erased config map.
      *
+     * <p>A map-valued field becomes one entry, under the field's option name, 
whose value is a JSON
+     * object string, such as {@code assume_role_session_tags} = {@code 
{"Team":"data"}}. The map's
+     * entries are not flattened into top-level entries. Its keys are sorted, 
an empty map becomes
+     * {@code {}}, and an unset field has no entry.
+     *
      * @return the config map
      */
     Map<String, String> configMap();
diff --git a/dev/src/generate/java.rs b/dev/src/generate/java.rs
index a1781c49df..15c13d2ea2 100644
--- a/dev/src/generate/java.rs
+++ b/dev/src/generate/java.rs
@@ -1129,29 +1129,27 @@ fn make_populate_map(field: Serde<Config>) -> 
Result<String, minijinja::Error> {
         | ConfigType::I64
         | ConfigType::Bool
         | ConfigType::U32
-        | ConfigType::U16 => Some(format!("String.valueOf({name})")),
-        ConfigType::String => Some(name.clone()),
-        ConfigType::Duration => Some(format!("{name}.toString()")),
-        ConfigType::Vec => Some(format!("String.join(\",\", {name})")),
-        ConfigType::HashMap => None,
+        | ConfigType::U16 => format!("String.valueOf({name})"),
+        ConfigType::String => name.clone(),
+        ConfigType::Duration => format!("{name}.toString()"),
+        ConfigType::Vec => format!("String.join(\",\", {name})"),
+        // Core reads a map-valued option from one JSON object string. The
+        // option name lets the encoder report a null key as `ConfigInvalid`.
+        ConfigType::HashMap => format!("ConfigJson.encodeObject(\"{}\", 
{name})", field.name),
     };
 
     let indent = if field.optional { "    " } else { "" };
     if field.optional {
         writeln!(w, "if ({name} != null) {{")?;
     }
-    if let Some(value) = value {
-        let populate = format!("map.put(\"{}\", {value});", field.name);
-        // java.j2 adds 12 columns; keep calls within the formatter's 
120-column layout.
-        if 12 + indent.len() + populate.len() > 120 {
-            writeln!(w, "{indent}map.put(")?;
-            writeln!(w, "{indent}        \"{}\",", field.name)?;
-            writeln!(w, "{indent}        {value});")?;
-        } else {
-            writeln!(w, "{indent}{populate}")?;
-        }
+    let populate = format!("map.put(\"{}\", {value});", field.name);
+    // java.j2 adds 12 columns; keep calls within the formatter's 120-column 
layout.
+    if 12 + indent.len() + populate.len() > 120 {
+        writeln!(w, "{indent}map.put(")?;
+        writeln!(w, "{indent}        \"{}\",", field.name)?;
+        writeln!(w, "{indent}        {value});")?;
     } else {
-        writeln!(w, "{indent}map.putAll({name});")?;
+        writeln!(w, "{indent}{populate}")?;
     }
     if field.optional {
         writeln!(w, "}}")?;

Reply via email to