org.openapitools.codegen.languages.JavaHelidonClientCodegen Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright (c) 2022 Oracle and/or its affiliates
*
* 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
*
* https://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.openapitools.codegen.languages;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.servers.Server;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenResponse;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.VendorExtension;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationsMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.openapitools.codegen.CodegenConstants.SERIALIZATION_LIBRARY;
public class JavaHelidonClientCodegen extends JavaHelidonCommonCodegen {
private final Logger LOGGER = LoggerFactory.getLogger(JavaHelidonClientCodegen.class);
private static final String X_HELIDON_REQUIRED_IMPL_IMPORTS = "x-helidon-requiredImplImports";
private static final String X_HELIDON_IMPL_IMPORTS = "x-helidon-implImports";
private static final String X_CLIENT_STYLE_V3 = "x-helidon-client-style-v3";
public static final String CONFIG_KEY = "configKey";
@Setter protected String configKey = null;
@Setter protected boolean performBeanValidation = false;
@Setter protected boolean useGzipFeature = false;
protected boolean caseInsensitiveResponseHeaders = false;
protected Path invokerFolder;
protected Path apiFolder;
@Getter protected String serializationLibrary = null;
/**
* Constructor for this generator. Uses the embedded template dir to find common templates
* shared between Helidon client and server generators.
*
* @see org.openapitools.codegen.templating.GeneratorTemplateContentLocator#getFullTemplatePath
*/
public JavaHelidonClientCodegen() {
// beta for now
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();
// TODO: Move GlobalFeature.ParameterizedServer to library: jersey after moving featureSet to generatorMetadata
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.includeGlobalFeatures(GlobalFeature.ParameterizedServer)
);
outputFolder = "generated-code" + File.separator + "java";
embeddedTemplateDir = "java-helidon" + File.separator + "common"; // use embedded for common
templateDir = "java-helidon" + File.separator + "client";
invokerPackage = "org.openapitools.client";
artifactId = "openapi-java-client";
apiPackage = invokerPackage + ".api";
modelPackage = invokerPackage + ".model";
updateOption(CodegenConstants.INVOKER_PACKAGE, getInvokerPackage());
updateOption(CodegenConstants.ARTIFACT_ID, getArtifactId());
updateOption(CodegenConstants.API_PACKAGE, apiPackage);
updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage);
modelTestTemplateFiles.put("model_test.mustache", ".java");
cliOptions.add(CliOption.newString(CONFIG_KEY, "Config key in @RegisterRestClient. Default to none."));
supportedLibraries.put(HELIDON_MP, "Helidon MP Client");
supportedLibraries.put(HELIDON_SE, "Helidon SE Client");
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY,
"library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
libraryOption.setDefault(HELIDON_MP);
cliOptions.add(libraryOption);
setLibrary(HELIDON_MP); // default
CliOption serializationLibrary = new CliOption(SERIALIZATION_LIBRARY,
"Serialization library, defaults to Jackson");
Map serializationOptions = new HashMap<>();
serializationOptions.put(SERIALIZATION_LIBRARY_JACKSON, "Use Jackson as serialization library");
serializationOptions.put(SERIALIZATION_LIBRARY_JSONB, "Use JSON-B as serialization library");
serializationLibrary.setEnum(serializationOptions);
cliOptions.add(serializationLibrary);
setSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); // default
removeUnusedOptions();
// Ensure the OAS 3.x discriminator mappings include any descendent schemas that allOf
// inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values,
// and the discriminator mapping schemas in the OAS document.
this.setLegacyDiscriminatorBehavior(false);
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "java-helidon-client";
}
@Override
public String getHelp() {
return "Generates a Helidon MP or SE client";
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co,
Map> operations) {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
if (HELIDON_MP.equals(getLibrary())) {
co.subresourceOperation = !co.path.isEmpty();
}
}
@Override
public String apiFilename(String templateName, String tag) {
if (templateName.contains("_impl")) {
String suffix = apiTemplateFiles().get(templateName);
return apiFileFolder() + File.separator + toApiFilename(tag) + "Impl" + suffix;
}
return super.apiFilename(templateName, tag);
}
@Override
public void processOpts() {
super.processOpts();
// Not intended for users to set; we compute this based on the major version.
additionalProperties.put(X_CLIENT_STYLE_V3, helidonMajorVersion == 3);
convertPropertyToStringAndWriteBack(SERIALIZATION_LIBRARY, this::setSerializationLibrary);
convertPropertyToStringAndWriteBack(CONFIG_KEY, this::setConfigKey);
String invokerPath = invokerPackage.replace('.', File.separatorChar);
invokerFolder = Paths.get(sourceFolder, invokerPath);
apiFolder = Paths.get(outputFolder).relativize(Paths.get(apiFileFolder()));
if (isLibrary(HELIDON_MP)) {
String apiExceptionFolder = Paths.get(sourceFolder,
apiPackage().replace('.', File.separatorChar)).toString();
List modifiable = new ArrayList<>();
modifiable.add(new SupportingFile("pom.mustache", "", "pom.xml"));
modifiable.add(new SupportingFile("README.mustache", "", "README.md"));
List unmodifiable = new ArrayList<>();
unmodifiable.add(new SupportingFile("api_exception.mustache", apiExceptionFolder, "ApiException.java"));
unmodifiable.add(new SupportingFile("api_exception_mapper.mustache", apiExceptionFolder, "ApiExceptionMapper.java"));
if (additionalProperties.containsKey("jsr310")) {
unmodifiable.add(new SupportingFile("JavaTimeFormatter.mustache",
invokerFolder.toString(), "JavaTimeFormatter.java"));
}
processSupportingFiles(modifiable, unmodifiable);
} else if (isLibrary(HELIDON_SE)) {
apiTemplateFiles.put("api_impl.mustache", ".java");
importMapping.put("StringJoiner", "java.util.StringJoiner");
if (helidonMajorVersion == 3) {
importMapping.put("WebClientRequestHeaders", "io.helidon.webclient.WebClientRequestHeaders");
} else {
importMapping.put("ClientRequestHeaders", "io.helidon.http.ClientRequestHeaders");
importMapping.put("HeaderNames", "io.helidon.http.HeaderNames");
}
importMapping.put("Pair", invokerPackage + ".Pair");
List modifiable = new ArrayList<>();
modifiable.add(new SupportingFile("pom.mustache", "", "pom.xml"));
modifiable.add(new SupportingFile("README.mustache", "", "README.md"));
List unmodifiable = new ArrayList<>();
unmodifiable.add(new SupportingFile("ApiResponse.mustache", invokerFolder.toString(), "ApiResponse.java"));
unmodifiable.add(new SupportingFile("ApiResponseBase.mustache", invokerFolder.toString(), "ApiResponseBase.java"));
unmodifiable.add(new SupportingFile("ApiClient.mustache", invokerFolder.toString(), "ApiClient.java"));
unmodifiable.add(new SupportingFile("Pair.mustache", invokerFolder.toString(), "Pair.java"));
unmodifiable.add(new SupportingFile("ResponseType.mustache", apiFolder.toString(), "ResponseType.java"));
processSupportingFiles(modifiable, unmodifiable);
}
else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
if (getSerializationLibrary() == null) {
LOGGER.info("No serializationLibrary configured, using '{}' as fallback", SERIALIZATION_LIBRARY_JACKSON);
setSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON);
}
switch (getSerializationLibrary()) {
case SERIALIZATION_LIBRARY_JACKSON:
additionalProperties.put(SERIALIZATION_LIBRARY_JACKSON, "true");
additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB);
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder.toString(), "RFC3339DateFormat.java"));
break;
case SERIALIZATION_LIBRARY_JSONB:
openApiNullable = false;
additionalProperties.put(OPENAPI_NULLABLE, false);
additionalProperties.put(SERIALIZATION_LIBRARY_JSONB, "true");
additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON);
break;
default:
additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON);
additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB);
LOGGER.error("Unknown serialization library option");
break;
}
}
/**
* Check if pom file and src directory already exist.
*
* @return outcome of test
*/
@Override
protected boolean projectFilesExist() {
Path projectFolder = Paths.get(getOutputTestFolder());
Path pom = projectFolder.resolve("pom.xml");
Path src = projectFolder.resolve(invokerFolder);
return pom.toFile().exists() && src.toFile().exists();
}
@Override
public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) {
if (isLibrary(HELIDON_MP)) {
super.postProcessOperationsWithModels(objs, allModels);
return AbstractJavaJAXRSServerCodegen.jaxrsPostProcessOperations(objs);
} else {
// Compute the imports to declare in the generated API impl class.
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy