Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,41 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
}
}

/**
* Format the given collection as a path parameter value according to the collection format.
* Each item is escaped individually, so that the delimiter is preserved (e.g. "a,b,c" for csv).
*
* @param collectionFormat Collection format (csv by default)
* @param value Collection value
* @return Escaped path parameter value
*/
public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
if (value == null || value.isEmpty()) {
return "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: An empty (non-null) required array path parameter serializes to an empty string, so {ids} is replaced with an empty segment and the path becomes /items//action. The generated Api method only null-checks required params, so an empty list reaches this method. Compare the old behavior (escapeString("[]") → %5B%5D), which could not match any route, whereas an empty segment is liable to slash-collapsing/normalization by servers and can change route resolution. Return a placeholder or document this degenerate case explicitly.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache, line 990:

<comment>An empty (non-null) required array path parameter serializes to an empty string, so `{ids}` is replaced with an empty segment and the path becomes `/items//action`. The generated Api method only null-checks required params, so an empty list reaches this method. Compare the old behavior (`escapeString("[]")` → `%5B%5D`), which could not match any route, whereas an empty segment is liable to slash-collapsing/normalization by servers and can change route resolution. Return a placeholder or document this degenerate case explicitly.</comment>

<file context>
@@ -977,6 +977,39 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
+   */
+  public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
+    if (value == null || value.isEmpty()) {
+      return "";
+    }
+
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning an empty string is intentional: for style: simple, RFC 6570 expands an empty list to an empty string, and the collectionPathParameterToString helpers in the resttemplate, webclient and restclient libraries behave the same way. The previous %5B%5D output was also an invalid path. A placeholder value would send a request the spec never defined, so I've kept this consistent with the other Java libraries.

}

// "multi" is not valid for path params, fall back to csv
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}

StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : value) {
if (!first) {
sb.append(delimiter);
}
sb.append(escapeString(parameterToString(item)));
first = false;
}
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
return sb.toString();
}

/**
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public class {{classname}} {
{{#hasPathParams}}
// Path parameters
String localVarPath = "{{{path}}}"{{#pathParams}}
.replaceAll({{=% %=}}"\\{%baseName%}"%={{ }}=%, apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
.replaceAll({{=% %=}}"\\{%baseName%}"%={{ }}=%, {{#isArray}}apiClient.collectionPathParameterToString("{{{collectionFormat}}}", {{{paramName}}}){{/isArray}}{{^isArray}}apiClient.escapeString({{{paramName}}}.toString()){{/isArray}}){{/pathParams}};

{{/hasPathParams}}
{{#queryParams}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,41 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
}
}

/**
* Format the given collection as a path parameter value according to the collection format.
* Each item is escaped individually, so that the delimiter is preserved (e.g. "a,b,c" for csv).
*
* @param collectionFormat Collection format (csv by default)
* @param value Collection value
* @return Escaped path parameter value
*/
public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
if (value == null || value.isEmpty()) {
return "";
}

// "multi" is not valid for path params, fall back to csv
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}

StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : value) {
if (!first) {
sb.append(delimiter);
}
sb.append(escapeString(parameterToString(item)));
first = false;
}
return sb.toString();
}

