adding Intellij style xml and applied to all java code (#20734)

* added intellij-codestyle.xml and sample of it being applied to some java code-gen classes

* code-format changes ONLY

* few more format changes since last merge with master

* applied code-style to all java one last time
This commit is contained in:
Ron Reynolds 2025-03-03 09:44:48 -08:00 committed by GitHub
parent 3ad5303f99
commit 2cff152e2a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
481 changed files with 5502 additions and 5688 deletions

9
intellij-codestyle.xml Normal file
View File

@ -0,0 +1,9 @@
<code_scheme name="Project" version="173">
<JavaCodeStyleSettings>
<option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION" value="true" />
<option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION_IN_PARAMETER" value="true" />
</JavaCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="FIELD_ANNOTATION_WRAP" value="0" />
</codeStyleSettings>
</code_scheme>

View File

@ -1,7 +1,8 @@
package org.openapitools.codegen;
public class Constants {
private Constants(){ }
private Constants() {
}
public static final String CLI_NAME = "openapi-generator-cli";
public static final String GIT_REPO = "https://github.com/openapitools/openapi-generator";

View File

@ -138,7 +138,7 @@ public class AuthorTemplate extends OpenApiGeneratorCommand {
} else {
LOGGER.warn("The library filter '{}' extracted an unexpected library path: {}", library, p.toAbsolutePath());
}
});
});
}
LOGGER.info("Extracted templates to '{}' directory. Refer to https://openapi-generator.tech/docs/templating for customization details.", outputDirPath);

View File

@ -20,11 +20,7 @@ package org.openapitools.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
import org.openapitools.codegen.GeneratorNotFoundException;
import org.openapitools.codegen.VendorExtension;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.FeatureSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -37,10 +33,10 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
@SuppressWarnings({"unused","java:S106", "java:S1192"})
@SuppressWarnings({"unused", "java:S106", "java:S1192"})
@Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp extends OpenApiGeneratorCommand {
@ -49,7 +45,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
private static final String FORMAT_TEXT = "text";
private static final String FORMAT_MARKDOWN = "markdown";
private static final String FORMAT_YAMLSAMPLE = "yamlsample";
private static final int FEATURE_SET_DISPLAY_WIDTH= 20;
private static final int FEATURE_SET_DISPLAY_WIDTH = 20;
@Option(name = {"-g",
"--generator-name"}, title = "generator name", description = "generator to get config help for")
@ -121,7 +117,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
private Boolean markdownHeader;
@Option(name = {
"--supported-vendor-extensions"}, title = "supported vendor extensions", description = "List supported vendor extensions")
"--supported-vendor-extensions"}, title = "supported vendor extensions", description = "List supported vendor extensions")
private Boolean supportedVendorExtensions;
@Option(name = {"--full-details"}, title = "full generator details", description = "displays CLI options as well as other configs/mappings (implies --instantiation-types, --reserved-words, --language-specific-primitives, --import-mappings, --feature-set)")
@ -241,16 +237,16 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
}
sb
.append(newline).append("## SUPPORTED VENDOR EXTENSIONS").append(newline).append(newline)
.append("| Extension name | Description | Applicable for | Default value |").append(newline)
.append("| -------------- | ----------- | -------------- | ------------- |").append(newline);
.append(newline).append("## SUPPORTED VENDOR EXTENSIONS").append(newline).append(newline)
.append("| Extension name | Description | Applicable for | Default value |").append(newline)
.append("| -------------- | ----------- | -------------- | ------------- |").append(newline);
supportedVendorExtensions.forEach(
extension -> sb.append("|").append(extension.getName())
.append("|").append(extension.getDescription())
.append("|").append(extension.getLevels().stream().map(Objects::toString).collect(Collectors.joining(", ")))
.append("|").append(extension.getDefaultValue())
.append(newline)
extension -> sb.append("|").append(extension.getName())
.append("|").append(extension.getDescription())
.append("|").append(extension.getLevels().stream().map(Objects::toString).collect(Collectors.joining(", ")))
.append("|").append(extension.getDefaultValue())
.append(newline)
);
sb.append(newline);
}
@ -359,17 +355,17 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
sb.append("| Property | Value | Notes |").append(newline);
sb.append("| -------- | ----- | ----- |").append(newline);
sb.append("| generator name | "+config.getName()+" | pass this to the generate command after -g |").append(newline);
sb.append("| generator stability | "+config.getGeneratorMetadata().getStability()+" | |").append(newline);
sb.append("| generator type | "+config.getTag()+" | |").append(newline);
sb.append("| generator name | " + config.getName() + " | pass this to the generate command after -g |").append(newline);
sb.append("| generator stability | " + config.getGeneratorMetadata().getStability() + " | |").append(newline);
sb.append("| generator type | " + config.getTag() + " | |").append(newline);
if (config.generatorLanguage() != null) {
sb.append("| generator language | "+config.generatorLanguage().toString()+" | |").append(newline);
sb.append("| generator language | " + config.generatorLanguage().toString() + " | |").append(newline);
}
if (config.generatorLanguageVersion() != null) {
sb.append("| generator language version | "+config.generatorLanguageVersion()+" | |").append(newline);
sb.append("| generator language version | " + config.generatorLanguageVersion() + " | |").append(newline);
}
sb.append("| generator default templating engine | "+config.defaultTemplatingEngine()+" | |").append(newline);
sb.append("| helpTxt | "+config.getHelp()+" | |").append(newline);
sb.append("| generator default templating engine | " + config.defaultTemplatingEngine() + " | |").append(newline);
sb.append("| helpTxt | " + config.getHelp() + " | |").append(newline);
sb.append(newline);
}

View File

