Skip to content

[java][resttemplate] Add property for config removal of @Component from ApiClient and <Name>Api classes #15416

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
May 5, 2023
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
1 change: 1 addition & 0 deletions docs/generators/java.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|<dl><dt>**false**</dt><dd>No changes to the enum's are made, this is the default option.</dd><dt>**true**</dt><dd>With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.</dd></dl>|false|
|errorObjectType|Error Object type. (This option is for okhttp-gson-next-gen only)| |null|
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|generateClientAsBean|For restTemplate, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation) | <dl><dt>**false**</dt><dd>No changes to the `ApiClient.java` or Apis are made, this is the default option.</dd><dt>**true**</dt><dd>With this option enabled, create `ApiClient.java` and Apis clients as bean.</dd></dl> | false |
|gradleProperties|Append additional Gradle properties to the gradle.properties file| |null|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String SERIALIZATION_LIBRARY_JACKSON = "jackson";
public static final String SERIALIZATION_LIBRARY_JSONB = "jsonb";

public static final String GENERATE_CLIENT_AS_BEAN = "generateClientAsBean";

protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
protected boolean useRxJava2 = false;
Expand Down Expand Up @@ -132,6 +134,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
protected Map<String, MpRestClientVersion> mpRestClientVersions = new HashMap<>();
protected boolean useSingleRequestParameter = false;
protected boolean webclientBlockingOperations = false;
protected boolean generateClientAsBean = false;

private static class MpRestClientVersion {
public final String rootPackage;
Expand Down Expand Up @@ -445,6 +448,10 @@ public void processOpts() {
additionalProperties.put(SUPPORT_URL_QUERY, Boolean.parseBoolean(additionalProperties.get(SUPPORT_URL_QUERY).toString()));
}

if (additionalProperties.containsKey(GENERATE_CLIENT_AS_BEAN)) {
this.setGenerateClientAsBean(convertPropertyToBooleanAndWriteBack(GENERATE_CLIENT_AS_BEAN));
}

final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String apiFolder = (sourceFolder + '/' + apiPackage).replace(".", "/");
final String modelsFolder = (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar);
Expand Down Expand Up @@ -1195,6 +1202,10 @@ public void setErrorObjectType(final String errorObjectType) {
this.errorObjectType = errorObjectType;
}

public void setGenerateClientAsBean(boolean generateClientAsBean) {
this.generateClientAsBean = generateClientAsBean;
}

/**
* Serialization library.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ import {{invokerPackage}}.auth.OAuth;
{{/hasOAuthMethods}}

{{>generatedAnnotation}}
{{#generateClientAsBean}}
@Component("{{invokerPackage}}.ApiClient")
{{/generateClientAsBean}}
public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
public enum CollectionFormat {
CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null);
Expand Down Expand Up @@ -114,6 +117,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
init();
}

{{#generateClientAsBean}}
@Autowired
{{/generateClientAsBean}}
public ApiClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
init();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

{{>generatedAnnotation}}
{{#generateClientAsBean}}
@Component("{{package}}.{{classname}}")
{{/generateClientAsBean}}
{{#operations}}
public class {{classname}} {
private ApiClient apiClient;
Expand All @@ -35,6 +38,9 @@ public class {{classname}} {
this(new ApiClient());
}

{{#generateClientAsBean}}
@Autowired
{{/generateClientAsBean}}
public {{classname}}(ApiClient apiClient) {
this.apiClient = apiClient;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2019,4 +2019,66 @@ public void testDeprecatedProperty() throws Exception {
output.deleteOnExit();
}

@Test
public void testRestTemplateWithGeneratedClientAsBeanDisabled() throws IOException {

Map<String, Object> properties = new HashMap<>();
properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
properties.put(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, false);

File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();

final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.RESTTEMPLATE)
.setAdditionalProperties(properties)
.setInputSpec("src/test/resources/3_0/petstore.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));


DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);

validateJavaSourceFiles(files);

Path apiClient = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java");
TestUtils.assertFileNotContains(apiClient, "@Component");

Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/PetApi.java");
TestUtils.assertFileNotContains(petApi, "@Component");
}

@Test
public void testRestTemplateWithGeneratedClientAsBeanEnabled() throws IOException {

Map<String, Object> properties = new HashMap<>();
properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api");
properties.put(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true);

File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();

final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.RESTTEMPLATE)
.setAdditionalProperties(properties)
.setInputSpec("src/test/resources/3_0/petstore.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));


DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);

validateJavaSourceFiles(files);

Path apiClient = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java");
TestUtils.assertFileContains(apiClient, "@Component");

Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/PetApi.java");
TestUtils.assertFileContains(petApi, "@Component");
}

}