/**
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public class {{classname}} {
{{#hasPathParams}}
// Path parameters
String localVarPath = "{{{path}}}"{{#pathParams}}
.replaceAll({{=% %=}}"\\{%baseName%}"%={{ }}=%, apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
.replaceAll({{=% %=}}"\\{%baseName%}"%={{ }}=%, {{#isArray}}apiClient.collectionPathParameterToString("{{{collectionFormat}}}", {{{paramName}}}){{/isArray}}{{^isArray}}apiClient.escapeString({{{paramName}}}.toString()){{/isArray}}){{/pathParams}};

{{/hasPathParams}}
{{#queryParams}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5351,6 +5351,27 @@ public void testInsecureTlsHookOmittedWhenDisabled(String library) {
.doesNotContain("import java.security.cert.X509Certificate;");
}

@Test(dataProvider = "jerseyLibraries")
public void testArrayPathParamSerializedAsCollection(String library) {
Path output = newTempFolder();
CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName(JAVA_GENERATOR)
.setLibrary(library)
.addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker")
.addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")
.setInputSpec("src/test/resources/3_0/java/array-path-param.yaml")
.setOutputDir(output.toString().replace("\\", "/"));

new DefaultGenerator().opts(configurator.toClientOptInput()).generate();

assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content()
.contains("apiClient.collectionPathParameterToString(\"csv\", ids)")
.contains("apiClient.escapeString(id.toString())")
.doesNotContain("apiClient.escapeString(ids.toString())");
JavaFileAssert.assertThat(output.resolve("src/main/java/xyz/abcdef/invoker/ApiClient.java").toFile())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The test proves the template invokes collectionPathParameterToString("csv", ids) and that the method exists, but never asserts the method's actual escaping behavior, which is the entire point of the PR. A behavioral check such as csv with an item containing , producing a%2Cb,c (item comma encoded, separator comma raw) would lock in per-item escaping and guard against regression to the old whole-string escape. Compare okhttp-gson's analogous helper (libraries/okhttp-gson/ApiClient.mustache), whose full-string escaping later breaks items containing the delimiter — exactly what this PR fixes for jersey and worth pinning with a test.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java, line 5371:

<comment>The test proves the template invokes `collectionPathParameterToString("csv", ids)` and that the method exists, but never asserts the method's actual escaping behavior, which is the entire point of the PR. A behavioral check such as `csv` with an item containing `,` producing `a%2Cb,c` (item comma encoded, separator comma raw) would lock in per-item escaping and guard against regression to the old whole-string escape. Compare okhttp-gson's analogous helper (libraries/okhttp-gson/ApiClient.mustache), whose full-string escaping later breaks items containing the delimiter — exactly what this PR fixes for jersey and worth pinning with a test.</comment>

<file context>
@@ -5351,6 +5351,27 @@ public void testInsecureTlsHookOmittedWhenDisabled(String library) {
+                .contains("apiClient.collectionPathParameterToString(\"csv\", ids)")
+                .contains("apiClient.escapeString(id.toString())")
+                .doesNotContain("apiClient.escapeString(ids.toString())");
+        JavaFileAssert.assertThat(output.resolve("src/main/java/xyz/abcdef/invoker/ApiClient.java").toFile())
+                .assertMethod("collectionPathParameterToString", "String", "Collection<?>");
+    }
</file context>

.assertMethod("collectionPathParameterToString", "String", "Collection<?>");
}

private static Path generateJerseyClient(String library, Boolean generateInsecureTlsHook) {
Path output = newTempFolder();
CodegenConfigurator configurator = new CodegenConfigurator()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
openapi: 3.0.3
info:
title: Array path param
version: 1.0.0
paths:
/items/{ids}/action:
get:
operationId: getItems
parameters:
- name: ids
in: path
required: true
schema:
type: array
items:
type: string
responses:
'204':
description: ok
/items/{id}:
get:
operationId: getItem
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
'204':
description: ok
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,41 @@ public String escapeString(String str) {
}
}

/**
* Format the given collection as a path parameter value according to the collection format.
* Each item is escaped individually, so that the delimiter is preserved (e.g. "a,b,c" for csv).
*
* @param collectionFormat Collection format (csv by default)
* @param value Collection value
* @return Escaped path parameter value
*/
public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
if (value == null || value.isEmpty()) {
return "";
}

// "multi" is not valid for path params, fall back to csv
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}

StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : value) {
if (!first) {
sb.append(delimiter);
}
sb.append(escapeString(parameterToString(item)));
first = false;
}
return sb.toString();
}

/**
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,41 @@ public String escapeString(String str) {
}
}

/**
* Format the given collection as a path parameter value according to the collection format.
* Each item is escaped individually, so that the delimiter is preserved (e.g. "a,b,c" for csv).
*
* @param collectionFormat Collection format (csv by default)
* @param value Collection value
* @return Escaped path parameter value
*/
public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
if (value == null || value.isEmpty()) {
return "";
}