@ -17,18 +17,10 @@
package org.openapitools.codegen.cmd;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.spi.FilterAttachable;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.config.CodegenConfigurator;
@ -36,6 +28,14 @@ import org.openapitools.codegen.config.MergedSpecBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
@SuppressWarnings({"java:S106"})
@Command(name = "generate", description = "Generate code with the specified generator.")
public class Generate extends OpenApiGeneratorCommand {
@ -101,7 +101,7 @@ public class Generate extends OpenApiGeneratorCommand {
+ "overwritten during the generation.")
private Boolean skipOverwrite;
@Option(name = { "--dry-run" }, title = "Dry run",
@Option(name = {"--dry-run"}, title = "Dry run",
description = "Try things out and report on potential changes (without actually making changes).")
private Boolean isDryRun;
@ -327,15 +327,15 @@ public class Generate extends OpenApiGeneratorCommand {
private Boolean legacyDiscriminatorBehavior;
@Option(name = {"--minimal-update"},
title = "Minimal update",
description = "Only write output files that have changed.")
title = "Minimal update",
description = "Only write output files that have changed.")
private Boolean minimalUpdate;
@Override
public void execute() {
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
spec = new MergedSpecBuilder(inputSpecRootDirectory, StringUtils.isBlank(mergedFileName) ? "_merged_spec" : mergedFileName)
.buildMergedSpec();
.buildMergedSpec();
System.out.println("Merge input spec would be used - " + spec);
}

View File

@ -18,7 +18,6 @@ package org.openapitools.codegen.cmd;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.*;
@ -26,7 +25,6 @@ import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.TokenBuffer;
import io.airlift.airline.Arguments;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
@ -211,7 +209,7 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
ClientOptInput opts = configurator.toClientOptInput();
CodegenConfig config = opts.getConfig();
name = config.getName();
Path target = Paths.get(config.getOutputDir());
Path updated = rootDir.resolve(target);
config.setOutputDir(updated.toString());
@ -308,34 +306,34 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();
TokenBuffer buffer = new TokenBuffer(p);
recurse(buffer, p, codec, false);
JsonParser newParser = buffer.asParser(codec);
newParser.nextToken();
return super.deserialize(newParser, ctx);
}
private void recurse(TokenBuffer buffer, JsonParser p, ObjectMapper codec, boolean skipOuterbraces) throws IOException {
boolean firstToken = true;
JsonToken token;
JsonToken token;
while ((token = p.nextToken()) != null) {
String name = p.currentName();
if (skipOuterbraces && firstToken && JsonToken.START_OBJECT.equals(token)) {
continue;
}
if (skipOuterbraces && p.getParsingContext().inRoot() && JsonToken.END_OBJECT.equals(token)) {
continue;
}
if (JsonToken.VALUE_NULL.equals(token)) {
continue;
}
if (name != null && JsonToken.FIELD_NAME.equals(token) && name.startsWith(INCLUDE)) {
p.nextToken();
String fileName = p.getText();
@ -348,7 +346,7 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
} else {
buffer.copyCurrentEvent(p);
}
firstToken = false;
}
}

View File

@ -1,10 +1,8 @@
package org.openapitools.codegen.cmd;
import com.google.common.base.Objects;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
@ -20,18 +18,18 @@ import java.util.stream.Collectors;
@Command(name = "list", description = "Lists the available generators")
public class ListGenerators extends OpenApiGeneratorCommand {
@Option(name = {"-s", "--short" }, description = "shortened output (suitable for scripting)")
@Option(name = {"-s", "--short"}, description = "shortened output (suitable for scripting)")
private Boolean shortened = false;
@Option(name = {"-d", "--docsite" }, description = "format for docusaurus site output", hidden = true)
@Option(name = {"-d", "--docsite"}, description = "format for docusaurus site output", hidden = true)
private Boolean docusaurus = false;
@Option(name = {"--github-nested-index" }, description = "format for github index at docs/generators/README.md", hidden = true)
private Boolean githubNestedIndex = false;
@Option(name = {"--github-nested-index"}, description = "format for github index at docs/generators/README.md", hidden = true)
private Boolean githubNestedIndex = false;
@Option(name = {"-i", "--include" },
@Option(name = {"-i", "--include"},
description = "comma-separated list of stability indexes to include (value: all,beta,stable,experimental,deprecated). Excludes deprecated by default.",
allowedValues = { "all", "beta", "stable", "experimental", "deprecated" })
allowedValues = {"all", "beta", "stable", "experimental", "deprecated"})
private String include = "stable,beta,experimental";
@Override
@ -88,7 +86,7 @@ public class ListGenerators extends OpenApiGeneratorCommand {
.sorted(Comparator.comparing(CodegenConfig::getName))
.collect(Collectors.toList());
if(!list.isEmpty()) {
if (!list.isEmpty()) {
if (docusaurus || githubNestedIndex) {
sb.append("## ").append(typeName).append(" generators");
} else {

View File

@ -17,9 +17,7 @@
package org.openapitools.codegen.cmd;
import static ch.lambdaj.collection.LambdaCollections.with;
import static com.google.common.base.Joiner.on;
import ch.lambdaj.function.convert.Converter;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@ -31,9 +29,9 @@ import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.TemplateManager;
import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
import org.openapitools.codegen.templating.MustacheEngineAdapter;
import org.openapitools.codegen.templating.TemplateManagerOptions;
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -43,7 +41,8 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import ch.lambdaj.function.convert.Converter;
import static ch.lambdaj.collection.LambdaCollections.with;
import static com.google.common.base.Joiner.on;
/**
* User: lanwen Date: 24.03.15 Time: 20:22
@ -99,19 +98,19 @@ public class Meta extends OpenApiGeneratorCommand {
new SupportingFile("kotlin/generatorClassTest.mustache", on(File.separator).join("src/test/kotlin", asPath(targetPackage)), mainClass.concat("Test.kt")),
new SupportingFile("kotlin/README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"),
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()))
: ImmutableList.of(
new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
new SupportingFile("README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name,"model.mustache"),
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));
new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
new SupportingFile("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
new SupportingFile("README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"),
new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"),
new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"),
new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));
String currentVersion = buildInfo.getVersion();
@ -134,11 +133,11 @@ public class Meta extends OpenApiGeneratorCommand {
* destination directory
*
* @param targetDir - destination directory
* @param data - map with additional params needed to process templates
* @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj
*/
private static Converter<SupportingFile, File> processFiles(final File targetDir,
final Map<String, Object> data) {
final Map<String, Object> data) {
return support -> {
try {
File destinationFolder =
@ -148,7 +147,7 @@ public class Meta extends OpenApiGeneratorCommand {
TemplateManager templateProcessor = new TemplateManager(
new TemplateManagerOptions(false, false),
new MustacheEngineAdapter(),
new TemplatePathLocator[]{ new CommonTemplateContentLocator("codegen") }
new TemplatePathLocator[]{new CommonTemplateContentLocator("codegen")}
);
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.getTemplateFile()).getPath());

View File

@ -19,7 +19,6 @@ package org.openapitools.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
@ -35,7 +34,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
@SuppressWarnings({"unused","java:S106"})
@SuppressWarnings({"unused", "java:S106"})
@Command(name = "validate", description = "Validate specification")
public class Validate extends OpenApiGeneratorCommand {
@ -43,7 +42,7 @@ public class Validate extends OpenApiGeneratorCommand {
description = "location of the OpenAPI spec, as URL or file (required)")
private String spec;
@Option(name = { "--recommend"}, title = "recommend spec improvements")
@Option(name = {"--recommend"}, title = "recommend spec improvements")
private Boolean recommend;
@Option(

View File

@ -20,7 +20,7 @@ public class AuthorTemplateTest {
}
@Test
public void smokeTestAuthorTemplateCommand(){
public void smokeTestAuthorTemplateCommand() {
Cli.CliBuilder<Runnable> builder = createBuilder();
String[] arguments = new String[]{
"author",
@ -57,7 +57,7 @@ public class AuthorTemplateTest {
Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/okhttp-gson/auth/RetryingOAuth.mustache")));
}
private Cli.CliBuilder<Runnable> createBuilder(){
private Cli.CliBuilder<Runnable> createBuilder() {
Cli.CliBuilder<Runnable> builder = new Cli.CliBuilder<>("openapi-generator-cli");
builder.withGroup("author")

View File

@ -42,7 +42,7 @@ public class GenerateBatchTest {
@DataProvider(name = "customIncludeDeserializerFiles")
public Object[][] customIncludeDeserializerFiles() {
return new Object[][] {
return new Object[][]{
{JAXRS_DATELIB_J8_JSON},
{JAXRS_DATELIB_J8_YAML},
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML},
@ -89,7 +89,7 @@ public class GenerateBatchTest {
@SuppressWarnings("unused")
@Test(
expectedExceptions = { RuntimeException.class },
expectedExceptions = {RuntimeException.class},
expectedExceptionsMessageRegExp = "Unable to deserialize config file: .*"
)
public void testInvalidDeserializerWithIncludeOption() {

View File

@ -363,7 +363,7 @@ public class GenerateTest {
verify(configurator).toContext();
verifyNoMoreInteractions(configurator);
} finally {
if(!f.delete()) {
if (!f.delete()) {
System.out.println("Directory didn't delete. You can ignore this.");
}
}
@ -389,7 +389,7 @@ public class GenerateTest {
verify(configurator).toClientOptInput();
verify(configurator).toContext();
verifyNoMoreInteractions(configurator);
if(!f.delete()) {
if (!f.delete()) {
System.out.println("Directory didn't delete. You can ignore this.");
}
}

View File

@ -17,8 +17,8 @@
package org.openapitools.codegen.cmd.utils;
import org.openapitools.codegen.utils.OptionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.utils.OptionUtils;
import org.testng.annotations.Test;
import java.util.Collections;

View File

@ -27,7 +27,6 @@ public abstract class AbstractTemplatingEngineAdapter implements TemplatingEngin
* Gets all possible template paths for a given location.
*
* @param location The full location of the template.
*
* @return A new array of locations, modified according to the extensions or other adapter rules.
*/
protected String[] getModifiedFileLocation(String location) {
@ -44,7 +43,6 @@ public abstract class AbstractTemplatingEngineAdapter implements TemplatingEngin
* Returns the path without an extension for an input location.
*
* @param location The location of the file, with original file extension intact.
*
* @return The full path, without extension (e.g. /path/to/file.txt => /path/to/file)
*/
private String getPathWithoutExtension(String location) {

View File

@ -17,7 +17,7 @@ public class TemplateDefinition {
/**
* <p>Constructor for TemplateDefinition.</p>
*
* @param templateFile a template path relative to user template or embedded template.
* @param templateFile a template path relative to user template or embedded template.
* @param destinationFilename a target output location for the file, relative to the output directory.
*/
public TemplateDefinition(String templateFile, String destinationFilename) {
@ -34,8 +34,8 @@ public class TemplateDefinition {
/**
* <p>Constructor for TemplateDefinition.</p>
*
* @param templateFile a template path relative to user template or embedded template.
* @param folder a folder in the target output directory in which to place the target file.
* @param templateFile a template path relative to user template or embedded template.
* @param folder a folder in the target output directory in which to place the target file.
* @param destinationFilename a target output location for the file, relative to the output directory.
*/
public TemplateDefinition(String templateFile, String folder, String destinationFilename) {
@ -94,7 +94,9 @@ public class TemplateDefinition {
this.templateType = templateType;
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
@ -106,13 +108,17 @@ public class TemplateDefinition {
getTemplateType() == that.getTemplateType();
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType());
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]")

View File

@ -17,16 +17,22 @@ public enum TemplateFileType {
private final String templateType;
TemplateFileType(String templateType) { this.templateType = templateType; }
TemplateFileType(String templateType) {
this.templateType = templateType;
}
/**
* Returns the value for this template file type
*
* @return The template type of this enum.
*/
public String value() { return this.templateType; }
public String value() {
return this.templateType;
}
/** {@inheritDoc} */
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return new StringJoiner(", ", TemplateFileType.class.getSimpleName() + "[", "]")

View File

@ -12,10 +12,9 @@ public interface TemplateProcessor {
/**
* Writes data to a compiled template
*
* @param data Input data
* @param data Input data
* @param template Input template location
* @param target The targeted file output location
*
* @param target The targeted file output location
* @return The actual file
* @throws IOException If file cannot be written.
*/
@ -34,7 +33,7 @@ public interface TemplateProcessor {
/**
* Allow a caller to mark a path as ignored with accompanying reason
*
* @param path The ignored path
* @param path The ignored path
* @param context The reason for ignoring this path
*/
void ignore(Path path, String context);
@ -42,7 +41,7 @@ public interface TemplateProcessor {
/**
* Allow a caller to mark a path as skipped with accompanying reason
*
* @param path The skipped path
* @param path The skipped path
* @param context The reason for skipping this path
*/
void skip(Path path, String context);
@ -50,8 +49,9 @@ public interface TemplateProcessor {
/**
* Allow a caller to mark a path having errored during processing with accompanying reason
*
* @param path The path which has caused an error
* @param path The path which has caused an error
* @param context The reason for the error
*/
default void error(Path path, String context) { }
default void error(Path path, String context) {
}
}

View File

@ -47,8 +47,8 @@ public interface TemplatingEngineAdapter {
/**
* Determine if the adapter handles compilation of the file
* @param filename The template filename
*
* @param filename The template filename
* @return True if the file should be compiled by this adapter, else false.
*/
default boolean handlesFile(String filename) {
@ -58,7 +58,7 @@ public interface TemplatingEngineAdapter {
/**
* Compiles a template into a string
*
* @param executor From where we can fetch the templates content (e.g. an instance of DefaultGenerator)
* @param executor From where we can fetch the templates content (e.g. an instance of DefaultGenerator)
* @param bundle The map of values to pass to the template
* @param templateFile The name of the template (e.g. model.mustache )
* @return the processed template result

View File

@ -17,6 +17,7 @@
package org.openapitools.codegen.api;
// TODO: 6.0 Remove
/**
* interface to the full template content
* implementers might take into account the -t cli option,

View File

@ -340,7 +340,7 @@ public class WorkflowSettings {
* @return a reference to this Builder
*/
public Builder withOutputDir(String outputDir) {
if (outputDir != null ) {
if (outputDir != null) {
this.outputDir = Paths.get(outputDir).toAbsolutePath().toString();
} else {
this.outputDir = DEFAULT_OUTPUT_DIR;
@ -473,7 +473,7 @@ public class WorkflowSettings {
// check to see if the folder exists
if (f.exists() && f.isDirectory()) {
uri = f.toURI();
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
} else {
String cpDir;
// HACK: this duplicates TemplateManager.getCPResourcePath a bit. We should probably move that function to core.
@ -543,7 +543,7 @@ public class WorkflowSettings {
/**
* Sets the {@code globalProperties} and returns a reference to this Builder so that the methods can be chained together.
*
* @param key The key of a system (global) property to set
* @param key The key of a system (global) property to set
* @param value The value of a system (global) property to set
* @return a reference to this Builder
*/

View File

@ -383,7 +383,6 @@ public class FeatureSet {
* Includes the defined {@link ClientModificationFeature} to the new/existing set of supported features.
*
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
@ -395,7 +394,6 @@ public class FeatureSet {
* Excludes the defined {@link ClientModificationFeature} from the set of supported features.
*
* @param clientModificationFeature One or more {@code clientModificationFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeClientModificationFeatures(ClientModificationFeature... clientModificationFeature) {
@ -422,7 +420,6 @@ public class FeatureSet {
* Includes the defined {@link DataTypeFeature} to the new/existing set of supported features.
*
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
@ -434,7 +431,6 @@ public class FeatureSet {
* Excludes the defined {@link DataTypeFeature} from the set of supported features.
*
* @param dataTypeFeature One or more {@code dataTypeFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeDataTypeFeatures(DataTypeFeature... dataTypeFeature) {
@ -461,7 +457,6 @@ public class FeatureSet {
* Includes the defined {@link DocumentationFeature} to the new/existing set of supported features.
*
* @param documentationFeature One or more {@code documentationFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeDocumentationFeatures(DocumentationFeature... documentationFeature) {
@ -473,7 +468,6 @@ public class FeatureSet {
* Excludes the defined {@link DocumentationFeature} from the set of supported features.
*
* @param documentationFeature One or more {@code documentationFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeDocumentationFeatures(DocumentationFeature... documentationFeature) {
@ -500,7 +494,6 @@ public class FeatureSet {
* Includes the defined {@link SchemaSupportFeature} to the new/existing set of supported features.
*
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
@ -512,7 +505,6 @@ public class FeatureSet {
* Excludes the defined {@link SchemaSupportFeature} from the set of supported features.
*
* @param schemaSupportFeature One or more {@code schemaSupportFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeSchemaSupportFeatures(SchemaSupportFeature... schemaSupportFeature) {
@ -539,7 +531,6 @@ public class FeatureSet {
* Includes the defined {@link ParameterFeature} to the new/existing set of supported features.
*
* @param parameterFeature One or more {@code parameterFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeParameterFeatures(ParameterFeature... parameterFeature) {
@ -551,7 +542,6 @@ public class FeatureSet {
* Excludes the defined {@link ParameterFeature} from the set of supported features.
*
* @param parameterFeature One or more {@code parameterFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeParameterFeatures(ParameterFeature... parameterFeature) {
@ -578,7 +568,6 @@ public class FeatureSet {
* Includes the defined {@link SecurityFeature} to the new/existing set of supported features.
*
* @param securityFeature One or more {@code securityFeature} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeSecurityFeatures(SecurityFeature... securityFeature) {
@ -590,7 +579,6 @@ public class FeatureSet {
* Excludes the defined {@link SecurityFeature} from the set of supported features.
*
* @param securityFeature One or more {@code securityFeature} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeSecurityFeatures(SecurityFeature... securityFeature) {
@ -617,7 +605,6 @@ public class FeatureSet {
* Includes the defined {@link GlobalFeature} to the new/existing set of supported features.
*
* @param globalFeature One or more {@code globalFeatures} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeGlobalFeatures(GlobalFeature... globalFeature) {
@ -629,7 +616,6 @@ public class FeatureSet {
* Excludes the defined {@link GlobalFeature} from the set of supported features.
*
* @param globalFeature One or more {@code globalFeatures} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeGlobalFeatures(GlobalFeature... globalFeature) {
@ -656,7 +642,6 @@ public class FeatureSet {
* Includes the defined {@link WireFormatFeature} to the new/existing set of supported features.
*
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are included in the set.
*
* @return a reference to this Builder
*/
public Builder includeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {
@ -672,7 +657,6 @@ public class FeatureSet {
* </p>
*
* @param wireFormatFeature One or more {@code wireFormatFeatures} to ensure are excluded from the set.
*
* @return a reference to this Builder
*/
public Builder excludeWireFormatFeatures(WireFormatFeature... wireFormatFeature) {

View File

@ -49,10 +49,12 @@ public enum Stability {
*
* @return The descriptive value of this enum.
*/
public String value() { return description; }
public String value() {
return description;
}
public static Stability forDescription(String description) {
for (Stability value: values()) {
for (Stability value : values()) {
if (value.description.equals(description)) {
return value;
}

View File

@ -23,7 +23,7 @@ import org.openapitools.codegen.meta.features.annotations.ToolingExtension;
/**
* Defines common data types supported by a generator.
* Some of these features are defined in specs, and some are specific to the tool.
*
* <p>
* Where data types are listed as tool-specific, this either indicates that the data type is common enough that it is an officially
* supported custom data type by the toolset (see {@link DataTypeFeature#Decimal}), or that the consideration of a special type isn't
* explicitly mentioned by the specification(s) but differs enough across languages that it warrants a special callout (see {@link DataTypeFeature#ArrayOfModel}).
@ -114,9 +114,9 @@ public enum DataTypeFeature {
*
*
* <p>
* This should be used as an indicator for password best practices, such as assigning a variable to
* a character array rather than string, avoiding logging the variable in clear text, and masking the value
* in any user inputs. See OWASP for best practices.
* This should be used as an indicator for password best practices, such as assigning a variable to
* a character array rather than string, avoiding logging the variable in clear text, and masking the value
* in any user inputs. See OWASP for best practices.
* </p>
*/
@OAS2 @OAS3

View File

@ -129,7 +129,7 @@ public enum GlobalFeature {
*
* <p>
* NOTE: This option is more relevant for documentation generators which support HTML stylesheets, but may be used
* to determine structural characteristics of a property (as with OAS 3.x lack of collectionFormat).
* to determine structural characteristics of a property (as with OAS 3.x lack of collectionFormat).
* </p>
*/
@OAS3

View File

@ -45,7 +45,7 @@ public enum ParameterFeature {
* Supports body parameters.
*
* <p>
* OAS 3.x specification supports this structurally rather than as an "in" parameter.
* OAS 3.x specification supports this structurally rather than as an "in" parameter.
* </p>
*/
@OAS2
@ -53,7 +53,7 @@ public enum ParameterFeature {
/**
* Supports form encoded parameters.
*
* <p>
* OAS 3.x specification supports this structurally via content types rather than as an "in" parameter.
*/
@OAS2

View File

@ -54,11 +54,11 @@ public enum SchemaSupportFeature {
*
* <p>
* This means that a single "Type" in generated code may refer to one of any type in a set of 2 or more types.
*
* <p>
* This is defined as a union as "OneOf" support is not explicitly limited to physical boundaries in OpenAPI Specification. The
* implementation of such a type is easily represented dynamically (a JSON object), but requires explicit language support and
* potentially a custom implementation (typed instances).
*
* <p>
* Note that a generator may support "Unions" very loosely by returning an Object/Any/ref/interface{} type, leaving onus
* on type determination to the consumer. This does *NOT* suggest generated code implements a "Union Type".
* </p>

View File

@ -4,9 +4,9 @@ public enum AnnotationType {
OAS2, OAS3, ToolingExtension;
public static AnnotationType fromAnnotation(Class<?> input) {
if(input == OAS2.class) return AnnotationType.OAS2;
if(input == OAS3.class) return AnnotationType.OAS3;
if(input == ToolingExtension.class) return AnnotationType.ToolingExtension;
if (input == OAS2.class) return AnnotationType.OAS2;
if (input == OAS3.class) return AnnotationType.OAS3;
if (input == ToolingExtension.class) return AnnotationType.ToolingExtension;
return null;
}
}

View File

@ -39,7 +39,6 @@ public class GenericValidator<TInput> implements Validator<TInput> {
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
*
* @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/
@Override

View File

@ -28,7 +28,7 @@ public final class Invalid extends Validated {
/**
* Constructs a new {@link Invalid} instance.
*
* @param rule The rule which was evaluated and resulted in this state.
* @param rule The rule which was evaluated and resulted in this state.
* @param message The message to be displayed for this invalid state.
*/
Invalid(ValidationRule rule, String message) {
@ -39,7 +39,7 @@ public final class Invalid extends Validated {
/**
* Constructs a new {@link Invalid} instance.
*
* @param rule The rule which was evaluated and resulted in this state.
* @param rule The rule which was evaluated and resulted in this state.
* @param message The message to be displayed for this invalid state.
* @param details Additional contextual details related to the invalid state.
*/

View File

@ -46,21 +46,20 @@ public abstract class Validated {
/**
* Creates an instance of an {@link Invalid} validation state.
*
* @param rule The rule which was evaluated.
* @param rule The rule which was evaluated.
* @param message The message to display to a user.
*
* @return A {@link Validated} instance representing an invalid state according to the rule.
*/
public static Validated invalid(ValidationRule rule, String message) {
return new Invalid(rule, message);
}
/**
* Creates an instance of an {@link Invalid} validation state.
*
* @param rule The rule which was evaluated.
* @param rule The rule which was evaluated.
* @param message The message to display to a user.
* @param details Additional contextual details related to the invalid state.
*
* @return A {@link Validated} instance representing an invalid state according to the rule.
*/
public static Validated invalid(ValidationRule rule, String message, String details) {
@ -71,7 +70,6 @@ public abstract class Validated {
* Creates an instance of an {@link Valid} validation state.
*
* @param rule The rule which was evaluated.
*
* @return A {@link Validated} instance representing a valid state according to the rule.
*/
public static Validated valid(ValidationRule rule) {

View File

@ -49,7 +49,7 @@ public final class ValidationResult {
* @return All validated results.
*/
public List<Validated> getAll() {
return validations;
return validations;
}
/**
@ -57,8 +57,8 @@ public final class ValidationResult {
*
* @return A list containing only {@link Valid} states.
*/
public List<Valid> getValid(){
return validations.stream().filter(Validated::isValid).map(it -> (Valid)it).collect(Collectors.toList());
public List<Valid> getValid() {
return validations.stream().filter(Validated::isValid).map(it -> (Valid) it).collect(Collectors.toList());
}
/**
@ -66,10 +66,10 @@ public final class ValidationResult {
*
* @return A list of all validation errors.
*/
public List<Invalid> getErrors(){
public List<Invalid> getErrors() {
return validations.stream()
.filter(it -> !it.isValid())
.map(it -> (Invalid)it)
.map(it -> (Invalid) it)
.filter(it -> it.getSeverity().equals(Severity.ERROR))
.collect(Collectors.toList());
}
@ -79,10 +79,10 @@ public final class ValidationResult {
*
* @return A list of all validation warnings.
*/
public List<Invalid> getWarnings(){
public List<Invalid> getWarnings() {
return validations.stream()
.filter(it -> !it.isValid())
.map(it -> (Invalid)it)
.map(it -> (Invalid) it)
.filter(it -> it.getSeverity().equals(Severity.WARNING))
.collect(Collectors.toList());
}

View File

@ -31,11 +31,11 @@ public class ValidationRule {
/**
* Constructs a new instance of {@link ValidationRule}
*
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param test The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param test The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
*/
ValidationRule(Severity severity, String description, String failureMessage, Function<Object, Result> test) {
this.severity = severity;
@ -57,7 +57,6 @@ public class ValidationRule {
* Evaluate an instance of an object against this rule.
*
* @param input The instance to be evaluated.
*
* @return <code>true</code> if the object state is valid according to this rule, otherwise <code>false</code>.
*/
public Result evaluate(Object input) {
@ -90,19 +89,18 @@ public class ValidationRule {
* @return An "empty" rule.
*/
static ValidationRule empty() {
return new ValidationRule(Severity.ERROR, "empty", "failure message", (i) -> Fail.empty() );
return new ValidationRule(Severity.ERROR, "empty", "failure message", (i) -> Fail.empty());
}
/**
* Create an instance of a {@link ValidationRule}
*
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
@ -114,10 +112,9 @@ public class ValidationRule {
* Create an instance of a {@link ValidationRule} which should result in an error should the evaluate of this rule fail.
*
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
@ -128,12 +125,11 @@ public class ValidationRule {
/**
* Create an instance of a {@link ValidationRule} which should result in a warning should the evaluate of this rule fail.
*
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
@ -164,17 +160,24 @@ public class ValidationRule {
}
public abstract boolean passed();
public final boolean failed() { return !passed(); }
public final boolean failed() {
return !passed();
}
public Throwable getThrowable() {
return throwable;
}
public boolean thrown() { return this.throwable == null; }
public boolean thrown() {
return this.throwable == null;
}
}
public static final class Pass extends Result {
public static Result empty() { return new Pass(); }
public static Result empty() {
return new Pass();
}
public Pass() {
super();
@ -192,7 +195,9 @@ public class ValidationRule {
}
public static final class Fail extends Result {
public static Result empty() { return new Fail(); }
public static Result empty() {
return new Fail();
}
public Fail() {
super();

View File

@ -27,7 +27,6 @@ public interface Validator<TInput> {
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
*
* @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/
ValidationResult validate(TInput input);

View File

@ -25,7 +25,7 @@ import static org.testng.Assert.*;
public class WorkflowSettingsTest {
@Test
public void defaultValuesNotOverriddenByNulls(){
public void defaultValuesNotOverriddenByNulls() {
WorkflowSettings settings = WorkflowSettings.newBuilder()
.withOutputDir(null)
.withVerbose(null)
@ -50,7 +50,7 @@ public class WorkflowSettingsTest {
}
@Test
public void newBuilderFromCopyShouldMutateGlobalProperties(){
public void newBuilderFromCopyShouldMutateGlobalProperties() {
WorkflowSettings original = WorkflowSettings.newBuilder()
.withOutputDir("output")
.withVerbose(true)
@ -110,16 +110,17 @@ public class WorkflowSettingsTest {
}
@Test
public void defaultValuesCanBeChangedClassConstructor(){
public void defaultValuesCanBeChangedClassConstructor() {
WorkflowSettings defaults = new WorkflowSettings();
assertOnChangesToDefaults(defaults);
}
@Test
public void defaultValuesCanBeChangedBuilder(){
public void defaultValuesCanBeChangedBuilder() {
WorkflowSettings defaults = WorkflowSettings.newBuilder().build();
assertOnChangesToDefaults(defaults);
}
@Test
public void customOutputDirIsSet() {
WorkflowSettings settings = WorkflowSettings.newBuilder()

View File

@ -18,12 +18,13 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class GenericValidatorTest {
static class Person {
private int age;
@ -53,7 +54,7 @@ public class GenericValidatorTest {
}
private static ValidationRule.Result checkNameNormalLength(Person person) {
return person.name.length() < 10? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
return person.name.length() < 10 ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
}
private List<ValidationRule> validationRules = Arrays.asList(
@ -65,7 +66,7 @@ public class GenericValidatorTest {
);
@Test
public void testGenericValidatorSuccesses(){
public void testGenericValidatorSuccesses() {
Person person = new Person("Jim", 23);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
@ -79,7 +80,7 @@ public class GenericValidatorTest {
}
@Test
public void testGenericValidatorSingleConditionFails(){
public void testGenericValidatorSingleConditionFails() {
Person person = new Person("Jim", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
@ -98,7 +99,7 @@ public class GenericValidatorTest {
}
@Test
public void testGenericValidatorMultipleConditionsFail(){
public void testGenericValidatorMultipleConditionsFail() {
Person person = new Person("asdf", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
@ -122,7 +123,7 @@ public class GenericValidatorTest {
}
@Test
public void testGenericValidatorErrorsAndWarnings(){
public void testGenericValidatorErrorsAndWarnings() {
Person person = new Person("0123456789asdfghjkl", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);

View File

@ -18,17 +18,18 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class ValidatedTest {
@Test
public void isValidTrueForValidType(){
public void isValidTrueForValidType() {
boolean isValid = Validated.valid(ValidationRule.empty()).isValid();
assertTrue(isValid);
}
@Test
public void isValidFalseForInvalidType(){
public void isValidFalseForInvalidType() {
boolean isValid = Validated.invalid(ValidationRule.empty(), "test").isValid();
assertFalse(isValid);
}

View File

@ -18,7 +18,8 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class ValidationRuleTest {
static class Sample {
@ -39,11 +40,11 @@ public class ValidationRuleTest {
private static ValidationRule.Result checkPattern(Sample input) {
String pattern = "^[A-Z][a-z]*$";
return (input.getName() != null && input.getName().matches(pattern)) ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
return (input.getName() != null && input.getName().matches(pattern)) ? ValidationRule.Pass.empty() : ValidationRule.Fail.empty();
}
@Test
public void createMethodUsingMethodReference(){
public void createMethodUsingMethodReference() {
Sample nil = new Sample(null);
Sample six = new Sample("123456");
Sample seven = new Sample("1234567");
@ -56,11 +57,11 @@ public class ValidationRuleTest {
}
@Test
public void createMethodUsingLambda(){
public void createMethodUsingLambda() {
Sample nil = new Sample(null);
Sample lowercase = new Sample("jim");
Sample titlecase = new Sample("Jim");
ValidationRule result = ValidationRule.error("test", i -> checkPattern((Sample)i));
ValidationRule result = ValidationRule.error("test", i -> checkPattern((Sample) i));
assertFalse(result.evaluate(nil).passed());
assertFalse(result.evaluate(lowercase).passed());
assertTrue(result.evaluate(titlecase).passed());

View File

@ -30,11 +30,13 @@ import lombok.Setter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.*;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.openapitools.codegen.*;
@ -49,7 +51,10 @@ import org.sonatype.plexus.build.incremental.DefaultBuildContext;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.MessageFormat;
@ -156,7 +161,7 @@ public class CodeGenMojo extends AbstractMojo {
/**
* The name of templating engine to use, "mustache" (default) or "handlebars" (beta)
*/
@Parameter(name = "engine", defaultValue = "mustache", property="openapi.generator.maven.plugin.engine")
@Parameter(name = "engine", defaultValue = "mustache", property = "openapi.generator.maven.plugin.engine")
private String engine;
/**
@ -541,7 +546,7 @@ public class CodeGenMojo extends AbstractMojo {
if (StringUtils.isNotBlank(inputSpecRootDirectory)) {
inputSpec = new MergedSpecBuilder(inputSpecRootDirectory, mergedFileName)
.buildMergedSpec();
.buildMergedSpec();
LOGGER.info("Merge input spec would be used - {}", inputSpec);
}
@ -572,7 +577,7 @@ public class CodeGenMojo extends AbstractMojo {
return;
}
if (buildContext != null && inputSpec != null ) {
if (buildContext != null && inputSpec != null) {
if (buildContext.isIncremental() &&
inputSpecFile.exists() &&
!buildContext.hasDelta(inputSpecFile)) {
@ -664,7 +669,7 @@ public class CodeGenMojo extends AbstractMojo {
configurator.setEnablePostProcessFile(enablePostProcessFile);
}
if (generateAliasAsModel != null) {
if (generateAliasAsModel != null) {
configurator.setGenerateAliasAsModel(generateAliasAsModel);
}
@ -974,7 +979,7 @@ public class CodeGenMojo extends AbstractMojo {
File parent = new File(storedInputSpecHashFile.getParent());
if (!parent.mkdirs()) {
throw new RuntimeException("Failed to create the folder " + parent.getAbsolutePath() +
" to store the checksum of the input spec.");
" to store the checksum of the input spec.");
}
}
@ -993,7 +998,7 @@ public class CodeGenMojo extends AbstractMojo {
}
/**
* Calculate an SHA256 hash for the openapi specification.
* Calculate an SHA256 hash for the openapi specification.
* If the specification is hosted on a remote resource it is downloaded first.
*
* @param inputSpec - Openapi specification input file. Can denote a URL or file path.
@ -1002,18 +1007,19 @@ public class CodeGenMojo extends AbstractMojo {
private String calculateInputSpecHash(String inputSpec) {
final ParseOptions parseOptions = new ParseOptions();
parseOptions.setResolve(true);
final URL remoteUrl = inputSpecRemoteUrl();
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
return Hashing.sha256().hashBytes(
new OpenAPIParser().readLocation(remoteUrl == null ? inputSpec : remoteUrl.toString(), authorizationValues, parseOptions)
.getOpenAPI().toString().getBytes(StandardCharsets.UTF_8)
new OpenAPIParser().readLocation(remoteUrl == null ? inputSpec : remoteUrl.toString(), authorizationValues, parseOptions)
.getOpenAPI().toString().getBytes(StandardCharsets.UTF_8)
).toString();
}
/**
* Try to parse inputSpec setting string into URL
*
* @return A valid URL or null if inputSpec is not a valid URL
*/
private URL inputSpecRemoteUrl() {
@ -1026,8 +1032,9 @@ public class CodeGenMojo extends AbstractMojo {
/**
* Get specification hash file
*
* @param inputSpecFile - Openapi specification input file to calculate its hash.
* Does not take into account if input spec is hosted on remote resource
* Does not take into account if input spec is hosted on remote resource
* @return a file with previously calculated hash
*/
private File getHashFile(File inputSpecFile) {

View File

@ -94,13 +94,13 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
assertTrue(Files.exists(tempDir.resolve(
"target/generated-sources/common-maven/remote-openapi/.openapi-generator/petstore.yaml-executionId.sha256"
"target/generated-sources/common-maven/remote-openapi/.openapi-generator/petstore.yaml-executionId.sha256"
)));
}
/**
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
* test that the spec is not regenerated when the hash has not changed.
* test that the spec is not regenerated when the hash has not changed.
*/
public void testSkipRegenerationForClasspathSpecFileNoChange() throws Exception {
//GIVEN
@ -114,7 +114,7 @@ public class CodeGenMojoTest extends BaseTestCase {
/* Check the hash file was created */
final Path generatedDir = tempDir.resolve("target/generated-sources/common-maven/remote-openapi");
assertTrue(Files.exists(
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256")
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256")
));
/* Remove the generated source */
@ -134,7 +134,7 @@ public class CodeGenMojoTest extends BaseTestCase {
/**
* For a Pom file which refers to an input file which will be on the classpath, as opposed to a file path,
* test that the generated source is regenerated when the hash has changed.
* test that the generated source is regenerated when the hash has changed.
*/
public void testSkipRegenerationForClasspathSpecFileWithChange() throws Exception {
//GIVEN
@ -151,12 +151,12 @@ public class CodeGenMojoTest extends BaseTestCase {
/* Update the hash contents to be a different value, simulating a spec change */
Files.write(
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256"),
List.of("bd1bf4a953c858f9d47b67ed6029daacf1707e5cbd3d2e4b01383ba30363366f")
generatedDir.resolve(".openapi-generator/petstore-on-classpath.yaml-executionId.sha256"),
List.of("bd1bf4a953c858f9d47b67ed6029daacf1707e5cbd3d2e4b01383ba30363366f")
);
/* Remove the generated source */
try(Stream<Path> files = Files.walk(generatedDir.resolve("src"))) {
try (Stream<Path> files = Files.walk(generatedDir.resolve("src"))) {
//noinspection ResultOfMethodCallIgnored
files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
}
@ -181,7 +181,7 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
assertTrue(Files.exists(
tempDir.resolve("target/generated-sources/common-maven/remote-openapi/petstore-full-spec.yaml")
tempDir.resolve("target/generated-sources/common-maven/remote-openapi/petstore-full-spec.yaml")
));
}
@ -194,8 +194,8 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
List<Artifact> matchingArtifacts = mojo.mavenProject.getAttachedArtifacts().stream()
.filter(artifact -> artifact.getFile().getName().equals("petstore-full-spec.yaml"))
.collect(Collectors.toList());
.filter(artifact -> artifact.getFile().getName().equals("petstore-full-spec.yaml"))
.collect(Collectors.toList());
assertEquals(1, matchingArtifacts.size());
}
@ -242,7 +242,7 @@ public class CodeGenMojoTest extends BaseTestCase {
var currentHash = Files.readString(hashFile); // read hash
FileUtils.deleteDirectory(generatedDir.resolve("src").toFile()); // Remove the generated source
Files.writeString( // change schema definition in external file
tempDir.resolve("schemas/Pet.yaml"),"\n wrapped: true", StandardOpenOption.APPEND
tempDir.resolve("schemas/Pet.yaml"), "\n wrapped: true", StandardOpenOption.APPEND
);
// WHEN
@ -250,8 +250,8 @@ public class CodeGenMojoTest extends BaseTestCase {
// THEN
assertNotEquals(
Files.readString(hashFile), currentHash, "Checksum should not be the same after external file change"
);
Files.readString(hashFile), currentHash, "Checksum should not be the same after external file change"
);
assertTrue("Src directory should have been regenerated", Files.exists(generatedDir.resolve("src")));
}
@ -269,7 +269,7 @@ public class CodeGenMojoTest extends BaseTestCase {
}
private MojoExecution copyWithExecutionId(String executionId, MojoExecution execution) {
MojoExecution executionWithId = new MojoExecution(execution.getMojoDescriptor(), executionId);
MojoExecution executionWithId = new MojoExecution(execution.getMojoDescriptor(), executionId);
executionWithId.setConfiguration(execution.getConfiguration());
return executionWithId;
}
@ -278,18 +278,18 @@ public class CodeGenMojoTest extends BaseTestCase {
LocalRepository localRepo = new LocalRepository(basedir.resolve("local-repo").toFile());
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
session.setLocalRepositoryManager(
new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer()).newInstance(session, localRepo)
new SimpleLocalRepositoryManagerFactory(new DefaultLocalPathComposer()).newInstance(session, localRepo)
);
MavenExecutionRequest request = new DefaultMavenExecutionRequest().setBaseDirectory(basedir.toFile());
if (profile != null) {
request.addActiveProfile(profile);
}
ProjectBuildingRequest configuration = request.getProjectBuildingRequest()
.setRepositorySession(session)
.setResolveDependencies(true);
.setRepositorySession(session)
.setResolveDependencies(true);
MavenProject project = lookup(ProjectBuilder.class)
.build(basedir.resolve("pom.xml").toFile(), configuration)
.getProject();
.build(basedir.resolve("pom.xml").toFile(), configuration)
.getProject();
assertNotNull(project);
return project;
}

View File

@ -20,6 +20,6 @@ import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
public class CommonMavenProjectStub extends MavenProjectStub {
public CommonMavenProjectStub() {
StubUtility.configureStub(this,"common-maven", "common-maven.xml");
StubUtility.configureStub(this, "common-maven", "common-maven.xml");
}
}

View File

@ -28,7 +28,7 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
@ComponentScan(basePackages = { "org.openapitools.codegen.online", "org.openapitools.codegen.online.api", "org.openapitools.codegen.online.configuration"})
@ComponentScan(basePackages = {"org.openapitools.codegen.online", "org.openapitools.codegen.online.api", "org.openapitools.codegen.online.configuration"})
public class OpenAPI2SpringBoot implements CommandLineRunner {
@Override

View File

@ -26,14 +26,14 @@ import java.util.Date;
public class RFC3339DateFormat extends ISO8601DateFormat {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
// Same as ISO8601DateFormat but serializing milliseconds.
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true);
toAppendTo.append(value);
return toAppendTo;
}
// Same as ISO8601DateFormat but serializing milliseconds.
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true);
toAppendTo.append(value);
return toAppendTo;
}
}

View File

@ -17,16 +17,15 @@
package org.openapitools.codegen.online.api;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiOriginFilter implements javax.servlet.Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

View File

@ -42,9 +42,9 @@ import java.util.Map;
public interface GenApi {
GenApiDelegate getDelegate();
@ApiOperation(value = "Gets languages supported by the client generator", nickname = "clientOptions", notes = "", response = String.class, responseContainer = "List", tags={ "clients", })
@ApiOperation(value = "Gets languages supported by the client generator", nickname = "clientOptions", notes = "", response = String.class, responseContainer = "List", tags = {"clients",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List") })
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List")})
@RequestMapping(value = "/gen/clients",
method = RequestMethod.GET)
default ResponseEntity<List<String>> clientOptions() {
@ -52,62 +52,62 @@ public interface GenApi {
}
@ApiOperation(value = "Downloads a pre-generated file", nickname = "downloadFile", notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST operations. The fileId code can be used just once, after which a new `fileId` will need to be requested.", response = MultipartFile.class, tags={ "clients","servers", })
@ApiOperation(value = "Downloads a pre-generated file", nickname = "downloadFile", notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST operations. The fileId code can be used just once, after which a new `fileId` will need to be requested.", response = MultipartFile.class, tags = {"clients", "servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = MultipartFile.class) })
@ApiResponse(code = 200, message = "successful operation", response = MultipartFile.class)})
@RequestMapping(value = "/gen/download/{fileId}",
produces = { "application/octet-stream" },
produces = {"application/octet-stream"},
method = RequestMethod.GET)
default ResponseEntity<Resource> downloadFile(@ApiParam(value = "",required=true) @PathVariable("fileId") String fileId) {
default ResponseEntity<Resource> downloadFile(@ApiParam(value = "", required = true) @PathVariable("fileId") String fileId) {
return getDelegate().downloadFile(fileId);
}
@ApiOperation(value = "Generates a client library", nickname = "generateClient", notes = "Accepts a `GeneratorInput` options map for spec location and generation options", response = ResponseCode.class, tags={ "clients", })
@ApiOperation(value = "Generates a client library", nickname = "generateClient", notes = "Accepts a `GeneratorInput` options map for spec location and generation options", response = ResponseCode.class, tags = {"clients",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class) })
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class)})
@RequestMapping(value = "/gen/clients/{language}",
method = RequestMethod.POST)
default ResponseEntity<ResponseCode> generateClient(@ApiParam(value = "The target language for the client library",required=true) @PathVariable("language") String language,@ApiParam(value = "Configuration for building the client library" ,required=true ) @Valid @RequestBody GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateClient(@ApiParam(value = "The target language for the client library", required = true) @PathVariable("language") String language, @ApiParam(value = "Configuration for building the client library", required = true) @Valid @RequestBody GeneratorInput generatorInput) {
return getDelegate().generateClient(language, generatorInput);
}
@ApiOperation(value = "Generates a server library", nickname = "generateServerForLanguage", notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", response = ResponseCode.class, tags={ "servers", })
@ApiOperation(value = "Generates a server library", nickname = "generateServerForLanguage", notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", response = ResponseCode.class, tags = {"servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class) })
@ApiResponse(code = 200, message = "successful operation", response = ResponseCode.class)})
@RequestMapping(value = "/gen/servers/{framework}",
method = RequestMethod.POST)
default ResponseEntity<ResponseCode> generateServerForLanguage(@ApiParam(value = "framework",required=true) @PathVariable("framework") String framework,@ApiParam(value = "parameters" ,required=true ) @Valid @RequestBody GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateServerForLanguage(@ApiParam(value = "framework", required = true) @PathVariable("framework") String framework, @ApiParam(value = "parameters", required = true) @Valid @RequestBody GeneratorInput generatorInput) {
return getDelegate().generateServerForLanguage(framework, generatorInput);
}
@ApiOperation(value = "Returns options for a client library", nickname = "getClientOptions", notes = "", tags={ "clients", })
@ApiOperation(value = "Returns options for a client library", nickname = "getClientOptions", notes = "", tags = {"clients",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") })
@ApiResponse(code = 200, message = "successful operation")})
@RequestMapping(value = "/gen/clients/{language}",
produces = { "application/json" },
produces = {"application/json"},
method = RequestMethod.GET)
default ResponseEntity<Map<String, CliOption>> getClientOptions(@ApiParam(value = "The target language for the client library",required=true) @PathVariable("language") String language) {
default ResponseEntity<Map<String, CliOption>> getClientOptions(@ApiParam(value = "The target language for the client library", required = true) @PathVariable("language") String language) {
return getDelegate().getClientOptions(language);
}
@ApiOperation(value = "Returns options for a server framework", nickname = "getServerOptions", notes = "", tags={ "servers", })
@ApiOperation(value = "Returns options for a server framework", nickname = "getServerOptions", notes = "", tags = {"servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") })
@ApiResponse(code = 200, message = "successful operation")})
@RequestMapping(value = "/gen/servers/{framework}",
produces = { "application/json" },
produces = {"application/json"},
method = RequestMethod.GET)
default ResponseEntity<Map<String, CliOption>> getServerOptions(@ApiParam(value = "The target language for the server framework",required=true) @PathVariable("framework") String framework) {
default ResponseEntity<Map<String, CliOption>> getServerOptions(@ApiParam(value = "The target language for the server framework", required = true) @PathVariable("framework") String framework) {
return getDelegate().getServerOptions(framework);
}
@ApiOperation(value = "Gets languages supported by the server generator", nickname = "serverOptions", notes = "", response = String.class, responseContainer = "List", tags={ "servers", })
@ApiOperation(value = "Gets languages supported by the server generator", nickname = "serverOptions", notes = "", response = String.class, responseContainer = "List", tags = {"servers",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List") })
@ApiResponse(code = 200, message = "successful operation", response = String.class, responseContainer = "List")})
@RequestMapping(value = "/gen/servers",
method = RequestMethod.GET)
default ResponseEntity<List<String>> serverOptions() {

View File

@ -42,12 +42,12 @@ public interface GenApiDelegate {
}
/**
* @see GenApi#clientOptions
* @return A {@link ResponseEntity} listing options for the target client generator.
* @see GenApi#clientOptions
*/
default ResponseEntity<List<String>> clientOptions() {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
break;
@ -60,24 +60,24 @@ public interface GenApiDelegate {
/**
* @param fileId The unique id of the file, provided in a {@link ResponseCode} response.
* @see GenApi#downloadFile
* @return A {@link ResponseEntity} of the requested {@link Resource}.
* @see GenApi#downloadFile
*/
default ResponseEntity<Resource> downloadFile(String fileId) {
default ResponseEntity<Resource> downloadFile(String fileId) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
/**
* @param language The target generator (language is a misnomer here, but kept for API consistency).
* @param language The target generator (language is a misnomer here, but kept for API consistency).
* @param generatorInput The configuration settings to be used during client generation.
* @see GenApi#generateClient
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested client code.
* @see GenApi#generateClient
*/
default ResponseEntity<ResponseCode> generateClient( String language,
GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateClient(String language,
GeneratorInput generatorInput) {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
break;
@ -89,15 +89,15 @@ public interface GenApiDelegate {
}
/**
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
* @param generatorInput The configuration settings to be used during server generation.
* @see GenApi#generateServerForLanguage
* @return A {@link ResponseEntity} referencing the unique download id and a link to download the requested server code.
* @see GenApi#generateServerForLanguage
*/
default ResponseEntity<ResponseCode> generateServerForLanguage( String framework,
GeneratorInput generatorInput) {
default ResponseEntity<ResponseCode> generateServerForLanguage(String framework,
GeneratorInput generatorInput) {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
break;
@ -110,31 +110,31 @@ public interface GenApiDelegate {
/**
* @param language The target generator (language is a misnomer here, but kept for API consistency).
* @see GenApi#getClientOptions
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by language (generator name).
* @see GenApi#getClientOptions
*/
default ResponseEntity<Map<String, CliOption>> getClientOptions(String language) {
default ResponseEntity<Map<String, CliOption>> getClientOptions(String language) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
/**
* @param framework The target generator name (framework is a slight misnomer here, as we may have a framework like Spring implemented in multiple languages).
* @see GenApi#getServerOptions
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by framework (generator name).
* @see GenApi#getServerOptions
*/
default ResponseEntity<Map<String, CliOption>> getServerOptions( String framework) {
default ResponseEntity<Map<String, CliOption>> getServerOptions(String framework) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
/**
* @see GenApi#serverOptions
* @return A {@link ResponseEntity} listing options for the target server generator.
* @see GenApi#serverOptions
*/
default ResponseEntity<List<String>> serverOptions() {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "\"\"");
break;

View File

@ -18,6 +18,9 @@
package org.openapitools.codegen.online.configuration;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
@ -28,17 +31,14 @@ import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.HashSet;
@Configuration
@ -59,22 +59,22 @@ public class OpenAPIDocumentationConfig {
String version = properties.getProperty("version", "unknown");
return new ApiInfoBuilder()
.title("OpenAPI Generator Online")
.description("This is an online openapi generator server. You can find out more at https://github.com/OpenAPITools/openapi-generator.")
.license("Apache 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version(version)
.contact(new Contact("","", ""))
.build();
.title("OpenAPI Generator Online")
.description("This is an online openapi generator server. You can find out more at https://github.com/OpenAPITools/openapi-generator.")
.license("Apache 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version(version)
.contact(new Contact("", "", ""))
.build();
}
@Bean
public Docket customImplementation(){
public Docket customImplementation() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api"))
.build()
.apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api"))
.build()
.forCodeGeneration(true)
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
@ -99,7 +99,7 @@ public class OpenAPIDocumentationConfig {
docket.host(authority);
}
docket.pathMapping(hostURI.getPath());
} catch(URISyntaxException e) {
} catch (URISyntaxException e) {
LOGGER.warn("Could not parse configured GENERATOR_HOST '" + hostString + "': " + e.getMessage());
}
}

View File

@ -35,7 +35,8 @@ public class ApiResponse {
@Getter String type;
@Getter String message;
public ApiResponse() {}
public ApiResponse() {
}
public ApiResponse(int code, String message) {
this.code = code;

View File

@ -20,7 +20,8 @@ package org.openapitools.codegen.online.model;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
@Getter
@Setter
public class Generated {
private String filename;
private String friendlyName;

View File

@ -22,7 +22,9 @@ import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter @NoArgsConstructor @AllArgsConstructor
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ResponseCode {
private String code;
private String link;

View File

@ -22,11 +22,7 @@ import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import io.swagger.v3.parser.core.models.ParseOptions;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.*;
import org.openapitools.codegen.online.model.GeneratorInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -35,11 +31,7 @@ import org.springframework.web.server.ResponseStatusException;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.*;
public class Generator {
private static Logger LOGGER = LoggerFactory.getLogger(Generator.class);
@ -49,7 +41,7 @@ public class Generator {
try {
config = CodegenConfigLoader.forName(language);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT,"Unsupported target %s supplied. %s",
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(Locale.ROOT, "Unsupported target %s supplied. %s",
language, e));
}
Map<String, CliOption> map = new LinkedHashMap<>();
@ -82,7 +74,7 @@ public class Generator {
}
private static String generate(String language, GeneratorInput opts, Type type) {
LOGGER.debug(String.format(Locale.ROOT,"generate %s for %s", type.getTypeName(), language));
LOGGER.debug(String.format(Locale.ROOT, "generate %s for %s", type.getTypeName(), language));
if (opts == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No options were supplied");
}
@ -141,13 +133,13 @@ public class Generator {
codegenConfig.additionalProperties().put("openAPI", openapi);
}
if(opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()){
for(String rule: opts.getOpenapiNormalizer()){
if (opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()) {
for (String rule : opts.getOpenapiNormalizer()) {
String[] ruleOperands = rule.split("=");
if(ruleOperands.length != 2) {
if (ruleOperands.length != 2) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "In rule: " + rule + "the operands were not provided in the form of <Rule>=<Value>");
}
codegenConfig.openapiNormalizer().put(ruleOperands[0],ruleOperands[1]);
codegenConfig.openapiNormalizer().put(ruleOperands[0], ruleOperands[1]);
}
}

View File

@ -17,12 +17,7 @@
package org.openapitools.codegen.online.service;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@ -32,7 +27,6 @@ import java.util.zip.ZipOutputStream;
* sub files and sub directories, recursively.
*
* @author Ha Minh Nam
*
*/
public class ZipUtil {
/**
@ -43,10 +37,10 @@ public class ZipUtil {
/**
* Compresses a collection of files to a destination zip file.
*
* @param listFiles A collection of files and directories
* @param listFiles A collection of files and directories
* @param destZipFile The path of the destination zip file
* @throws FileNotFoundException if file not found
* @throws IOException if IO exception occurs
* @throws IOException if IO exception occurs
*/
public void compressFiles(List<File> listFiles, String destZipFile)
throws IOException {
@ -69,11 +63,11 @@ public class ZipUtil {
/**
* Adds a directory to the current zip output stream.
*
* @param folder the directory to be added
* @param folder the directory to be added
* @param parentFolder the path of parent directory
* @param zos the current zip output stream
* @param zos the current zip output stream
* @throws FileNotFoundException if file not found
* @throws IOException if IO exception occurs
* @throws IOException if IO exception occurs
*/
private void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos)
throws FileNotFoundException, IOException {
@ -103,9 +97,9 @@ public class ZipUtil {
* Adds a file to the current zip output stream.
*
* @param file the file to be added
* @param zos the current zip output stream
* @param zos the current zip output stream
* @throws FileNotFoundException if file not found
* @throws IOException if IO exception occurs
* @throws IOException if IO exception occurs
*/
private static void addFileToZip(File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {

View File

@ -88,8 +88,8 @@ public class GenApiControllerTest {
private void generateAndDownload(String type, String name) throws Exception {
String result = mockMvc.perform(post("http://test.com:1234/api/gen/" + type + "/" + name)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.contentType(MediaType.APPLICATION_JSON)
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
@ -107,11 +107,11 @@ public class GenApiControllerTest {
@Test
public void generateWIthForwardedHeaders() throws Exception {
String result = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Forwarded-Proto", "https")
.header("X-Forwarded-Host", "forwarded.com")
.header("X-Forwarded-Port", "5678")
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.contentType(MediaType.APPLICATION_JSON)
.header("X-Forwarded-Proto", "https")
.header("X-Forwarded-Host", "forwarded.com")
.header("X-Forwarded-Port", "5678")
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
@ -141,8 +141,8 @@ public class GenApiControllerTest {
String withoutOpenAPINormalizer = "{\"openAPIUrl\":\"https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml\",\"options\":{},\"spec\":{}}";
String responseOfNormalized = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
.contentType(MediaType.APPLICATION_JSON)
.content(withOpenAPINormalizer))
.contentType(MediaType.APPLICATION_JSON)
.content(withOpenAPINormalizer))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String codeOfNormalized = new ObjectMapper().readValue(responseOfNormalized, ResponseCode.class).getCode();
Long lengthOfNormalized = Long.parseLong(mockMvc.perform(get("http://test.com:1234/api/gen/download/" + codeOfNormalized))
@ -159,7 +159,7 @@ public class GenApiControllerTest {
.andExpect(content().contentType("application/zip"))
.andExpect(status().isOk()).andReturn().getResponse().getHeader("Content-Length"));
Assert.isTrue(lengthOfNormalized <= lengthOfNotNormalized,"Using the normalizer should result in a smaller or equal file size");
Assert.isTrue(lengthOfNormalized <= lengthOfNotNormalized, "Using the normalizer should result in a smaller or equal file size");
}
}

View File

@ -60,7 +60,7 @@ public class CliOption {
}
public void setOptValue(String optValue) {
if (this.enumValues!=null && this.enumValues.containsKey(optValue)) {
if (this.enumValues != null && this.enumValues.containsKey(optValue)) {
this.optValue = optValue;
} else {
this.optValue = null;
@ -88,7 +88,7 @@ public class CliOption {
/**
* Create new boolean command line option with a default of false
*
* @param opt Option name
* @param opt Option name
* @param description Option description
* @return the CliOption created
*/
@ -99,8 +99,8 @@ public class CliOption {
/**
* Create new boolean command line option with the provided value as default
*
* @param opt Option name
* @param description Option description
* @param opt Option name
* @param description Option description
* @param defaultValue the default value to use if option not specified
* @return the CliOption created
*/
@ -115,7 +115,7 @@ public class CliOption {
@JsonIgnore
public String getOptionHelp() {
StringBuilder sb = new StringBuilder(description);
if(defaultValue != null) {
if (defaultValue != null) {
sb.append(" (Default: ").append(defaultValue).append(")");
}
if (enumValues != null) {

View File

@ -19,7 +19,6 @@ package org.openapitools.codegen;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import lombok.Getter;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.auth.AuthParser;
@ -84,8 +83,8 @@ public class ClientOptInput {
/**
* Sets the generator/config instance
*
* @deprecated use {@link #config(CodegenConfig)} instead
* @param config codegen config
* @deprecated use {@link #config(CodegenConfig)} instead
*/
@Deprecated
public void setConfig(CodegenConfig config) {
@ -118,8 +117,8 @@ public class ClientOptInput {
/**
* Sets the OpenAPI document
*
* @deprecated use {@link #openAPI(OpenAPI)} instead
* @param openAPI the specification
* @deprecated use {@link #openAPI(OpenAPI)} instead
*/
@Deprecated
public void setOpenAPI(OpenAPI openAPI) {

View File

@ -38,6 +38,7 @@ public class CodegenCallback {
return Objects.equals(that.expression, expression) &&
Objects.equals(that.requests, requests) && Objects.equals(that.vendorExtensions, vendorExtensions);
}
@Override
public int hashCode() {
return Objects.hash(expression, requests, vendorExtensions);

View File

@ -19,9 +19,11 @@ package org.openapitools.codegen;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
import java.util.List;
import java.util.Objects;
@Getter @Setter
@Getter
@Setter
public class CodegenComposedSchemas {
private List<CodegenProperty> allOf;
private List<CodegenProperty> oneOf;

View File

@ -372,9 +372,9 @@ public class CodegenConstants {
public static final String GENERATE_ALIAS_AS_MODEL = "generateAliasAsModel";
public static final String GENERATE_ALIAS_AS_MODEL_DESC = "Generate model implementation for aliases to map and array schemas. " +
"An 'alias' is an array, map, or list which is defined inline in a OpenAPI document and becomes a model in the generated code. " +
"A 'map' schema is an object that can have undeclared properties, i.e. the 'additionalproperties' attribute is set on that object. " +
"An 'array' schema is a list of sub schemas in a OAS document";
"An 'alias' is an array, map, or list which is defined inline in a OpenAPI document and becomes a model in the generated code. " +
"A 'map' schema is an object that can have undeclared properties, i.e. the 'additionalproperties' attribute is set on that object. " +
"An 'array' schema is a list of sub schemas in a OAS document";
public static final String USE_COMPARE_NET_OBJECTS = "useCompareNetObjects";
public static final String USE_COMPARE_NET_OBJECTS_DESC = "Use KellermanSoftware.CompareNetObjects for deep recursive object comparison. WARNING: this option incurs potential performance impact.";
@ -405,16 +405,16 @@ public class CodegenConstants {
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT = "disallowAdditionalPropertiesIfNotPresent";
public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC =
"If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. " +
"If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.";
"If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. " +
"If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.";
public static final String UNSUPPORTED_V310_SPEC_MSG =
"OpenAPI 3.1 support is still in beta. To report an issue related to 3.1 spec, please kindly open an issue in the Github repo: https://github.com/openAPITools/openapi-generator.";
"OpenAPI 3.1 support is still in beta. To report an issue related to 3.1 spec, please kindly open an issue in the Github repo: https://github.com/openAPITools/openapi-generator.";
public static final String ENUM_UNKNOWN_DEFAULT_CASE = "enumUnknownDefaultCase";
public static final String ENUM_UNKNOWN_DEFAULT_CASE_DESC =
"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.";
"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.";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP = "useOneOfDiscriminatorLookup";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC = "Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.";
@ -438,7 +438,7 @@ public class CodegenConstants {
public static final String FASTAPI_IMPLEMENTATION_PACKAGE = "fastapiImplementationPackage";
public static final String WITH_XML = "withXml";
public static final String WITH_GO_MOD = "withGoMod";
public static final String GENERATE_MARSHAL_JSON = "generateMarshalJSON";

View File

@ -8,7 +8,7 @@ import java.util.*;
/**
* This class encapsulates the OpenAPI discriminator construct, as specified at
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#discriminatorObject.
*
* <p>
* When request bodies or response payloads may be one of a number of different schemas,
* a discriminator object can be used to aid in serialization, deserialization, and validation.
* The discriminator is a specific object in a schema which is used to inform the consumer of
@ -57,18 +57,18 @@ public class CodegenDiscriminator {
public void setIsEnum(boolean isEnum) {
this.isEnum = isEnum;
}
/**
* An object to hold discriminator mappings between payload values and schema names or
* references.
*
* <p>
* In the OpenAPI document, the discriminator "mapping" attribute is optional.
* In scenarios where the value of the discriminator field does not match the schema name
* or implicit mapping is not possible, an optional mapping definition MAY be used.
* In OpenAPITools codegen, the MappedModel is the union of all the discriminator mappings,
* both explicitly defined in the OpenAPI document and inherited from oneOf/allOf/anyOf.
*/
public static class MappedModel implements Comparable<MappedModel>{
public static class MappedModel implements Comparable<MappedModel> {
// The value of the discriminator property in the payload.
@Getter @Setter
private String mappingName;

View File

@ -8,7 +8,8 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
@Getter public class CodegenMediaType {
@Getter
public class CodegenMediaType {
private CodegenProperty schema;
private LinkedHashMap<String, CodegenEncoding> encoding;
private HashMap<String, SchemaTestCase> testCases = new HashMap<>();
@ -47,7 +48,7 @@ import java.util.Objects;
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodegenMediaType that = (CodegenMediaType) o;
return Objects.equals(schema,that.getSchema()) &&
return Objects.equals(schema, that.getSchema()) &&
Objects.equals(encoding, that.getEncoding()) &&
Objects.equals(vendorExtensions, that.vendorExtensions);
}

View File

@ -19,13 +19,12 @@ package org.openapitools.codegen;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.v3.oas.models.ExternalDocumentation;
import java.util.*;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* CodegenModel represents a schema object in a OpenAPI document.
*/
@ -85,39 +84,39 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public String unescapedDescription;
/**
* -- GETTER --
* Returns the discriminator for this schema object, or null if no discriminator has been specified.
* The list of all possible schema discriminator mapping values is obtained
* from explicit discriminator mapping values in the OpenAPI document, and from
* inherited discriminators through oneOf, allOf, anyOf.
* For example, a discriminator may be defined in a 'Pet' schema as shown below.
* The Dog and Cat schemas inherit the discriminator through the allOf reference.
* In the 'Pet' schema, the supported discriminator mapping values for the
* 'objectType' properties are 'Dog' and 'Cat'.
* The allowed discriminator mapping value for the Dog schema is 'Dog'.
* The allowed discriminator mapping value for the Cat schema is 'Dog'.
* Pet:
* type: object
* discriminator:
* propertyName: objectType
* required:
* - objectType
* properties:
* objectType:
* type: string
* Dog:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p1:
* type: string
* Cat:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p2:
* type: string
* Returns the discriminator for this schema object, or null if no discriminator has been specified.
* The list of all possible schema discriminator mapping values is obtained
* from explicit discriminator mapping values in the OpenAPI document, and from
* inherited discriminators through oneOf, allOf, anyOf.
* For example, a discriminator may be defined in a 'Pet' schema as shown below.
* The Dog and Cat schemas inherit the discriminator through the allOf reference.
* In the 'Pet' schema, the supported discriminator mapping values for the
* 'objectType' properties are 'Dog' and 'Cat'.
* The allowed discriminator mapping value for the Dog schema is 'Dog'.
* The allowed discriminator mapping value for the Cat schema is 'Dog'.
* Pet:
* type: object
* discriminator:
* propertyName: objectType
* required:
* - objectType
* properties:
* objectType:
* type: string
* Dog:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p1:
* type: string
* Cat:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* properties:
* p2:
* type: string
*
* @return the discriminator.
*/
@ -174,7 +173,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public boolean isArray;
public boolean hasChildren;
public boolean isMap;
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
/**
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
*/
public boolean isOptional;
public boolean isNull;
public boolean isVoid = false;
@ -208,7 +209,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
/**
* The type of the value for the additionalProperties keyword in the OAS document.
* Used in map like objects, including composed schemas.
*
* <p>
* In most programming languages, the additional (undeclared) properties are stored
* in a map data structure, such as HashMap in Java, map in golang, or a dict in Python.
* There are multiple ways to implement the additionalProperties keyword, depending
@ -218,24 +219,23 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
* In that case 'CodegenModel.parent' is set to represent the class hierarchy.
* Another way is to use CodegenModel.additionalPropertiesType. A code generator
* such as Python does not use class inheritance to model additional properties.
*
* <p>
* For example, in the OAS schema below, the schema has a declared 'id' property
* and additional, undeclared properties of type 'integer' are allowed.
*
* <p>
* type: object
* properties:
* id:
* type: integer
* id:
* type: integer
* additionalProperties:
* type: integer
*
* type: integer
*/
@Getter @Setter
public String additionalPropertiesType;
/**
* True if additionalProperties is set to true (boolean value), any type, free form object, etc
*
* <p>
* TODO: we may rename this to isAdditionalPropertiesEnabled or something
* else to avoid confusions
*/
@ -758,14 +758,22 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public boolean getIsUuid() { return isUuid; }
public boolean getIsUuid() {
return isUuid;
}
@Override
public void setIsUuid(boolean isUuid) { this.isUuid = isUuid; }
public void setIsUuid(boolean isUuid) {
this.isUuid = isUuid;
}
public boolean getIsUri() { return isUri; }
public boolean getIsUri() {
return isUri;
}
public void setIsUri(boolean isUri) { this.isUri = isUri; }
public void setIsUri(boolean isUri) {
this.isUri = isUri;
}
@Override
public void setComposedSchemas(CodegenComposedSchemas composedSchemas) {
@ -833,7 +841,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public void setIsBinary(boolean isBinary) {}
public void setIsBinary(boolean isBinary) {
}
@Override
public boolean getIsByteArray() {
@ -841,7 +850,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public void setIsByteArray(boolean isByteArray) {}
public void setIsByteArray(boolean isByteArray) {
}
@Override
public boolean getIsDecimal() {
@ -1005,7 +1015,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
sb.append(", parent='").append(parent).append('\'');
sb.append(", parentSchema='").append(parentSchema).append('\'');
sb.append(", interfaces=").append(interfaces);
sb.append(", interfaceModels=").append(interfaceModels !=null ? interfaceModels.size() : "[]");
sb.append(", interfaceModels=").append(interfaceModels != null ? interfaceModels.size() : "[]");
sb.append(", allParents=").append(allParents);
sb.append(", parentModel=").append(parentModel);
sb.append(", children=").append(children != null ? children.size() : "[]");
@ -1141,10 +1151,14 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
}
@Override
public Map<String, CodegenProperty> getRequiredVarsMap() { return requiredVarsMap; }
public Map<String, CodegenProperty> getRequiredVarsMap() {
return requiredVarsMap;
}
@Override
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; }
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) {
this.requiredVarsMap = requiredVarsMap;
}
/**
* Remove duplicated properties in all variable list

View File

@ -24,7 +24,8 @@ public final class CodegenModelFactory {
public static <T> T newInstance(CodegenModelType type) {
try {
return (T) type.getDefaultImplementation().getDeclaredConstructor().newInstance();
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException |
InvocationTargetException e) {
throw new RuntimeException(e);
}
}

View File

@ -19,7 +19,8 @@ package org.openapitools.codegen;
import lombok.Getter;
@Getter public enum CodegenModelType {
@Getter
public enum CodegenModelType {
MODEL(CodegenModel.class),
OPERATION(CodegenOperation.class),

View File

@ -220,7 +220,9 @@ public class CodegenOperation {
*
* @return true if responses contain only 1 entry and it's a default response, false otherwise
*/
public boolean getHasOnlyDefaultResponse() { return responses.size() == 1 && getHasDefaultResponse(); }
public boolean getHasOnlyDefaultResponse() {
return responses.size() == 1 && getHasDefaultResponse();
}
public boolean getAllResponsesAreErrors() {
return responses.stream().allMatch(response -> response.is4xx || response.is5xx);
@ -237,7 +239,7 @@ public class CodegenOperation {
return null;
}
LinkedHashMap<String, CodegenMediaType> content = bodyParam.getContent();
for (String contentType: content.keySet()) {
for (String contentType : content.keySet()) {
contentTypeToOperation.put(contentType, this);
}
return contentTypeToOperation;

View File

@ -17,17 +17,12 @@
package org.openapitools.codegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import io.swagger.v3.oas.models.examples.Example;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
/**
* Describes a single operation parameter in the OAS specification.
* A unique parameter is defined by a combination of a name and location.
@ -50,7 +45,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary,
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isShort, isUnboundedInteger;
public boolean isArray, isMap;
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
/**
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
*/
public boolean isOptional;
public boolean isFile;
public boolean isEnum;
@ -291,7 +288,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation,
getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(),
getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(),
getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull,isVoid,
getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, isVoid,
additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger,
hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content,
requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties,

View File

@ -20,12 +20,7 @@ package org.openapitools.codegen;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperties {
/**
@ -178,7 +173,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
public boolean isAnyType;
public boolean isArray;
public boolean isMap;
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
/**
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
*/
public boolean isOptional;
public boolean isEnum; // true if the enum is defined inline
public boolean isInnerEnum; // Enums declared inline will be located inside the generic model, changing how the enum is referenced in some cases.
@ -243,7 +240,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
private boolean hasDiscriminatorWithNonEmptyMapping;
private CodegenComposedSchemas composedSchemas = null;
private boolean hasMultipleTypes = false;
/** true if the property's baseName != name, e.g. baseName = '_prop.value', name = 'propValue' after sanitization */
/**
* true if the property's baseName != name, e.g. baseName = '_prop.value', name = 'propValue' after sanitization
*/
private boolean hasSanitizedName = false;
private Map<String, CodegenProperty> requiredVarsMap;
private String ref;
@ -849,7 +848,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
return hasSanitizedName;
}
public void setHasSanitizedName(boolean hasSanitizedName) { this.hasSanitizedName = hasSanitizedName; }
public void setHasSanitizedName(boolean hasSanitizedName) {
this.hasSanitizedName = hasSanitizedName;
}
@Override
public boolean getIsUuid() {

View File

@ -63,7 +63,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public boolean simpleType;
public boolean primitiveType;
public boolean isMap;
/** datatype is the generic inner parameter of a std::optional for C++, or Optional (Java) */
/**
* datatype is the generic inner parameter of a std::optional for C++, or Optional (Java)
*/
public boolean isOptional;
public boolean isArray;
public boolean isBinary = false;
@ -212,7 +214,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setContains instead of this
@Override
public void setContains(CodegenProperty contains) {}
public void setContains(CodegenProperty contains) {
}
// use content.mediaType.schema.getDependentRequired instead of this
@Override
@ -222,7 +225,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setDependentRequired instead of this
@Override
public void setDependentRequired(LinkedHashMap<String, List<String>> dependentRequired) {}
public void setDependentRequired(LinkedHashMap<String, List<String>> dependentRequired) {
}
// use content.mediaType.schema.getIsBooleanSchemaTrue instead of this
@Override
@ -232,7 +236,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setIsBooleanSchemaTrue instead of this
@Override
public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {}
public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {
}
// use content.mediaType.schema.getIsBooleanSchemaFalse instead of this
@Override
@ -242,7 +247,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setIsBooleanSchemaFalse instead of this
@Override
public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {}
public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {
}
// use content.mediaType.schema.getFormat instead of this
@Override
@ -252,7 +258,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setFormat instead of this
@Override
public void setFormat(String format) {}
public void setFormat(String format) {
}
@Override
public String getPattern() {
@ -782,16 +789,24 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
}
@Override
public Map<String, CodegenProperty> getRequiredVarsMap() { return requiredVarsMap; }
public Map<String, CodegenProperty> getRequiredVarsMap() {
return requiredVarsMap;
}
@Override
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; }
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) {
this.requiredVarsMap = requiredVarsMap;
}
@Override
public String getRef() { return ref; }
public String getRef() {
return ref;
}
@Override
public void setRef(String ref) { this.ref=ref; }
public void setRef(String ref) {
this.ref = ref;
}
@Override
public boolean getSchemaIsFromAdditionalProperties() {
@ -889,5 +904,6 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
}
@Override
public void setIsEnum(boolean isEnum) {}
public void setIsEnum(boolean isEnum) {
}
}

View File

@ -17,11 +17,7 @@
package org.openapitools.codegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
import java.util.stream.Collectors;
public class CodegenSecurity {
@ -49,10 +45,10 @@ public class CodegenSecurity {
// OpenId specific
public String openIdConnectUrl;
public CodegenSecurity () {
public CodegenSecurity() {
}
public CodegenSecurity (CodegenSecurity original) {
public CodegenSecurity(CodegenSecurity original) {
this.name = original.name;
this.description = original.description;
this.type = original.type;
@ -97,8 +93,8 @@ public class CodegenSecurity {
// In such cases, no filtering is performed.
if (!(Boolean.TRUE.equals(isOAuth) || Boolean.TRUE.equals(isOpenId))) {
filteredSecurity.scopes = filterScopes.stream()
.map(s -> new HashMap<String, Object>(Map.of("scope", s)))
.collect(Collectors.toList());
.map(s -> new HashMap<String, Object>(Map.of("scope", s)))
.collect(Collectors.toList());
return filteredSecurity;
}

View File

@ -70,10 +70,10 @@ import org.openapitools.codegen.utils.OneOfImplementorAdditionalData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Map.Entry;
@ -350,7 +350,6 @@ public class DefaultCodegen implements CodegenConfig {
* first from additionalProperties
* then from the getter in this instance
* then from the fields in this instance
*
*/
protected void useCodegenAsMustacheParentContext() {
additionalProperties.put(CodegenConstants.MUSTACHE_PARENT_CONTEXT, this);
@ -392,7 +391,7 @@ public class DefaultCodegen implements CodegenConfig {
convertPropertyToBooleanAndWriteBack(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, this::setDisallowAdditionalPropertiesIfNotPresent);
convertPropertyToBooleanAndWriteBack(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE, this::setEnumUnknownDefaultCase);
convertPropertyToBooleanAndWriteBack(CodegenConstants.AUTOSET_CONSTANTS, this::setAutosetConstants);
}
}
/***
@ -546,6 +545,7 @@ public class DefaultCodegen implements CodegenConfig {
* This usually occurs when the data type is different.
* We can also consider discriminators as new because the derived class discriminator will have to be defined again
* to contain a new value. Doing so prevents having to include the discriminator in the constructor.
*
* @param model
* @param property
* @return
@ -553,9 +553,9 @@ public class DefaultCodegen implements CodegenConfig {
private boolean codegenPropertyIsNew(CodegenModel model, CodegenProperty property) {
return model.parentModel == null
? false
: model.parentModel.allVars.stream().anyMatch(p ->
p.name.equals(property.name) &&
(p.dataType.equals(property.dataType) == false || p.datatypeWithEnum.equals(property.datatypeWithEnum) == false));
: model.parentModel.allVars.stream().anyMatch(p ->
p.name.equals(property.name) &&
(p.dataType.equals(property.dataType) == false || p.datatypeWithEnum.equals(property.datatypeWithEnum) == false));
}
/**
@ -874,8 +874,8 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Return the enum default value in the language specified format
*
* @param property The codegen property to create the default for.
* @param value Enum variable name
* @param property The codegen property to create the default for.
* @param value Enum variable name
* @return the default value for the enum
*/
public String toEnumDefaultValue(CodegenProperty property, String value) {
@ -1133,6 +1133,7 @@ public class DefaultCodegen implements CodegenConfig {
/**
* This method escapes text to be used in a single quoted string
*
* @param input the input string
* @return the escaped string
*/
@ -3275,7 +3276,7 @@ public class DefaultCodegen implements CodegenConfig {
}
if (refSchema.getProperties() != null && refSchema.getProperties().get(discPropName) != null) {
Schema discSchema = ModelUtils.getReferencedSchema(openAPI, (Schema)refSchema.getProperties().get(discPropName));
Schema discSchema = ModelUtils.getReferencedSchema(openAPI, (Schema) refSchema.getProperties().get(discPropName));
CodegenProperty cp = new CodegenProperty();
if (ModelUtils.isStringSchema(discSchema)) {
cp.isString = true;
@ -6904,7 +6905,7 @@ public class DefaultCodegen implements CodegenConfig {
* writes it back to additionalProperties to be usable as a boolean in
* mustache files.
*
* @param propertyKey property key
* @param propertyKey property key
* @param booleanSetter the setter function reference
* @return property value as boolean or false if it does not exist
*/
@ -6923,7 +6924,7 @@ public class DefaultCodegen implements CodegenConfig {
* writes it back to additionalProperties to be usable as a string in
* mustache files.
*
* @param propertyKey property key
* @param propertyKey property key
* @param stringSetter the setter function reference
* @return property value as String or null if not found
*/
@ -6936,7 +6937,7 @@ public class DefaultCodegen implements CodegenConfig {
* writes it back to additionalProperties to be usable as T in
* mustache files.
*
* @param propertyKey property key
* @param propertyKey property key
* @param genericTypeSetter the setter function reference
* @return property value as instance of type T or null if not found
*/
@ -8237,7 +8238,7 @@ public class DefaultCodegen implements CodegenConfig {
int exitValue = p.exitValue();
if (exitValue != 0) {
try (InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(inputStreamReader)) {
BufferedReader br = new BufferedReader(inputStreamReader)) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
@ -8391,7 +8392,8 @@ public class DefaultCodegen implements CodegenConfig {
public void addImportsToOneOfInterface(List<Map<String, String>> imports) {
}
//// End of methods related to the "useOneOfInterfaces" feature
/// / End of methods related to the "useOneOfInterfaces" feature
protected void modifyFeatureSet(Consumer<FeatureSet.Builder> processor) {
FeatureSet.Builder builder = getFeatureSet().modify();
@ -8403,7 +8405,8 @@ public class DefaultCodegen implements CodegenConfig {
/**
* An map entry for cached sanitized names.
*/
@Getter private static class SanitizeNameOptions {
@Getter
private static class SanitizeNameOptions {
public SanitizeNameOptions(String name, String removeCharRegEx, List<String> exceptions) {
this.name = name;
this.removeCharRegEx = removeCharRegEx;

View File

@ -18,11 +18,7 @@
package org.openapitools.codegen;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.SpecVersion;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
@ -35,12 +31,8 @@ import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.api.TemplateProcessor;
import org.openapitools.codegen.api.*;
import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.api.TemplatingEngineAdapter;
import org.openapitools.codegen.api.TemplateFileType;
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
@ -50,15 +42,13 @@ import org.openapitools.codegen.templating.CommonTemplateContentLocator;
import org.openapitools.codegen.templating.GeneratorTemplateContentLocator;
import org.openapitools.codegen.templating.MustacheEngineAdapter;
import org.openapitools.codegen.templating.TemplateManagerOptions;
import org.openapitools.codegen.utils.ImplementationVersion;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.openapitools.codegen.utils.URLPathUtils;
import org.openapitools.codegen.utils.SemVer;
import org.openapitools.codegen.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@ -97,8 +87,8 @@ public class DefaultGenerator implements Generator {
private String contextPath;
private Map<String, String> generatorPropertyDefaults = new HashMap<>();
/**
* Retrieves an instance to the configured template processor, available after user-defined options are
* applied via
* Retrieves an instance to the configured template processor, available after user-defined options are
* applied via
*/
@Getter protected TemplateProcessor templateProcessor = null;
@ -461,7 +451,7 @@ public class DefaultGenerator implements Generator {
}
Set<String> modelKeys = modelKeysSupplier.get();
if(modelKeys.isEmpty()) {
if (modelKeys.isEmpty()) {
return;
}
@ -536,11 +526,11 @@ public class DefaultGenerator implements Generator {
allProcessedModels = config.postProcessAllModels(allProcessedModels);
if (generateRecursiveDependentModels) {
for(ModelsMap modelsMap : allProcessedModels.values()) {
for(ModelMap mm: modelsMap.getModels()) {
for (ModelsMap modelsMap : allProcessedModels.values()) {
for (ModelMap mm : modelsMap.getModels()) {
CodegenModel cm = mm.getModel();
if (cm != null) {
for(CodegenProperty variable : cm.getVars()) {
for (CodegenProperty variable : cm.getVars()) {
generateModelsForVariable(files, allModels, unusedModels, aliasModels, processedModels, variable);
}
//TODO: handle interfaces
@ -552,7 +542,7 @@ public class DefaultGenerator implements Generator {
}
}
}
// generate files based on processed models
for (String modelName : allProcessedModels.keySet()) {
ModelsMap models = allProcessedModels.get(modelName);
@ -616,10 +606,10 @@ public class DefaultGenerator implements Generator {
if (!processedModels.contains(key) && allSchemas.containsKey(key)) {
generateModels(files, allModels, unusedModels, aliasModels, processedModels, () -> Set.of(key));
} else {
LOGGER.info("Type " + variable.getComplexType()+" of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
LOGGER.info("Type " + variable.getComplexType() + " of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
}
} else {
LOGGER.info("Type " + variable.getOpenApiType()+" of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
LOGGER.info("Type " + variable.getOpenApiType() + " of variable " + variable.getName() + " could not be resolve because it is not declared as a model.");
}
}
@ -627,7 +617,7 @@ public class DefaultGenerator implements Generator {
Map<String, Schema> schemaMap = ModelUtils.getSchemas(this.openAPI);
Set<String> keys = schemaMap.keySet();
String simpleRef;
if(keys.contains(type)) {
if (keys.contains(type)) {
return type;
} else if (keys.contains(simpleRef = ModelUtils.getSimpleRef(ref))) {
return simpleRef;
@ -688,7 +678,7 @@ public class DefaultGenerator implements Generator {
for (String tag : paths.keySet()) {
try {
List<CodegenOperation> ops = paths.get(tag);
if(!this.config.isSkipSortingOperations()) {
if (!this.config.isSkipSortingOperations()) {
// sort operations by operationId
ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId));
}
@ -931,17 +921,17 @@ public class DefaultGenerator implements Generator {
String outputDir = config.getOutputDir() + File.separator + config.templateOutputDirs().get(templateName);
String filename = config.apiFilename(templateName, tag, outputDir);
// do not overwrite apiController file for spring server
if (apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)){
if (apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)) {
written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS, outputDir);
} else {
LOGGER.info("Implementation file {} is not overwritten",filename);
LOGGER.info("Implementation file {} is not overwritten", filename);
}
} else {
String filename = config.apiFilename(templateName, tag);
if(apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)){
if (apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)) {
written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS);
} else {
LOGGER.info("Implementation file {} is not overwritten",filename);
LOGGER.info("Implementation file {} is not overwritten", filename);
}
}
if (written != null) {
@ -1218,9 +1208,9 @@ public class DefaultGenerator implements Generator {
* <p>
* Examples:
* <p>
* boolean hasOAuthMethods
* boolean hasOAuthMethods
* <p>
* List&lt;CodegenSecurity&gt; oauthMethods
* List&lt;CodegenSecurity&gt; oauthMethods
*
* @param bundle the map which the booleans and collections will be added
*/
@ -1490,7 +1480,7 @@ public class DefaultGenerator implements Generator {
return ops;
}
public Map<String, List<CodegenOperation>> processWebhooks(Map<String, PathItem> webhooks) {
public Map<String, List<CodegenOperation>> processWebhooks(Map<String, PathItem> webhooks) {
Map<String, List<CodegenOperation>> ops = new TreeMap<>();
// when input file is not valid and doesn't contain any paths
if (webhooks == null) {
@ -1619,7 +1609,7 @@ public class DefaultGenerator implements Generator {
}
private static String generateParameterId(Parameter parameter) {
return null == parameter.get$ref() ? parameter.getName() + ":" + parameter.getIn() : parameter.get$ref() ;
return null == parameter.get$ref() ? parameter.getName() + ":" + parameter.getIn() : parameter.get$ref();
}
private OperationsMap processOperations(CodegenConfig config, String tag, List<CodegenOperation> ops, List<ModelMap> allModels) {
@ -2013,7 +2003,7 @@ public class DefaultGenerator implements Generator {
}
});
Collections.sort(relativePaths, (a, b) -> IOCase.SENSITIVE.checkCompareTo(a,b));
Collections.sort(relativePaths, (a, b) -> IOCase.SENSITIVE.checkCompareTo(a, b));
relativePaths.forEach(relativePath -> {
sb.append(relativePath).append(System.lineSeparator());
});

View File

@ -9,25 +9,26 @@ import java.util.Locale;
/**
* Holds details about a file's write status for display via the --dry-run option of CLI
*/
@Getter class DryRunStatus {
@Getter
class DryRunStatus {
/**
* -- GETTER --
* Gets the target path of the file write operation
* Gets the target path of the file write operation
*
* @return a {@link Path} instance
*/
private final Path path;
/**
* -- GETTER --
* Gets the
* as determined by the generator's workflow
* Gets the
* as determined by the generator's workflow
*
* @return A {@link State} enum detailing the expected operation of the generator's workflow
*/
private State state;
/**
* -- GETTER --
* Gets the reason for the file's
* Gets the reason for the file's
*
* @return A human-readable string which explains why this file's dry-run resulted in the defined {@link State}
*/
@ -110,7 +111,8 @@ import java.util.Locale;
/**
* Represents the possible states of a file write operation as determined by the Generator
*/
@Getter enum State {
@Getter
enum State {
Write("w", "Write"),
WriteIfNewer("n", "Write if New/Updated"),
Ignored("i", "Ignored"),
@ -120,14 +122,14 @@ import java.util.Locale;
/**
* -- GETTER --
* Gets the short value used for display
* Gets the short value used for display
*
* @return A character representing this state
*/
private final String shortDisplay;
/**
* -- GETTER --
* Gets a description of the state which is more human-readable than the enum's name
* Gets a description of the state which is more human-readable than the enum's name
*
* @return A human-readable description
*/

View File

@ -18,7 +18,7 @@ import java.util.Map;
public class DryRunTemplateManager implements TemplateProcessor {
private final TemplateManagerOptions options;
private final Map<String, DryRunStatus> dryRunStatusMap = new HashMap<>();
private final Map<String, Map<String, Object>> capturedTemplateData = new HashMap<>();
private boolean recordTemplateData = false;
@ -65,9 +65,9 @@ public class DryRunTemplateManager implements TemplateProcessor {
if (outputFile.exists()) {
if (this.options.isSkipOverwrite()) {
status = new DryRunStatus(
path,
DryRunStatus.State.SkippedOverwrite,
"File exists and skip overwrite option is enabled."
path,
DryRunStatus.State.SkippedOverwrite,
"File exists and skip overwrite option is enabled."
);
} else if (this.options.isMinimalUpdate()) {
status.setState(DryRunStatus.State.WriteIfNewer);
@ -118,10 +118,11 @@ public class DryRunTemplateManager implements TemplateProcessor {
}
/**
* Retrieve the captured template data for a specific file. Capturing must have
* Retrieve the captured template data for a specific file. Capturing must have
* been enabled via {@link #enableTemplateDataCapturing()} prior to generation.<br>
* Note: Not all files have template data (e.g. Metadata files) in such case an empty
* map is returned.
*
* @param generatedFile An absolute path to the generated file
* @return Typically one of the *Map types found in {@link org.openapitools.codegen.model}
*/

View File

@ -1,20 +1,13 @@
package org.openapitools.codegen;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.meta.FeatureSet;
import org.openapitools.codegen.meta.features.SchemaSupportFeature;
import org.openapitools.codegen.utils.ModelUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import java.util.*;
import java.util.stream.Stream;
public interface IJsonSchemaValidationProperties {
CodegenProperty getContains();
@ -108,14 +101,15 @@ public interface IJsonSchemaValidationProperties {
/**
* Tells if the datatype is a generic inner parameter of a <code>std::optional</code> for C++, or <code>Optional</code> (Java)<br>
* to resolve cases (detected in issue #6726) where :<br>
* - <code>categoryOneOf</code> is a parameter of class <code>GetAccountVideos_categoryOneOf_parameter</code>, a model parameter that correctly prefixed by its namespace: <code>org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter</code><br>
* - but that <code>GetAccountVideos_categoryOneOf_parameter</code> class is inside an <code>std::optional</code><br>
* <br>
* Then a correct generation of that parameter can be (for C++) <code>const std::optional&lt;org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter&gt; &amp;categoryOneOf</code><br>
* but using #isModel alone without #isOptional in mustache might produce <code>const org::openapitools::server::model::std::optional&lt;org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter&gt; &amp;categoryOneOf</code> instead, that do not compile.
* to resolve cases (detected in issue #6726) where :<br>
* - <code>categoryOneOf</code> is a parameter of class <code>GetAccountVideos_categoryOneOf_parameter</code>, a model parameter that correctly prefixed by its namespace: <code>org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter</code><br>
* - but that <code>GetAccountVideos_categoryOneOf_parameter</code> class is inside an <code>std::optional</code><br>
* <br>
* Then a correct generation of that parameter can be (for C++) <code>const std::optional&lt;org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter&gt; &amp;categoryOneOf</code><br>
* but using #isModel alone without #isOptional in mustache might produce <code>const org::openapitools::server::model::std::optional&lt;org::openapitools::server::model::GetAccountVideos_categoryOneOf_parameter&gt; &amp;categoryOneOf</code> instead, that do not compile.
*/
boolean getIsOptional();
void setIsOptional(boolean isOptional);
boolean getIsArray();

View File

@ -22,8 +22,6 @@ import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.annotations.Webhook;
import io.swagger.v3.oas.annotations.Webhooks;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.PathItem.HttpMethod;
import io.swagger.v3.oas.models.callbacks.Callback;
@ -37,7 +35,6 @@ import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.util.*;
public class InlineModelResolver {
@ -118,7 +115,7 @@ public class InlineModelResolver {
* Flatten inline models in Webhooks
*/
private void flattenWebhooks() {
Map<String, PathItem> webhooks = openAPI.getWebhooks();
Map<String, PathItem> webhooks = openAPI.getWebhooks();
if (webhooks == null) {
return;
}
@ -536,8 +533,8 @@ public class InlineModelResolver {
/**
* Flatten inline models in parameters
*
* @param modelName model name
* @param parameters list of parameters
* @param modelName model name
* @param parameters list of parameters
* @param operationId operation Id (optional)
*/
private void flattenParameters(String modelName, List<Parameter> parameters, String operationId) {
@ -619,18 +616,18 @@ public class InlineModelResolver {
* allOf:
* - $ref: '#/components/schemas/Animal'
* - type: object
* properties:
* name:
* type: string
* age:
* type: string
* properties:
* name:
* type: string
* age:
* type: string
* - type: object
* properties:
* breed:
* type: string
* properties:
* breed:
* type: string
*
* @param key a unique name for the composed schema.
* @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf).
* @param key a unique name for the composed schema.
* @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf).
* @param skipAllOfInlineSchemas true if allOf inline schemas need to be skipped.
*/
private void flattenComposedChildren(String key, List<Schema> children, boolean skipAllOfInlineSchemas) {

View File

@ -20,23 +20,24 @@ public class ObjectWithTypeBooleans {
* Other booleans: isUnboundedInteger/isNumber/isString/isMap/isArray/isBoolean/isNull
* allow generator templates to decide how to render each payload into code
* based upon what type it is. The booleans isX describe the value in value.
*
* @param value the input payload that is stored
*/
public ObjectWithTypeBooleans(Object value) {
Object usedValue = null;
if (value instanceof Integer){
if (value instanceof Integer) {
this.isUnboundedInteger = true;
this.value = value;
} else if (value instanceof Double || value instanceof Float){
} else if (value instanceof Double || value instanceof Float) {
this.isNumber = true;
this.value = value;
} else if (value instanceof String) {
this.isString = true;
this.isString = true;
this.value = value;
} else if (value instanceof LinkedHashMap) {
LinkedHashMap<String, Object> castValue = (LinkedHashMap<String, Object>) value;
LinkedHashMap<ObjectWithTypeBooleans, ObjectWithTypeBooleans> castMap = new LinkedHashMap<>();
for (Map.Entry entry: castValue.entrySet()) {
for (Map.Entry entry : castValue.entrySet()) {
ObjectWithTypeBooleans entryKey = new ObjectWithTypeBooleans(entry.getKey());
ObjectWithTypeBooleans entryValue = new ObjectWithTypeBooleans(entry.getValue());
castMap.put(entryKey, entryValue);
@ -45,7 +46,7 @@ public class ObjectWithTypeBooleans {
this.isMap = true;
} else if (value instanceof ArrayList) {
ArrayList<ObjectWithTypeBooleans> castList = new ArrayList<>();
for (Object item: (ArrayList<Object>) value) {
for (Object item : (ArrayList<Object>) value) {
castList.add(new ObjectWithTypeBooleans(item));
}
this.value = castList;

View File

@ -35,7 +35,6 @@ import java.util.*;
import java.util.stream.Collectors;
import static org.openapitools.codegen.utils.StringUtils.getUniqueString;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class OpenAPINormalizer {
private OpenAPI openAPI;
@ -546,7 +545,7 @@ public class OpenAPINormalizer {
return;
}
for (Map.Entry<String, ApiResponse> entry : apiResponses.entrySet()) {
for (Map.Entry<String, ApiResponse> entry : apiResponses.entrySet()) {
normalizeResponse(entry.getValue());
}
}
@ -1013,7 +1012,6 @@ public class OpenAPINormalizer {
}
/**
* If the schema contains anyOf/oneOf and properties, remove oneOf/anyOf as these serve as rules to
* ensure inter-dependency between properties. It's a workaround as such validation is not supported at the moment.

View File

@ -6,7 +6,8 @@ import lombok.Setter;
import java.util.Optional;
import java.util.Set;
@Getter @Setter
@Getter
@Setter
public class SpecValidationException extends RuntimeException {
private Set<String> errors;
@ -100,8 +101,8 @@ public class SpecValidationException extends RuntimeException {
StringBuilder sb = new StringBuilder();
sb.append(System.lineSeparator())
.append("Errors: ")
.append(System.lineSeparator());
.append("Errors: ")
.append(System.lineSeparator());
Optional.ofNullable(errors).ifPresent(_errors -> {
for (String msg : errors) {

View File

@ -27,11 +27,12 @@ import java.util.StringJoiner;
/**
* Defines the template definition for a "supporting file", that is any file which is generic and not bound to
* api/model definitions and their relevant docs or tests.
*
* <p>
* Supporting files are generated once for an entire application while api/model bound definitions are generated multiple
* times according to their target use.
*/
@Getter public class SupportingFile extends TemplateDefinition {
@Getter
public class SupportingFile extends TemplateDefinition {
private boolean canOverwrite = true;
public SupportingFile(String templateFile, String destinationFilename) {

View File

@ -13,8 +13,14 @@ import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
@ -30,8 +36,8 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
/**
* Constructs a new instance of a {@link TemplateManager}
*
* @param options The {@link TemplateManagerOptions} for reading and writing templates
* @param engineAdapter The adaptor to underlying templating engine
* @param options The {@link TemplateManagerOptions} for reading and writing templates
* @param engineAdapter The adaptor to underlying templating engine
* @param templateLoaders Loaders which define where we look for templates
*/
public TemplateManager(
@ -87,7 +93,6 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
* Gets a normalized classpath resource location according to OS-specific file separator
*
* @param name The name of the resource file/directory to find
*
* @return A normalized string according to OS-specific file separator
*/
public static String getCPResourcePath(final String name) {
@ -152,8 +157,7 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
*
* @param data Input data
* @param template Input template location
* @param target The targeted file output location
*
* @param target The targeted file output location
* @return The actual file
*/
@Override

View File

@ -6,7 +6,8 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Getter public enum VendorExtension {
@Getter
public enum VendorExtension {
X_IMPLEMENTS("x-implements", ExtensionLevel.MODEL, "Ability to specify interfaces that model must implements", "empty array"),
X_SPRING_PAGINATED("x-spring-paginated", ExtensionLevel.OPERATION, "Add org.springframework.data.domain.Pageable to controller method. Can be used to handle page & size query parameters", "false"),

View File

@ -41,9 +41,9 @@ public class AuthParser {
String[] kvPair = part.split(":");
if (kvPair.length == 2) {
auths.add(new AuthorizationValue(
URLDecoder.decode(kvPair[0], StandardCharsets.UTF_8),
URLDecoder.decode(kvPair[1], StandardCharsets.UTF_8),
"header"
URLDecoder.decode(kvPair[0], StandardCharsets.UTF_8),
URLDecoder.decode(kvPair[1], StandardCharsets.UTF_8),
"header"
));
}
}
@ -59,7 +59,7 @@ public class AuthParser {
b.append(",");
}
b.append(URLEncoder.encode(v.getKeyName(), StandardCharsets.UTF_8))
.append(":").append(URLEncoder.encode(v.getValue(), StandardCharsets.UTF_8));
.append(":").append(URLEncoder.encode(v.getValue(), StandardCharsets.UTF_8));
}
return b.toString();
} else {

View File

@ -48,7 +48,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty;
/**
* A class which manages the contextual configuration for code generation.
* This includes configuring the generator, templating, and the workflow which orchestrates these.
*
* <p>
* This helper also enables the deserialization of {@link GeneratorSettings} via application-specific Jackson JSON usage
* (see {@link DynamicSettings}.
*/
@ -109,55 +109,55 @@ public class CodegenConfigurator {
if (workflowSettings.getGlobalProperties() != null) {
configurator.globalProperties.putAll(workflowSettings.getGlobalProperties());
}
if(generatorSettings.getInstantiationTypes() != null) {
if (generatorSettings.getInstantiationTypes() != null) {
configurator.instantiationTypes.putAll(generatorSettings.getInstantiationTypes());
}
if(generatorSettings.getTypeMappings() != null) {
if (generatorSettings.getTypeMappings() != null) {
configurator.typeMappings.putAll(generatorSettings.getTypeMappings());
}
if(generatorSettings.getAdditionalProperties() != null) {
if (generatorSettings.getAdditionalProperties() != null) {
configurator.additionalProperties.putAll(generatorSettings.getAdditionalProperties());
}
if(generatorSettings.getImportMappings() != null) {
if (generatorSettings.getImportMappings() != null) {
configurator.importMappings.putAll(generatorSettings.getImportMappings());
}
if(generatorSettings.getSchemaMappings() != null) {
if (generatorSettings.getSchemaMappings() != null) {
configurator.schemaMappings.putAll(generatorSettings.getSchemaMappings());
}
if(generatorSettings.getInlineSchemaNameMappings() != null) {
if (generatorSettings.getInlineSchemaNameMappings() != null) {
configurator.inlineSchemaNameMappings.putAll(generatorSettings.getInlineSchemaNameMappings());
}
if(generatorSettings.getInlineSchemaOptions() != null) {
if (generatorSettings.getInlineSchemaOptions() != null) {
configurator.inlineSchemaOptions.putAll(generatorSettings.getInlineSchemaOptions());
}
if(generatorSettings.getNameMappings() != null) {
if (generatorSettings.getNameMappings() != null) {
configurator.nameMappings.putAll(generatorSettings.getNameMappings());
}
if(generatorSettings.getParameterNameMappings() != null) {
if (generatorSettings.getParameterNameMappings() != null) {
configurator.parameterNameMappings.putAll(generatorSettings.getParameterNameMappings());
}
if(generatorSettings.getModelNameMappings() != null) {
if (generatorSettings.getModelNameMappings() != null) {
configurator.modelNameMappings.putAll(generatorSettings.getModelNameMappings());
}
if(generatorSettings.getEnumNameMappings() != null) {
if (generatorSettings.getEnumNameMappings() != null) {
configurator.enumNameMappings.putAll(generatorSettings.getEnumNameMappings());
}
if(generatorSettings.getOperationIdNameMappings() != null) {
if (generatorSettings.getOperationIdNameMappings() != null) {
configurator.operationIdNameMappings.putAll(generatorSettings.getOperationIdNameMappings());
}
if(generatorSettings.getOpenapiNormalizer() != null) {
if (generatorSettings.getOpenapiNormalizer() != null) {
configurator.openapiNormalizer.putAll(generatorSettings.getOpenapiNormalizer());
}
if(generatorSettings.getLanguageSpecificPrimitives() != null) {
if (generatorSettings.getLanguageSpecificPrimitives() != null) {
configurator.languageSpecificPrimitives.addAll(generatorSettings.getLanguageSpecificPrimitives());
}
if(generatorSettings.getOpenapiGeneratorIgnoreList() != null) {
if (generatorSettings.getOpenapiGeneratorIgnoreList() != null) {
configurator.openapiGeneratorIgnoreList.addAll(generatorSettings.getOpenapiGeneratorIgnoreList());
}
if(generatorSettings.getReservedWordsMappings() != null) {
if (generatorSettings.getReservedWordsMappings() != null) {
configurator.reservedWordsMappings.putAll(generatorSettings.getReservedWordsMappings());
}
if(generatorSettings.getServerVariables() != null) {
if (generatorSettings.getServerVariables() != null) {
configurator.serverVariables.putAll(generatorSettings.getServerVariables());
}
@ -700,12 +700,12 @@ public class CodegenConfigurator {
// Wrap the getUnusedSchemas() in try catch block so it catches the NPE
// when the input spec file is not correct
try{
try {
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification);
if (unusedModels != null) {
unusedModels.forEach(name -> warnings.add("Unused model: " + name));
}
} catch (Exception e){
} catch (Exception e) {
System.err.println("[error] There is an error with OpenAPI specification parsed from the input spec file: " + inputSpec);
System.err.println("[error] Please make sure the spec file has correct format and all required fields are populated with valid value.");
}
@ -808,6 +808,6 @@ public class CodegenConfigurator {
.generatorSettings(generatorSettings)
.userDefinedTemplates(userDefinedTemplates);
return input.openAPI((OpenAPI)context.getSpecDocument());
return input.openAPI((OpenAPI) context.getSpecDocument());
}
}

View File

@ -23,7 +23,7 @@ import java.util.stream.Collectors;
public class DynamicSettings {
/**
* -- GETTER --
* Gets all "custom" properties included in the config object.
* Gets all "custom" properties included in the config object.
*
* @return All user-specified custom properties.
*/
@ -96,9 +96,10 @@ public class DynamicSettings {
* <p>Constructor for DynamicSettings.</p>
*/
@JsonCreator
public DynamicSettings() { }
public DynamicSettings() {
}
private void excludeSettingsFromDynamicProperties(){
private void excludeSettingsFromDynamicProperties() {
Set<String> fieldNames = new HashSet<>();
for (Field field : GeneratorSettings.class.getDeclaredFields()) {
fieldNames.add(field.getName());

View File

@ -27,7 +27,7 @@ import java.util.Properties;
* GlobalSettings encapsulates SystemProperties, since the codegen mechanism heavily relies on a stable,
* non-changing System Property Basis. Using plain System.(get|set|clear)Property raises Race-Conditions in combination
* with Code, that uses System.setProperties (e.g. maven-surefire-plugin).
*
* <p>
* This provides a set of properties specific to the executing thread, such that the generator may not modify system properties
* consumed by other threads.
*

View File

@ -1,32 +1,24 @@
package org.openapitools.codegen.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.collect.ImmutableMap;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.ParseOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.collect.ImmutableMap;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.ParseOptions;
public class MergedSpecBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(MergedSpecBuilder.class);
@ -59,8 +51,8 @@ public class MergedSpecBuilder {
LOGGER.info("Reading spec: {}", specPath);
OpenAPI result = new OpenAPIParser()
.readLocation(specPath, new ArrayList<>(), options)
.getOpenAPI();
.readLocation(specPath, new ArrayList<>(), options)
.getOpenAPI();
if (openapiVersion == null) {
openapiVersion = result.getOpenapi();
@ -93,11 +85,11 @@ public class MergedSpecBuilder {
Map<String, Object> paths = new HashMap<>();
spec.put("paths", paths);
for(SpecWithPaths specWithPaths : allPaths) {
for (SpecWithPaths specWithPaths : allPaths) {
for (String path : specWithPaths.paths) {
String specRelatedPath = "./" + specWithPaths.specRelatedPath + "#/paths/" + path.replace("/", "~1");
paths.put(path, ImmutableMap.of(
"$ref", specRelatedPath
"$ref", specRelatedPath
));
}
}
@ -109,12 +101,12 @@ public class MergedSpecBuilder {
Map<String, Object> map = new HashMap<>();
map.put("openapi", openapiVersion);
map.put("info", ImmutableMap.of(
"title", "merged spec",
"description", "merged spec",
"version", "1.0.0"
"title", "merged spec",
"description", "merged spec",
"version", "1.0.0"
));
map.put("servers", Collections.singleton(
ImmutableMap.of("url", "http://localhost:8080")
ImmutableMap.of("url", "http://localhost:8080")
));
return map;
}
@ -123,9 +115,9 @@ public class MergedSpecBuilder {
Path rootDirectory = new File(inputSpecRootDirectory).toPath();
try (Stream<Path> pathStream = Files.walk(rootDirectory)) {
return pathStream
.filter(path -> !Files.isDirectory(path))
.map(path -> rootDirectory.relativize(path).toString())
.collect(Collectors.toList());
.filter(path -> !Files.isDirectory(path))
.map(path -> rootDirectory.relativize(path).toString())
.collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException("Exception while listing files in spec root directory: " + inputSpecRootDirectory, e);
}
@ -134,10 +126,12 @@ public class MergedSpecBuilder {
private void deleteMergedFileFromPreviousRun() {
try {
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".json"));
} catch (IOException e) { }
} catch (IOException e) {
}
try {
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".yaml"));
} catch (IOException e) { }
} catch (IOException e) {
}
}
private static class SpecWithPaths {

View File

@ -248,7 +248,7 @@ public class ExampleGenerator {
} else if (ModelUtils.isArraySchema(property)) {
Schema innerType = ModelUtils.getSchemaItems(property);
if (innerType != null) {
int arrayLength = null == property.getMaxItems() ? 2 : property.getMaxItems();
int arrayLength = null == property.getMaxItems() ? 2 : property.getMaxItems();
// avoid memory issues by limiting to max. 5 items
arrayLength = Math.min(arrayLength, 5);
Object[] objectProperties = new Object[arrayLength];
@ -398,10 +398,11 @@ public class ExampleGenerator {
/**
* Transverse and resolves all property examples for `allOf` composed schemas into `values` map object
* @param mediaType MIME type
* @param schema OAS schema
*
* @param mediaType MIME type
* @param schema OAS schema
* @param processedModels Set containing all processed models
* @param values Example value map
* @param values Example value map
*/
private void resolveAllOfSchemaProperties(String mediaType, Schema schema, Set<String> processedModels, Map<String, Object> values) {
List<Schema> interfaces = schema.getAllOf();

View File

@ -172,7 +172,7 @@ public class XmlExampleGenerator {
/**
* Get the example string value for the given schema.
*
* <p>
* If an example value was not provided in the specification, a default will be generated.
*
* @param schema Schema to get example string for

View File

@ -2,8 +2,8 @@ package org.openapitools.codegen.exceptions;
public class ProtoBufIndexComputationException extends Exception {
public ProtoBufIndexComputationException(String reason) {
super(reason);
}
public ProtoBufIndexComputationException(String reason) {
super(reason);
}
}

View File

@ -25,7 +25,10 @@ import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
@ -113,15 +116,15 @@ public class CodegenIgnoreProcessor {
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
while ((line = reader.readLine()) != null) {
if(
if (
//: A blank line matches no files, so it can serve as a separator for readability.
line.length() == 0
line.length() == 0
) continue;
Rule rule = Rule.create(line);
// rule could be null here if it's a COMMENT, for example
if(rule != null) {
if (rule != null) {
if (Boolean.TRUE.equals(rule.getNegated())) {
inclusionRules.add(rule);
} else {
@ -140,12 +143,12 @@ public class CodegenIgnoreProcessor {
* @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed).
*/
public boolean allowsFile(final File targetFile) {
if(this.ignoreFile == null) return true;
if (this.ignoreFile == null) return true;
File file = new File(this.ignoreFile.getAbsoluteFile().getParentFile().toURI().relativize(targetFile.toURI()).getPath());
boolean directoryExcluded = false;
boolean exclude = false;
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
if (exclusionRules.size() == 0 && inclusionRules.size() == 0) {
return true;
}
@ -154,12 +157,12 @@ public class CodegenIgnoreProcessor {
Rule current = exclusionRules.get(i);
Rule.Operation op = current.evaluate(file.getPath());
switch (op){
switch (op) {
case EXCLUDE:
exclude = true;
// Include rule can't override rules that exclude a file by some parent directory.
if(current instanceof DirectoryRule) {
if (current instanceof DirectoryRule) {
directoryExcluded = true;
}
break;
@ -174,7 +177,7 @@ public class CodegenIgnoreProcessor {
}
}
if(exclude) {
if (exclude) {
// Only need to process inclusion rules if we've been excluded
for (int i = 0; exclude && i < inclusionRules.size(); i++) {
Rule current = inclusionRules.get(i);
@ -182,8 +185,8 @@ public class CodegenIgnoreProcessor {
// At this point exclude=true means the file should be ignored.
// op == INCLUDE means we have to flip that flag.
if(op.equals(Rule.Operation.INCLUDE)) {
if(current instanceof DirectoryRule && directoryExcluded) {
if (op.equals(Rule.Operation.INCLUDE)) {
if (current instanceof DirectoryRule && directoryExcluded) {
// e.g
// baz/
// !foo/bar/baz/
@ -216,7 +219,7 @@ public class CodegenIgnoreProcessor {
/**
* Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent
* files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
*
* <p>
* NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
*
* @return A {@link Collections#unmodifiableList(List)} of rules which define exclusions by patterns in the ignore file.

View File

@ -32,7 +32,7 @@ public class DirectoryRule extends FileRule {
StringBuilder sb = new StringBuilder();
sb.append("glob:");
sb.append(pattern);
if(!pattern.endsWith("/")) sb.append("/");
if (!pattern.endsWith("/")) sb.append("/");
directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
sb.append("**");
contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());

View File

@ -33,5 +33,7 @@ public class EverythingRule extends Rule {
}
@Override
protected Operation getExcludeOperation(){ return Operation.EXCLUDE_AND_TERMINATE; }
protected Operation getExcludeOperation() {
return Operation.EXCLUDE_AND_TERMINATE;
}
}

View File

@ -27,7 +27,7 @@ public class FileRule extends Rule {
FileRule(List<Part> syntax, String definition) {
super(syntax, definition);
matcher = FileSystems.getDefault().getPathMatcher("glob:"+this.getPattern());
matcher = FileSystems.getDefault().getPathMatcher("glob:" + this.getPattern());
}
@Override

View File

@ -23,7 +23,8 @@ import java.util.ArrayList;
import java.util.List;
public class IgnoreLineParser {
@Getter enum Token {
@Getter
enum Token {
MATCH_ALL("**"),
MATCH_ANY("*"),
ESCAPED_EXCLAMATION("\\!"),
@ -84,8 +85,8 @@ public class IgnoreLineParser {
if (Token.MATCH_ANY.pattern.equals(next)) {
// peek ahead for invalid pattern. Slightly inefficient, but acceptable.
if ((i+2 < totalLength - 1) &&
String.valueOf(characters[i+2]).equals(Token.MATCH_ANY.pattern)) {
if ((i + 2 < totalLength - 1) &&
String.valueOf(characters[i + 2]).equals(Token.MATCH_ANY.pattern)) {
// It doesn't matter where we are in the pattern, *** is invalid.
throw new ParserException("The pattern *** is invalid.");
}
@ -129,7 +130,7 @@ public class IgnoreLineParser {
}
parts.add(new Part(Token.PATH_DELIM));
if(Token.PATH_DELIM.pattern.equals(next)) {
if (Token.PATH_DELIM.pattern.equals(next)) {
// ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will result in //
i++;
}

View File

@ -21,7 +21,8 @@ import lombok.Getter;
import java.util.List;
@Getter public class InvalidRule extends Rule {
@Getter
public class InvalidRule extends Rule {
private final String reason;
InvalidRule(List<Part> syntax, String definition, String reason) {

View File

@ -19,7 +19,8 @@ package org.openapitools.codegen.ignore.rules;
import lombok.Getter;
@Getter class Part {
@Getter
class Part {
private final IgnoreLineParser.Token token;
private final String value;

View File

@ -36,12 +36,12 @@ public class RootedFileRule extends Rule {
definedExtension = getExtensionPart(definition, separatorIndex);
}
private String getFilenamePart(final String input, int stopIndex){
private String getFilenamePart(final String input, int stopIndex) {
return input.substring('/' == input.charAt(0) ? 1 : 0, stopIndex > 0 ? stopIndex : input.length());
}
private String getExtensionPart(final String input, int stopIndex) {
return input.substring(stopIndex > 0 ? stopIndex+1: input.length());
return input.substring(stopIndex > 0 ? stopIndex + 1 : input.length());
}
@Override
@ -51,13 +51,13 @@ public class RootedFileRule extends Rule {
// relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore.
boolean isSingleFile = relativePath.lastIndexOf("/") <= 0;
if(isSingleFile) {
if (isSingleFile) {
int separatorIndex = relativePath.lastIndexOf(".");
final String filename = getFilenamePart(relativePath, separatorIndex);
final String extension = getExtensionPart(relativePath, separatorIndex);
boolean extensionMatches = definedExtension.equals(extension) || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY.getPattern());
if(extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) {
if (extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) {
// TODO: Evaluate any other escape requirements here.
Pattern regex = Pattern.compile(
definedFilename

View File

@ -38,7 +38,7 @@ public abstract class Rule {
public abstract Boolean matches(String relativePath);
protected String getPattern() {
if(syntax == null) return this.definition;
if (syntax == null) return this.definition;
StringBuilder sb = new StringBuilder();
for (Part current : syntax) {
@ -75,7 +75,7 @@ public abstract class Rule {
public Operation evaluate(String relativePath) {
if (Boolean.TRUE.equals(matches(relativePath))) {
if(Boolean.TRUE.equals(this.getNegated())) {
if (Boolean.TRUE.equals(this.getNegated())) {
return this.getIncludeOperation();
}
return this.getExcludeOperation();
@ -83,8 +83,13 @@ public abstract class Rule {
return Operation.NOOP;
}
protected Operation getIncludeOperation(){ return Operation.INCLUDE; }
protected Operation getExcludeOperation(){ return Operation.EXCLUDE; }
protected Operation getIncludeOperation() {
return Operation.INCLUDE;
}
protected Operation getExcludeOperation() {
return Operation.EXCLUDE;
}
public static Rule create(String definition) {
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore

View File

@ -27,12 +27,7 @@ import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.ClientModificationFeature;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
import org.openapitools.codegen.meta.features.SchemaSupportFeature;
import org.openapitools.codegen.meta.features.SecurityFeature;
import org.openapitools.codegen.meta.features.WireFormatFeature;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationMap;

View File

@ -18,10 +18,9 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Lambda;
import com.samskivert.mustache.Template;
import io.swagger.v3.oas.models.media.Schema;
import lombok.Getter;
import lombok.Setter;
@ -504,7 +503,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
}
}
/** If the value can be parsed as a double, returns the value, otherwise returns null */
/**
* If the value can be parsed as a double, returns the value, otherwise returns null
*/
public static Double asDouble(String strNum) {
if (strNum == null) {
return null;
@ -516,7 +517,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
}
}
/** If the value can be parsed as an integer, returns the value, otherwise returns null */
/**
* If the value can be parsed as an integer, returns the value, otherwise returns null
*/
public static Integer asInteger(String strNum) {
if (strNum == null) {
return null;
@ -751,7 +754,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
property.name = patchPropertyName(model, property.name);
String[] nestedTypes = { "List", "Collection", "ICollection", "Dictionary" };
String[] nestedTypes = {"List", "Collection", "ICollection", "Dictionary"};
Arrays.stream(nestedTypes).forEach(nestedType -> {
// fix incorrect data types for maps of maps
@ -835,6 +838,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
httpStatusesWithReturn.add(status);
}
}
private HashMap<String, String> duplicateOf = new HashMap<String, String>();
@Override
@ -876,7 +880,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
}
String code = response.code.toLowerCase(Locale.ROOT);
switch(code) {
switch (code) {
case "default":
case "0":
postProcessResponseCode(response, "Default", httpStatusesWithReturn);
@ -1242,7 +1246,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
}
protected void processOperation(CodegenOperation operation) {
String[] nestedTypes = { "List", "Collection", "ICollection", "Dictionary" };
String[] nestedTypes = {"List", "Collection", "ICollection", "Dictionary"};
Arrays.stream(nestedTypes).forEach(nestedType -> {
if (operation.returnProperty != null && operation.returnType.contains("<" + nestedType + ">") && operation.returnProperty.items != null) {
@ -1707,8 +1711,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
* @param name The original name
* @return The adjusted name
*/
private String adjustNamingStyle(String name)
{
private String adjustNamingStyle(String name) {
switch (getEnumPropertyNaming()) {
case camelCase:
// NOTE: Removes hyphens and underscores
@ -1765,7 +1768,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
return (this.getValueTypes().contains(var.dataType) || var.isEnum);
}
protected boolean useNet60OrLater() { return false; }
protected boolean useNet60OrLater() {
return false;
}
protected boolean useDateOnly() {
return useNet60OrLater() && !useDateTimeForDateFlag;
@ -1915,7 +1920,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
// only process files with .cs extension
if ("cs".equals(FilenameUtils.getExtension(file.toString()))) {
this.executePostProcessor(new String[] {csharpPostProcessFile, file.toString()});
this.executePostProcessor(new String[]{csharpPostProcessFile, file.toString()});
}
}
@ -1936,12 +1941,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
Pattern hasModifiers = Pattern.compile(".*/[gmiyuvsdlnx]+$");
int end = hasModifiers.matcher(pattern).find()
? pattern.lastIndexOf('/')
: pattern.length() - 1;
? pattern.lastIndexOf('/')
: pattern.length() - 1;
int start = pattern.startsWith("/")
? 1
: 0;
? 1
: 0;
Map<Character, String> optionsMap = new HashMap<Character, String>();
optionsMap.put('i', "IgnoreCase");
@ -1956,7 +1961,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
for (char c : pattern.substring(end).toCharArray()) {
if (optionsMap.containsKey(c)) {
modifiers.add(optionsMap.get(c));
} else if (c == 'l'){
} else if (c == 'l') {
modifiers.remove("CultureInvariant");
} else {
vendorExtensions.put("x-modifier-" + c, c);

View File

@ -19,15 +19,14 @@ package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.ServerVariables;
import io.swagger.v3.oas.models.servers.ServerVariable;
import org.openapitools.codegen.*;
import io.swagger.v3.oas.models.servers.ServerVariables;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.templating.mustache.IndentedLambda;
@ -38,11 +37,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.*;
abstract public class AbstractCppCodegen extends DefaultCodegen implements CodegenConfig {
private final Logger LOGGER = LoggerFactory.getLogger(AbstractCppCodegen.class);
@ -348,7 +343,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
}
// only process files with cpp extension
if ("cpp".equals(FilenameUtils.getExtension(file.toString())) || "h".equals(FilenameUtils.getExtension(file.toString()))) {
this.executePostProcessor(new String[] {cppPostProcessFile, file.toString()});
this.executePostProcessor(new String[]{cppPostProcessFile, file.toString()});
}
}

View File

@ -806,7 +806,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
// process all files with dart extension
if ("dart".equals(FilenameUtils.getExtension(file.toString()))) {
// currently supported is "dartfmt -w" and "dart format"
this.executePostProcessor(new String[] {dartPostProcessFile, file.toString()});
this.executePostProcessor(new String[]{dartPostProcessFile, file.toString()});
}
}

Some files were not shown because too many files have changed in this diff Show More