// "multi" is not valid for path params, fall back to csv
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}

StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : value) {
if (!first) {
sb.append(delimiter);
}
sb.append(escapeString(parameterToString(item)));
first = false;
}
return sb.toString();
}

/**
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,41 @@ public String escapeString(String str) {
}
}

/**
* Format the given collection as a path parameter value according to the collection format.
* Each item is escaped individually, so that the delimiter is preserved (e.g. "a,b,c" for csv).
*
* @param collectionFormat Collection format (csv by default)
* @param value Collection value
* @return Escaped path parameter value
*/
public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
if (value == null || value.isEmpty()) {
return "";
}

// "multi" is not valid for path params, fall back to csv
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}

StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : value) {
if (!first) {
sb.append(delimiter);
}
sb.append(escapeString(parameterToString(item)));
first = false;
}
return sb.toString();
}

/**
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,41 @@ public String escapeString(String str) {
}
}

/**
* Format the given collection as a path parameter value according to the collection format.
* Each item is escaped individually, so that the delimiter is preserved (e.g. "a,b,c" for csv).
*
* @param collectionFormat Collection format (csv by default)
* @param value Collection value
* @return Escaped path parameter value
*/
public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
if (value == null || value.isEmpty()) {
return "";
}

// "multi" is not valid for path params, fall back to csv
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}

StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : value) {
if (!first) {
sb.append(delimiter);
}
sb.append(escapeString(parameterToString(item)));
first = false;
}
return sb.toString();
}

/**
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,8 @@

@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1));

Check warning on line 179 in samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java

View workflow job for this annotation

GitHub Actions / Build Java Client JDK11 (samples/client/petstore/java/jersey2-java8)

[deprecation] Integer(int) in Integer has been deprecated
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1));

Check warning on line 180 in samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java

View workflow job for this annotation

GitHub Actions / Build Java Client JDK11 (samples/client/petstore/java/jersey2-java8)

[deprecation] Integer(int) in Integer has been deprecated

assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
Expand Down Expand Up @@ -254,4 +254,20 @@
assertEquals(values.size(), pairValueSplit.length);
}
}

@Test
public void testCollectionPathParameterToString() {
// items are escaped individually, the csv delimiter is kept raw
assertEquals("a%2Cb,c", apiClient.collectionPathParameterToString("csv", Arrays.asList("a,b", "c")));
assertEquals("a,b", apiClient.collectionPathParameterToString("", Arrays.asList("a", "b")));
assertEquals("a,b", apiClient.collectionPathParameterToString("multi", Arrays.asList("a", "b")));
assertEquals("a%7Cb", apiClient.collectionPathParameterToString("pipes", Arrays.asList("a", "b")));
assertEquals("a%20b", apiClient.collectionPathParameterToString("ssv", Arrays.asList("a", "b")));
assertEquals("a%09b", apiClient.collectionPathParameterToString("tsv", Arrays.asList("a", "b")));
// leading empty or null items keep their delimiter
assertEquals(",b", apiClient.collectionPathParameterToString("csv", Arrays.asList("", "b")));
assertEquals(",b", apiClient.collectionPathParameterToString("csv", Arrays.asList(null, "b")));
assertEquals("", apiClient.collectionPathParameterToString("csv", Collections.emptyList()));
assertEquals("", apiClient.collectionPathParameterToString("csv", null));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,41 @@ public String escapeString(String str) {
}
}

/**
* Format the given collection as a path parameter value according to the collection format.
* Each item is escaped individually, so that the delimiter is preserved (e.g. "a,b,c" for csv).
*
* @param collectionFormat Collection format (csv by default)
* @param value Collection value
* @return Escaped path parameter value
*/
public String collectionPathParameterToString(String collectionFormat, Collection<?> value) {
if (value == null || value.isEmpty()) {
return "";
}

// "multi" is not valid for path params, fall back to csv
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}

StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : value) {
if (!first) {
sb.append(delimiter);
}
sb.append(escapeString(parameterToString(item)));
first = false;
}
return sb.toString();
}

/**
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
Expand Down
Loading
Loading