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; package org.openapitools.codegen;
public class Constants { public class Constants {
private Constants(){ } private Constants() {
}
public static final String CLI_NAME = "openapi-generator-cli"; public static final String CLI_NAME = "openapi-generator-cli";
public static final String GIT_REPO = "https://github.com/openapitools/openapi-generator"; public static final String GIT_REPO = "https://github.com/openapitools/openapi-generator";

View File

@ -20,11 +20,7 @@ package org.openapitools.codegen.cmd;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption; import org.openapitools.codegen.*;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
import org.openapitools.codegen.GeneratorNotFoundException;
import org.openapitools.codegen.VendorExtension;
import org.openapitools.codegen.meta.FeatureSet; import org.openapitools.codegen.meta.FeatureSet;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,10 +33,10 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; 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.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") @Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp extends OpenApiGeneratorCommand { 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_TEXT = "text";
private static final String FORMAT_MARKDOWN = "markdown"; private static final String FORMAT_MARKDOWN = "markdown";
private static final String FORMAT_YAMLSAMPLE = "yamlsample"; 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", @Option(name = {"-g",
"--generator-name"}, title = "generator name", description = "generator to get config help for") "--generator-name"}, title = "generator name", description = "generator to get config help for")
@ -359,17 +355,17 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
sb.append("| Property | Value | Notes |").append(newline); sb.append("| Property | Value | Notes |").append(newline);
sb.append("| -------- | ----- | ----- |").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 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 stability | " + config.getGeneratorMetadata().getStability() + " | |").append(newline);
sb.append("| generator type | "+config.getTag()+" | |").append(newline); sb.append("| generator type | " + config.getTag() + " | |").append(newline);
if (config.generatorLanguage() != null) { 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) { 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("| generator default templating engine | " + config.defaultTemplatingEngine() + " | |").append(newline);
sb.append("| helpTxt | "+config.getHelp()+" | |").append(newline); sb.append("| helpTxt | " + config.getHelp() + " | |").append(newline);
sb.append(newline); sb.append(newline);
} }

View File

@ -17,18 +17,10 @@
package org.openapitools.codegen.cmd; 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.classic.LoggerContext;
import ch.qos.logback.core.spi.FilterAttachable; import ch.qos.logback.core.spi.FilterAttachable;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; 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.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*; import org.openapitools.codegen.*;
import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.config.CodegenConfigurator;
@ -36,6 +28,14 @@ import org.openapitools.codegen.config.MergedSpecBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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"}) @SuppressWarnings({"java:S106"})
@Command(name = "generate", description = "Generate code with the specified generator.") @Command(name = "generate", description = "Generate code with the specified generator.")
public class Generate extends OpenApiGeneratorCommand { public class Generate extends OpenApiGeneratorCommand {
@ -101,7 +101,7 @@ public class Generate extends OpenApiGeneratorCommand {
+ "overwritten during the generation.") + "overwritten during the generation.")
private Boolean skipOverwrite; 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).") description = "Try things out and report on potential changes (without actually making changes).")
private Boolean isDryRun; private Boolean isDryRun;

View File

@ -18,7 +18,6 @@ package org.openapitools.codegen.cmd;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.*; 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.deser.std.DelegatingDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.TokenBuffer; import com.fasterxml.jackson.databind.util.TokenBuffer;
import io.airlift.airline.Arguments; import io.airlift.airline.Arguments;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;

View File

@ -1,10 +1,8 @@
package org.openapitools.codegen.cmd; package org.openapitools.codegen.cmd;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader; import org.openapitools.codegen.CodegenConfigLoader;
@ -20,18 +18,18 @@ import java.util.stream.Collectors;
@Command(name = "list", description = "Lists the available generators") @Command(name = "list", description = "Lists the available generators")
public class ListGenerators extends OpenApiGeneratorCommand { 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; 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; private Boolean docusaurus = false;
@Option(name = {"--github-nested-index" }, description = "format for github index at docs/generators/README.md", hidden = true) @Option(name = {"--github-nested-index"}, description = "format for github index at docs/generators/README.md", hidden = true)
private Boolean githubNestedIndex = false; 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.", 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"; private String include = "stable,beta,experimental";
@Override @Override
@ -88,7 +86,7 @@ public class ListGenerators extends OpenApiGeneratorCommand {
.sorted(Comparator.comparing(CodegenConfig::getName)) .sorted(Comparator.comparing(CodegenConfig::getName))
.collect(Collectors.toList()); .collect(Collectors.toList());
if(!list.isEmpty()) { if (!list.isEmpty()) {
if (docusaurus || githubNestedIndex) { if (docusaurus || githubNestedIndex) {
sb.append("## ").append(typeName).append(" generators"); sb.append("## ").append(typeName).append(" generators");
} else { } else {

View File

@ -17,9 +17,7 @@
package org.openapitools.codegen.cmd; package org.openapitools.codegen.cmd;
import static ch.lambdaj.collection.LambdaCollections.with; import ch.lambdaj.function.convert.Converter;
import static com.google.common.base.Joiner.on;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -31,9 +29,9 @@ import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.TemplateManager; import org.openapitools.codegen.TemplateManager;
import org.openapitools.codegen.api.TemplatePathLocator; import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
import org.openapitools.codegen.templating.MustacheEngineAdapter; import org.openapitools.codegen.templating.MustacheEngineAdapter;
import org.openapitools.codegen.templating.TemplateManagerOptions; import org.openapitools.codegen.templating.TemplateManagerOptions;
import org.openapitools.codegen.templating.CommonTemplateContentLocator;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -43,7 +41,8 @@ import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import java.util.Map; 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 * User: lanwen Date: 24.03.15 Time: 20:22
@ -99,8 +98,8 @@ 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/generatorClassTest.mustache", on(File.separator).join("src/test/kotlin", asPath(targetPackage)), mainClass.concat("Test.kt")),
new SupportingFile("kotlin/README.mustache", "", "README.md"), new SupportingFile("kotlin/README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.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("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("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("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()))
: ImmutableList.of( : ImmutableList.of(
@ -108,8 +107,8 @@ public class Meta extends OpenApiGeneratorCommand {
new SupportingFile("generatorClass.mustache", on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")), 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("generatorClassTest.mustache", on(File.separator).join("src/test/java", asPath(targetPackage)), mainClass.concat("Test.java")),
new SupportingFile("README.mustache", "", "README.md"), new SupportingFile("README.mustache", "", "README.md"),
new SupportingFile("api.template", "src/main/resources" + File.separator + name,"api.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("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("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("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName()));
@ -148,7 +147,7 @@ public class Meta extends OpenApiGeneratorCommand {
TemplateManager templateProcessor = new TemplateManager( TemplateManager templateProcessor = new TemplateManager(
new TemplateManagerOptions(false, false), new TemplateManagerOptions(false, false),
new MustacheEngineAdapter(), new MustacheEngineAdapter(),
new TemplatePathLocator[]{ new CommonTemplateContentLocator("codegen") } new TemplatePathLocator[]{new CommonTemplateContentLocator("codegen")}
); );
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.getTemplateFile()).getPath()); 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.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;
import io.swagger.parser.OpenAPIParser; import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue; import io.swagger.v3.parser.core.models.AuthorizationValue;
@ -35,7 +34,7 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@SuppressWarnings({"unused","java:S106"}) @SuppressWarnings({"unused", "java:S106"})
@Command(name = "validate", description = "Validate specification") @Command(name = "validate", description = "Validate specification")
public class Validate extends OpenApiGeneratorCommand { 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)") description = "location of the OpenAPI spec, as URL or file (required)")
private String spec; private String spec;
@Option(name = { "--recommend"}, title = "recommend spec improvements") @Option(name = {"--recommend"}, title = "recommend spec improvements")
private Boolean recommend; private Boolean recommend;
@Option( @Option(

View File

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

View File

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

View File

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

View File

@ -17,8 +17,8 @@
package org.openapitools.codegen.cmd.utils; package org.openapitools.codegen.cmd.utils;
import org.openapitools.codegen.utils.OptionUtils;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.utils.OptionUtils;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.util.Collections; 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. * Gets all possible template paths for a given location.
* *
* @param location The full location of the template. * @param location The full location of the template.
*
* @return A new array of locations, modified according to the extensions or other adapter rules. * @return A new array of locations, modified according to the extensions or other adapter rules.
*/ */
protected String[] getModifiedFileLocation(String location) { 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. * Returns the path without an extension for an input location.
* *
* @param location The location of the file, with original file extension intact. * @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) * @return The full path, without extension (e.g. /path/to/file.txt => /path/to/file)
*/ */
private String getPathWithoutExtension(String location) { private String getPathWithoutExtension(String location) {

View File

@ -94,7 +94,9 @@ public class TemplateDefinition {
this.templateType = templateType; this.templateType = templateType;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -106,13 +108,17 @@ public class TemplateDefinition {
getTemplateType() == that.getTemplateType(); getTemplateType() == that.getTemplateType();
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType()); return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType());
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public String toString() { public String toString() {
return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]") return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]")

View File

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

View File

@ -15,7 +15,6 @@ public interface TemplateProcessor {
* @param data Input data * @param data Input data
* @param template Input template location * @param template Input template location
* @param target The targeted file output location * @param target The targeted file output location
*
* @return The actual file * @return The actual file
* @throws IOException If file cannot be written. * @throws IOException If file cannot be written.
*/ */
@ -53,5 +52,6 @@ public interface TemplateProcessor {
* @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 * @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 * 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. * @return True if the file should be compiled by this adapter, else false.
*/ */
default boolean handlesFile(String filename) { default boolean handlesFile(String filename) {

View File

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

View File

@ -340,7 +340,7 @@ public class WorkflowSettings {
* @return a reference to this Builder * @return a reference to this Builder
*/ */
public Builder withOutputDir(String outputDir) { public Builder withOutputDir(String outputDir) {
if (outputDir != null ) { if (outputDir != null) {
this.outputDir = Paths.get(outputDir).toAbsolutePath().toString(); this.outputDir = Paths.get(outputDir).toAbsolutePath().toString();
} else { } else {
this.outputDir = DEFAULT_OUTPUT_DIR; this.outputDir = DEFAULT_OUTPUT_DIR;

View File

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

View File

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

View File

@ -23,7 +23,7 @@ import org.openapitools.codegen.meta.features.annotations.ToolingExtension;
/** /**
* Defines common data types supported by a generator. * Defines common data types supported by a generator.
* Some of these features are defined in specs, and some are specific to the tool. * 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 * 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 * 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}). * explicitly mentioned by the specification(s) but differs enough across languages that it warrants a special callout (see {@link DataTypeFeature#ArrayOfModel}).

View File

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

View File

@ -54,11 +54,11 @@ public enum SchemaSupportFeature {
* *
* <p> * <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. * 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 * 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 * implementation of such a type is easily represented dynamically (a JSON object), but requires explicit language support and
* potentially a custom implementation (typed instances). * 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 * 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". * on type determination to the consumer. This does *NOT* suggest generated code implements a "Union Type".
* </p> * </p>

View File

@ -4,9 +4,9 @@ public enum AnnotationType {
OAS2, OAS3, ToolingExtension; OAS2, OAS3, ToolingExtension;
public static AnnotationType fromAnnotation(Class<?> input) { public static AnnotationType fromAnnotation(Class<?> input) {
if(input == OAS2.class) return AnnotationType.OAS2; if (input == OAS2.class) return AnnotationType.OAS2;
if(input == OAS3.class) return AnnotationType.OAS3; if (input == OAS3.class) return AnnotationType.OAS3;
if(input == ToolingExtension.class) return AnnotationType.ToolingExtension; if (input == ToolingExtension.class) return AnnotationType.ToolingExtension;
return null; 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). * 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. * @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results. * @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/ */
@Override @Override

View File

@ -48,19 +48,18 @@ public abstract class Validated {
* *
* @param rule The rule which was evaluated. * @param rule The rule which was evaluated.
* @param message The message to display to a user. * @param message The message to display to a user.
*
* @return A {@link Validated} instance representing an invalid state according to the rule. * @return A {@link Validated} instance representing an invalid state according to the rule.
*/ */
public static Validated invalid(ValidationRule rule, String message) { public static Validated invalid(ValidationRule rule, String message) {
return new Invalid(rule, message); return new Invalid(rule, message);
} }
/** /**
* Creates an instance of an {@link Invalid} validation state. * 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 message The message to display to a user.
* @param details Additional contextual details related to the invalid state. * @param details Additional contextual details related to the invalid state.
*
* @return A {@link Validated} instance representing an invalid state according to the rule. * @return A {@link Validated} instance representing an invalid state according to the rule.
*/ */
public static Validated invalid(ValidationRule rule, String message, String details) { 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. * Creates an instance of an {@link Valid} validation state.
* *
* @param rule The rule which was evaluated. * @param rule The rule which was evaluated.
*
* @return A {@link Validated} instance representing a valid state according to the rule. * @return A {@link Validated} instance representing a valid state according to the rule.
*/ */
public static Validated valid(ValidationRule rule) { public static Validated valid(ValidationRule rule) {

View File

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

View File

@ -57,7 +57,6 @@ public class ValidationRule {
* Evaluate an instance of an object against this rule. * Evaluate an instance of an object against this rule.
* *
* @param input The instance to be evaluated. * @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>. * @return <code>true</code> if the object state is valid according to this rule, otherwise <code>false</code>.
*/ */
public Result evaluate(Object input) { public Result evaluate(Object input) {
@ -90,7 +89,7 @@ public class ValidationRule {
* @return An "empty" rule. * @return An "empty" rule.
*/ */
static ValidationRule empty() { 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());
} }
/** /**
@ -102,7 +101,6 @@ public class ValidationRule {
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>, * @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. * the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated. * @param <T> The type of the object being evaluated.
*
* @return A new instance of a {@link ValidationRule} * @return A new instance of a {@link ValidationRule}
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -117,7 +115,6 @@ public class ValidationRule {
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>, * @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. * the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated. * @param <T> The type of the object being evaluated.
*
* @return A new instance of a {@link ValidationRule} * @return A new instance of a {@link ValidationRule}
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -133,7 +130,6 @@ public class ValidationRule {
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>, * @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. * the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated. * @param <T> The type of the object being evaluated.
*
* @return A new instance of a {@link ValidationRule} * @return A new instance of a {@link ValidationRule}
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -164,17 +160,24 @@ public class ValidationRule {
} }
public abstract boolean passed(); public abstract boolean passed();
public final boolean failed() { return !passed(); }
public final boolean failed() {
return !passed();
}
public Throwable getThrowable() { public Throwable getThrowable() {
return throwable; 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 final class Pass extends Result {
public static Result empty() { return new Pass(); } public static Result empty() {
return new Pass();
}
public Pass() { public Pass() {
super(); super();
@ -192,7 +195,9 @@ public class ValidationRule {
} }
public static final class Fail extends Result { public static final class Fail extends Result {
public static Result empty() { return new Fail(); } public static Result empty() {
return new Fail();
}
public Fail() { public Fail() {
super(); 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). * 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. * @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results. * @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/ */
ValidationResult validate(TInput input); ValidationResult validate(TInput input);

View File

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

View File

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

View File

@ -18,17 +18,18 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test; 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 { public class ValidatedTest {
@Test @Test
public void isValidTrueForValidType(){ public void isValidTrueForValidType() {
boolean isValid = Validated.valid(ValidationRule.empty()).isValid(); boolean isValid = Validated.valid(ValidationRule.empty()).isValid();
assertTrue(isValid); assertTrue(isValid);
} }
@Test @Test
public void isValidFalseForInvalidType(){ public void isValidFalseForInvalidType() {
boolean isValid = Validated.invalid(ValidationRule.empty(), "test").isValid(); boolean isValid = Validated.invalid(ValidationRule.empty(), "test").isValid();
assertFalse(isValid); assertFalse(isValid);
} }

View File

@ -18,7 +18,8 @@ package org.openapitools.codegen.validation;
import org.testng.annotations.Test; 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 { public class ValidationRuleTest {
static class Sample { static class Sample {
@ -43,7 +44,7 @@ public class ValidationRuleTest {
} }
@Test @Test
public void createMethodUsingMethodReference(){ public void createMethodUsingMethodReference() {
Sample nil = new Sample(null); Sample nil = new Sample(null);
Sample six = new Sample("123456"); Sample six = new Sample("123456");
Sample seven = new Sample("1234567"); Sample seven = new Sample("1234567");
@ -56,11 +57,11 @@ public class ValidationRuleTest {
} }
@Test @Test
public void createMethodUsingLambda(){ public void createMethodUsingLambda() {
Sample nil = new Sample(null); Sample nil = new Sample(null);
Sample lowercase = new Sample("jim"); Sample lowercase = new Sample("jim");
Sample titlecase = 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(nil).passed());
assertFalse(result.evaluate(lowercase).passed()); assertFalse(result.evaluate(lowercase).passed());
assertTrue(result.evaluate(titlecase).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.FileUtils;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException; 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.MavenProject;
import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.project.MavenProjectHelper;
import org.openapitools.codegen.*; import org.openapitools.codegen.*;
@ -49,7 +51,10 @@ import org.sonatype.plexus.build.incremental.DefaultBuildContext;
import java.io.File; import java.io.File;
import java.io.IOException; 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.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.text.MessageFormat; 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) * 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; private String engine;
/** /**
@ -572,7 +577,7 @@ public class CodeGenMojo extends AbstractMojo {
return; return;
} }
if (buildContext != null && inputSpec != null ) { if (buildContext != null && inputSpec != null) {
if (buildContext.isIncremental() && if (buildContext.isIncremental() &&
inputSpecFile.exists() && inputSpecFile.exists() &&
!buildContext.hasDelta(inputSpecFile)) { !buildContext.hasDelta(inputSpecFile)) {
@ -1014,6 +1019,7 @@ public class CodeGenMojo extends AbstractMojo {
/** /**
* Try to parse inputSpec setting string into URL * Try to parse inputSpec setting string into URL
*
* @return A valid URL or null if inputSpec is not a valid URL * @return A valid URL or null if inputSpec is not a valid URL
*/ */
private URL inputSpecRemoteUrl() { private URL inputSpecRemoteUrl() {
@ -1026,6 +1032,7 @@ public class CodeGenMojo extends AbstractMojo {
/** /**
* Get specification hash file * Get specification hash file
*
* @param inputSpecFile - Openapi specification input file to calculate its hash. * @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 * @return a file with previously calculated hash

View File

@ -156,7 +156,7 @@ public class CodeGenMojoTest extends BaseTestCase {
); );
/* Remove the generated source */ /* Remove the generated source */
try(Stream<Path> files = Files.walk(generatedDir.resolve("src"))) { try (Stream<Path> files = Files.walk(generatedDir.resolve("src"))) {
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
} }
@ -242,7 +242,7 @@ public class CodeGenMojoTest extends BaseTestCase {
var currentHash = Files.readString(hashFile); // read hash var currentHash = Files.readString(hashFile); // read hash
FileUtils.deleteDirectory(generatedDir.resolve("src").toFile()); // Remove the generated source FileUtils.deleteDirectory(generatedDir.resolve("src").toFile()); // Remove the generated source
Files.writeString( // change schema definition in external file 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 // WHEN

View File

@ -20,6 +20,6 @@ import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
public class CommonMavenProjectStub extends MavenProjectStub { public class CommonMavenProjectStub extends MavenProjectStub {
public CommonMavenProjectStub() { 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; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication @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 { public class OpenAPI2SpringBoot implements CommandLineRunner {
@Override @Override

View File

@ -17,10 +17,9 @@
package org.openapitools.codegen.online.api; package org.openapitools.codegen.online.api;
import java.io.IOException;
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiOriginFilter implements javax.servlet.Filter { public class ApiOriginFilter implements javax.servlet.Filter {

View File

@ -42,9 +42,9 @@ import java.util.Map;
public interface GenApi { public interface GenApi {
GenApiDelegate getDelegate(); 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 = { @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", @RequestMapping(value = "/gen/clients",
method = RequestMethod.GET) method = RequestMethod.GET)
default ResponseEntity<List<String>> clientOptions() { 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 = { @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}", @RequestMapping(value = "/gen/download/{fileId}",
produces = { "application/octet-stream" }, produces = {"application/octet-stream"},
method = RequestMethod.GET) 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); 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 = { @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}", @RequestMapping(value = "/gen/clients/{language}",
method = RequestMethod.POST) 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); 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 = { @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}", @RequestMapping(value = "/gen/servers/{framework}",
method = RequestMethod.POST) 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); 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 = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") }) @ApiResponse(code = 200, message = "successful operation")})
@RequestMapping(value = "/gen/clients/{language}", @RequestMapping(value = "/gen/clients/{language}",
produces = { "application/json" }, produces = {"application/json"},
method = RequestMethod.GET) 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); 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 = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") }) @ApiResponse(code = 200, message = "successful operation")})
@RequestMapping(value = "/gen/servers/{framework}", @RequestMapping(value = "/gen/servers/{framework}",
produces = { "application/json" }, produces = {"application/json"},
method = RequestMethod.GET) 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); 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 = { @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", @RequestMapping(value = "/gen/servers",
method = RequestMethod.GET) method = RequestMethod.GET)
default ResponseEntity<List<String>> serverOptions() { 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. * @return A {@link ResponseEntity} listing options for the target client generator.
* @see GenApi#clientOptions
*/ */
default ResponseEntity<List<String>> clientOptions() { default ResponseEntity<List<String>> clientOptions() {
getRequest().ifPresent(request -> { getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "\"\""); ApiUtil.setExampleResponse(request, "*/*", "\"\"");
break; break;
@ -60,8 +60,8 @@ public interface GenApiDelegate {
/** /**
* @param fileId The unique id of the file, provided in a {@link ResponseCode} response. * @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}. * @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); return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
@ -71,13 +71,13 @@ public interface GenApiDelegate {
/** /**
* @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. * @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. * @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, default ResponseEntity<ResponseCode> generateClient(String language,
GeneratorInput generatorInput) { GeneratorInput generatorInput) {
getRequest().ifPresent(request -> { getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { 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\"}"); ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
break; break;
@ -91,13 +91,13 @@ 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. * @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. * @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, default ResponseEntity<ResponseCode> generateServerForLanguage(String framework,
GeneratorInput generatorInput) { GeneratorInput generatorInput) {
getRequest().ifPresent(request -> { getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { 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\"}"); ApiUtil.setExampleResponse(request, "*/*", "{ \"code\" : \"d40029be-eda6-4d62-b1ef-d05e2e91a72a\", \"link\" : \"http://localhost:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a\"}");
break; break;
@ -110,8 +110,8 @@ public interface GenApiDelegate {
/** /**
* @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).
* @see GenApi#getClientOptions
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by language (generator name). * @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); return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
@ -120,21 +120,21 @@ 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).
* @see GenApi#getServerOptions
* @return A {@link ResponseEntity} of {@link CliOption}, grouped by framework (generator name). * @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); return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
} }
/** /**
* @see GenApi#serverOptions
* @return A {@link ResponseEntity} listing options for the target server generator. * @return A {@link ResponseEntity} listing options for the target server generator.
* @see GenApi#serverOptions
*/ */
default ResponseEntity<List<String>> serverOptions() { default ResponseEntity<List<String>> serverOptions() {
getRequest().ifPresent(request -> { getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) {
ApiUtil.setExampleResponse(request, "*/*", "\"\""); ApiUtil.setExampleResponse(request, "*/*", "\"\"");
break; break;

View File

@ -18,6 +18,9 @@
package org.openapitools.codegen.online.configuration; package org.openapitools.codegen.online.configuration;
import com.fasterxml.jackson.databind.JsonNode; 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
@ -28,17 +31,14 @@ import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; 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.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.HashSet;
@Configuration @Configuration
@ -65,12 +65,12 @@ public class OpenAPIDocumentationConfig {
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("") .termsOfServiceUrl("")
.version(version) .version(version)
.contact(new Contact("","", "")) .contact(new Contact("", "", ""))
.build(); .build();
} }
@Bean @Bean
public Docket customImplementation(){ public Docket customImplementation() {
Docket docket = new Docket(DocumentationType.SWAGGER_2) Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select() .select()
.apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api")) .apis(RequestHandlerSelectors.basePackage("org.openapitools.codegen.online.api"))
@ -99,7 +99,7 @@ public class OpenAPIDocumentationConfig {
docket.host(authority); docket.host(authority);
} }
docket.pathMapping(hostURI.getPath()); docket.pathMapping(hostURI.getPath());
} catch(URISyntaxException e) { } catch (URISyntaxException e) {
LOGGER.warn("Could not parse configured GENERATOR_HOST '" + hostString + "': " + e.getMessage()); 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 type;
@Getter String message; @Getter String message;
public ApiResponse() {} public ApiResponse() {
}
public ApiResponse(int code, String message) { public ApiResponse(int code, String message) {
this.code = code; this.code = code;

View File

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

View File

@ -22,7 +22,9 @@ import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
@Setter @NoArgsConstructor @AllArgsConstructor @Setter
@NoArgsConstructor
@AllArgsConstructor
public class ResponseCode { public class ResponseCode {
private String code; private String code;
private String link; 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.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue; import io.swagger.v3.parser.core.models.AuthorizationValue;
import io.swagger.v3.parser.core.models.ParseOptions; import io.swagger.v3.parser.core.models.ParseOptions;
import org.openapitools.codegen.CliOption; import org.openapitools.codegen.*;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.online.model.GeneratorInput; import org.openapitools.codegen.online.model.GeneratorInput;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -35,11 +31,7 @@ import org.springframework.web.server.ResponseStatusException;
import java.io.File; import java.io.File;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.ArrayList; import java.util.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class Generator { public class Generator {
private static Logger LOGGER = LoggerFactory.getLogger(Generator.class); private static Logger LOGGER = LoggerFactory.getLogger(Generator.class);
@ -49,7 +41,7 @@ public class Generator {
try { try {
config = CodegenConfigLoader.forName(language); config = CodegenConfigLoader.forName(language);
} catch (Exception e) { } 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)); language, e));
} }
Map<String, CliOption> map = new LinkedHashMap<>(); Map<String, CliOption> map = new LinkedHashMap<>();
@ -82,7 +74,7 @@ public class Generator {
} }
private static String generate(String language, GeneratorInput opts, Type type) { 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) { if (opts == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No options were supplied"); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No options were supplied");
} }
@ -141,13 +133,13 @@ public class Generator {
codegenConfig.additionalProperties().put("openAPI", openapi); codegenConfig.additionalProperties().put("openAPI", openapi);
} }
if(opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()){ if (opts.getOpenapiNormalizer() != null && !opts.getOpenapiNormalizer().isEmpty()) {
for(String rule: opts.getOpenapiNormalizer()){ for (String rule : opts.getOpenapiNormalizer()) {
String[] ruleOperands = rule.split("="); 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>"); 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; package org.openapitools.codegen.online.service;
import java.io.BufferedInputStream; import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
@ -32,7 +27,6 @@ import java.util.zip.ZipOutputStream;
* sub files and sub directories, recursively. * sub files and sub directories, recursively.
* *
* @author Ha Minh Nam * @author Ha Minh Nam
*
*/ */
public class ZipUtil { public class ZipUtil {
/** /**

View File

@ -159,7 +159,7 @@ public class GenApiControllerTest {
.andExpect(content().contentType("application/zip")) .andExpect(content().contentType("application/zip"))
.andExpect(status().isOk()).andReturn().getResponse().getHeader("Content-Length")); .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) { public void setOptValue(String optValue) {
if (this.enumValues!=null && this.enumValues.containsKey(optValue)) { if (this.enumValues != null && this.enumValues.containsKey(optValue)) {
this.optValue = optValue; this.optValue = optValue;
} else { } else {
this.optValue = null; this.optValue = null;
@ -115,7 +115,7 @@ public class CliOption {
@JsonIgnore @JsonIgnore
public String getOptionHelp() { public String getOptionHelp() {
StringBuilder sb = new StringBuilder(description); StringBuilder sb = new StringBuilder(description);
if(defaultValue != null) { if (defaultValue != null) {
sb.append(" (Default: ").append(defaultValue).append(")"); sb.append(" (Default: ").append(defaultValue).append(")");
} }
if (enumValues != null) { if (enumValues != null) {

View File

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

View File

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

View File

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

View File

@ -8,7 +8,7 @@ import java.util.*;
/** /**
* This class encapsulates the OpenAPI discriminator construct, as specified at * This class encapsulates the OpenAPI discriminator construct, as specified at
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#discriminatorObject. * 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, * 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. * 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 * The discriminator is a specific object in a schema which is used to inform the consumer of
@ -61,14 +61,14 @@ public class CodegenDiscriminator {
/** /**
* An object to hold discriminator mappings between payload values and schema names or * An object to hold discriminator mappings between payload values and schema names or
* references. * references.
* * <p>
* In the OpenAPI document, the discriminator "mapping" attribute is optional. * 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 * 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. * 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, * 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. * 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. // The value of the discriminator property in the payload.
@Getter @Setter @Getter @Setter
private String mappingName; private String mappingName;

View File

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

View File

@ -19,13 +19,12 @@ package org.openapitools.codegen;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.v3.oas.models.ExternalDocumentation; import io.swagger.v3.oas.models.ExternalDocumentation;
import java.util.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.util.*;
/** /**
* CodegenModel represents a schema object in a OpenAPI document. * CodegenModel represents a schema object in a OpenAPI document.
*/ */
@ -174,7 +173,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public boolean isArray; public boolean isArray;
public boolean hasChildren; public boolean hasChildren;
public boolean isMap; 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 isOptional;
public boolean isNull; public boolean isNull;
public boolean isVoid = false; 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. * The type of the value for the additionalProperties keyword in the OAS document.
* Used in map like objects, including composed schemas. * Used in map like objects, including composed schemas.
* * <p>
* In most programming languages, the additional (undeclared) properties are stored * 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. * 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 * 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. * In that case 'CodegenModel.parent' is set to represent the class hierarchy.
* Another way is to use CodegenModel.additionalPropertiesType. A code generator * Another way is to use CodegenModel.additionalPropertiesType. A code generator
* such as Python does not use class inheritance to model additional properties. * 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 * For example, in the OAS schema below, the schema has a declared 'id' property
* and additional, undeclared properties of type 'integer' are allowed. * and additional, undeclared properties of type 'integer' are allowed.
* * <p>
* type: object * type: object
* properties: * properties:
* id: * id:
* type: integer * type: integer
* additionalProperties: * additionalProperties:
* type: integer * type: integer
*
*/ */
@Getter @Setter @Getter @Setter
public String additionalPropertiesType; public String additionalPropertiesType;
/** /**
* True if additionalProperties is set to true (boolean value), any type, free form object, etc * 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 * TODO: we may rename this to isAdditionalPropertiesEnabled or something
* else to avoid confusions * else to avoid confusions
*/ */
@ -758,14 +758,22 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
} }
@Override @Override
public boolean getIsUuid() { return isUuid; } public boolean getIsUuid() {
return isUuid;
}
@Override @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 @Override
public void setComposedSchemas(CodegenComposedSchemas composedSchemas) { public void setComposedSchemas(CodegenComposedSchemas composedSchemas) {
@ -833,7 +841,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
} }
@Override @Override
public void setIsBinary(boolean isBinary) {} public void setIsBinary(boolean isBinary) {
}
@Override @Override
public boolean getIsByteArray() { public boolean getIsByteArray() {
@ -841,7 +850,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
} }
@Override @Override
public void setIsByteArray(boolean isByteArray) {} public void setIsByteArray(boolean isByteArray) {
}
@Override @Override
public boolean getIsDecimal() { public boolean getIsDecimal() {
@ -1005,7 +1015,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
sb.append(", parent='").append(parent).append('\''); sb.append(", parent='").append(parent).append('\'');
sb.append(", parentSchema='").append(parentSchema).append('\''); sb.append(", parentSchema='").append(parentSchema).append('\'');
sb.append(", interfaces=").append(interfaces); 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(", allParents=").append(allParents);
sb.append(", parentModel=").append(parentModel); sb.append(", parentModel=").append(parentModel);
sb.append(", children=").append(children != null ? children.size() : "[]"); sb.append(", children=").append(children != null ? children.size() : "[]");
@ -1141,10 +1151,14 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
} }
@Override @Override
public Map<String, CodegenProperty> getRequiredVarsMap() { return requiredVarsMap; } public Map<String, CodegenProperty> getRequiredVarsMap() {
return requiredVarsMap;
}
@Override @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 * Remove duplicated properties in all variable list

View File

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

View File

@ -19,7 +19,8 @@ package org.openapitools.codegen;
import lombok.Getter; import lombok.Getter;
@Getter public enum CodegenModelType { @Getter
public enum CodegenModelType {
MODEL(CodegenModel.class), MODEL(CodegenModel.class),
OPERATION(CodegenOperation.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 * @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() { public boolean getAllResponsesAreErrors() {
return responses.stream().allMatch(response -> response.is4xx || response.is5xx); return responses.stream().allMatch(response -> response.is4xx || response.is5xx);
@ -237,7 +239,7 @@ public class CodegenOperation {
return null; return null;
} }
LinkedHashMap<String, CodegenMediaType> content = bodyParam.getContent(); LinkedHashMap<String, CodegenMediaType> content = bodyParam.getContent();
for (String contentType: content.keySet()) { for (String contentType : content.keySet()) {
contentTypeToOperation.put(contentType, this); contentTypeToOperation.put(contentType, this);
} }
return contentTypeToOperation; return contentTypeToOperation;

View File

@ -17,17 +17,12 @@
package org.openapitools.codegen; 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 io.swagger.v3.oas.models.examples.Example;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.*;
/** /**
* Describes a single operation parameter in the OAS specification. * Describes a single operation parameter in the OAS specification.
* A unique parameter is defined by a combination of a name and location. * 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, public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary,
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isShort, isUnboundedInteger; isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isShort, isUnboundedInteger;
public boolean isArray, isMap; 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 isOptional;
public boolean isFile; public boolean isFile;
public boolean isEnum; public boolean isEnum;
@ -291,7 +288,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation,
getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(),
getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), 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, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger,
hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content,
requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties, requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties,

View File

@ -20,12 +20,7 @@ package org.openapitools.codegen;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperties { public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperties {
/** /**
@ -178,7 +173,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
public boolean isAnyType; public boolean isAnyType;
public boolean isArray; public boolean isArray;
public boolean isMap; 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 isOptional;
public boolean isEnum; // true if the enum is defined inline 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. 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 boolean hasDiscriminatorWithNonEmptyMapping;
private CodegenComposedSchemas composedSchemas = null; private CodegenComposedSchemas composedSchemas = null;
private boolean hasMultipleTypes = false; 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 boolean hasSanitizedName = false;
private Map<String, CodegenProperty> requiredVarsMap; private Map<String, CodegenProperty> requiredVarsMap;
private String ref; private String ref;
@ -849,7 +848,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
return hasSanitizedName; return hasSanitizedName;
} }
public void setHasSanitizedName(boolean hasSanitizedName) { this.hasSanitizedName = hasSanitizedName; } public void setHasSanitizedName(boolean hasSanitizedName) {
this.hasSanitizedName = hasSanitizedName;
}
@Override @Override
public boolean getIsUuid() { public boolean getIsUuid() {

View File

@ -63,7 +63,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public boolean simpleType; public boolean simpleType;
public boolean primitiveType; public boolean primitiveType;
public boolean isMap; 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 isOptional;
public boolean isArray; public boolean isArray;
public boolean isBinary = false; public boolean isBinary = false;
@ -212,7 +214,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setContains instead of this // use content.mediaType.schema.setContains instead of this
@Override @Override
public void setContains(CodegenProperty contains) {} public void setContains(CodegenProperty contains) {
}
// use content.mediaType.schema.getDependentRequired instead of this // use content.mediaType.schema.getDependentRequired instead of this
@Override @Override
@ -222,7 +225,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setDependentRequired instead of this // use content.mediaType.schema.setDependentRequired instead of this
@Override @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 // use content.mediaType.schema.getIsBooleanSchemaTrue instead of this
@Override @Override
@ -232,7 +236,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setIsBooleanSchemaTrue instead of this // use content.mediaType.schema.setIsBooleanSchemaTrue instead of this
@Override @Override
public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {} public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {
}
// use content.mediaType.schema.getIsBooleanSchemaFalse instead of this // use content.mediaType.schema.getIsBooleanSchemaFalse instead of this
@Override @Override
@ -242,7 +247,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setIsBooleanSchemaFalse instead of this // use content.mediaType.schema.setIsBooleanSchemaFalse instead of this
@Override @Override
public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {} public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {
}
// use content.mediaType.schema.getFormat instead of this // use content.mediaType.schema.getFormat instead of this
@Override @Override
@ -252,7 +258,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
// use content.mediaType.schema.setFormat instead of this // use content.mediaType.schema.setFormat instead of this
@Override @Override
public void setFormat(String format) {} public void setFormat(String format) {
}
@Override @Override
public String getPattern() { public String getPattern() {
@ -782,16 +789,24 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
} }
@Override @Override
public Map<String, CodegenProperty> getRequiredVarsMap() { return requiredVarsMap; } public Map<String, CodegenProperty> getRequiredVarsMap() {
return requiredVarsMap;
}
@Override @Override
public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; } public void setRequiredVarsMap(Map<String, CodegenProperty> requiredVarsMap) {
this.requiredVarsMap = requiredVarsMap;
}
@Override @Override
public String getRef() { return ref; } public String getRef() {
return ref;
}
@Override @Override
public void setRef(String ref) { this.ref=ref; } public void setRef(String ref) {
this.ref = ref;
}
@Override @Override
public boolean getSchemaIsFromAdditionalProperties() { public boolean getSchemaIsFromAdditionalProperties() {
@ -889,5 +904,6 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
} }
@Override @Override
public void setIsEnum(boolean isEnum) {} public void setIsEnum(boolean isEnum) {
}
} }

View File

@ -17,11 +17,7 @@
package org.openapitools.codegen; package org.openapitools.codegen;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class CodegenSecurity { public class CodegenSecurity {
@ -49,10 +45,10 @@ public class CodegenSecurity {
// OpenId specific // OpenId specific
public String openIdConnectUrl; public String openIdConnectUrl;
public CodegenSecurity () { public CodegenSecurity() {
} }
public CodegenSecurity (CodegenSecurity original) { public CodegenSecurity(CodegenSecurity original) {
this.name = original.name; this.name = original.name;
this.description = original.description; this.description = original.description;
this.type = original.type; this.type = original.type;

View File

@ -70,10 +70,10 @@ import org.openapitools.codegen.utils.OneOfImplementorAdditionalData;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -350,7 +350,6 @@ public class DefaultCodegen implements CodegenConfig {
* first from additionalProperties * first from additionalProperties
* then from the getter in this instance * then from the getter in this instance
* then from the fields in this instance * then from the fields in this instance
*
*/ */
protected void useCodegenAsMustacheParentContext() { protected void useCodegenAsMustacheParentContext() {
additionalProperties.put(CodegenConstants.MUSTACHE_PARENT_CONTEXT, this); additionalProperties.put(CodegenConstants.MUSTACHE_PARENT_CONTEXT, this);
@ -546,6 +545,7 @@ public class DefaultCodegen implements CodegenConfig {
* This usually occurs when the data type is different. * 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 * 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. * to contain a new value. Doing so prevents having to include the discriminator in the constructor.
*
* @param model * @param model
* @param property * @param property
* @return * @return
@ -1133,6 +1133,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* This method escapes text to be used in a single quoted string * This method escapes text to be used in a single quoted string
*
* @param input the input string * @param input the input string
* @return the escaped string * @return the escaped string
*/ */
@ -3275,7 +3276,7 @@ public class DefaultCodegen implements CodegenConfig {
} }
if (refSchema.getProperties() != null && refSchema.getProperties().get(discPropName) != null) { 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(); CodegenProperty cp = new CodegenProperty();
if (ModelUtils.isStringSchema(discSchema)) { if (ModelUtils.isStringSchema(discSchema)) {
cp.isString = true; cp.isString = true;
@ -8391,7 +8392,8 @@ public class DefaultCodegen implements CodegenConfig {
public void addImportsToOneOfInterface(List<Map<String, String>> imports) { 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) { protected void modifyFeatureSet(Consumer<FeatureSet.Builder> processor) {
FeatureSet.Builder builder = getFeatureSet().modify(); FeatureSet.Builder builder = getFeatureSet().modify();
@ -8403,7 +8405,8 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* An map entry for cached sanitized names. * 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) { public SanitizeNameOptions(String name, String removeCharRegEx, List<String> exceptions) {
this.name = name; this.name = name;
this.removeCharRegEx = removeCharRegEx; this.removeCharRegEx = removeCharRegEx;

View File

@ -18,11 +18,7 @@
package org.openapitools.codegen; package org.openapitools.codegen;
import io.swagger.v3.core.util.Json; import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.*;
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.info.Contact; import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License; 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.io.IOCase;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.api.TemplateDefinition; import org.openapitools.codegen.api.*;
import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.api.TemplateProcessor;
import org.openapitools.codegen.config.GlobalSettings; 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.ignore.CodegenIgnoreProcessor;
import org.openapitools.codegen.meta.GeneratorMetadata; import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability; 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.GeneratorTemplateContentLocator;
import org.openapitools.codegen.templating.MustacheEngineAdapter; import org.openapitools.codegen.templating.MustacheEngineAdapter;
import org.openapitools.codegen.templating.TemplateManagerOptions; import org.openapitools.codegen.templating.TemplateManagerOptions;
import org.openapitools.codegen.utils.ImplementationVersion; import org.openapitools.codegen.utils.*;
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.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
@ -461,7 +451,7 @@ public class DefaultGenerator implements Generator {
} }
Set<String> modelKeys = modelKeysSupplier.get(); Set<String> modelKeys = modelKeysSupplier.get();
if(modelKeys.isEmpty()) { if (modelKeys.isEmpty()) {
return; return;
} }
@ -536,11 +526,11 @@ public class DefaultGenerator implements Generator {
allProcessedModels = config.postProcessAllModels(allProcessedModels); allProcessedModels = config.postProcessAllModels(allProcessedModels);
if (generateRecursiveDependentModels) { if (generateRecursiveDependentModels) {
for(ModelsMap modelsMap : allProcessedModels.values()) { for (ModelsMap modelsMap : allProcessedModels.values()) {
for(ModelMap mm: modelsMap.getModels()) { for (ModelMap mm : modelsMap.getModels()) {
CodegenModel cm = mm.getModel(); CodegenModel cm = mm.getModel();
if (cm != null) { if (cm != null) {
for(CodegenProperty variable : cm.getVars()) { for (CodegenProperty variable : cm.getVars()) {
generateModelsForVariable(files, allModels, unusedModels, aliasModels, processedModels, variable); generateModelsForVariable(files, allModels, unusedModels, aliasModels, processedModels, variable);
} }
//TODO: handle interfaces //TODO: handle interfaces
@ -616,10 +606,10 @@ public class DefaultGenerator implements Generator {
if (!processedModels.contains(key) && allSchemas.containsKey(key)) { if (!processedModels.contains(key) && allSchemas.containsKey(key)) {
generateModels(files, allModels, unusedModels, aliasModels, processedModels, () -> Set.of(key)); generateModels(files, allModels, unusedModels, aliasModels, processedModels, () -> Set.of(key));
} else { } 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 { } 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); Map<String, Schema> schemaMap = ModelUtils.getSchemas(this.openAPI);
Set<String> keys = schemaMap.keySet(); Set<String> keys = schemaMap.keySet();
String simpleRef; String simpleRef;
if(keys.contains(type)) { if (keys.contains(type)) {
return type; return type;
} else if (keys.contains(simpleRef = ModelUtils.getSimpleRef(ref))) { } else if (keys.contains(simpleRef = ModelUtils.getSimpleRef(ref))) {
return simpleRef; return simpleRef;
@ -688,7 +678,7 @@ public class DefaultGenerator implements Generator {
for (String tag : paths.keySet()) { for (String tag : paths.keySet()) {
try { try {
List<CodegenOperation> ops = paths.get(tag); List<CodegenOperation> ops = paths.get(tag);
if(!this.config.isSkipSortingOperations()) { if (!this.config.isSkipSortingOperations()) {
// sort operations by operationId // sort operations by operationId
ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.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 outputDir = config.getOutputDir() + File.separator + config.templateOutputDirs().get(templateName);
String filename = config.apiFilename(templateName, tag, outputDir); String filename = config.apiFilename(templateName, tag, outputDir);
// do not overwrite apiController file for spring server // 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); written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS, outputDir);
} else { } else {
LOGGER.info("Implementation file {} is not overwritten",filename); LOGGER.info("Implementation file {} is not overwritten", filename);
} }
} else { } else {
String filename = config.apiFilename(templateName, tag); 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); written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS);
} else { } else {
LOGGER.info("Implementation file {} is not overwritten",filename); LOGGER.info("Implementation file {} is not overwritten", filename);
} }
} }
if (written != null) { if (written != null) {
@ -1619,7 +1609,7 @@ public class DefaultGenerator implements Generator {
} }
private static String generateParameterId(Parameter parameter) { 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) { 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 -> { relativePaths.forEach(relativePath -> {
sb.append(relativePath).append(System.lineSeparator()); sb.append(relativePath).append(System.lineSeparator());
}); });

View File

@ -9,7 +9,8 @@ import java.util.Locale;
/** /**
* Holds details about a file's write status for display via the --dry-run option of CLI * Holds details about a file's write status for display via the --dry-run option of CLI
*/ */
@Getter class DryRunStatus { @Getter
class DryRunStatus {
/** /**
* -- GETTER -- * -- GETTER --
* Gets the target path of the file write operation * Gets the target path of the file write operation
@ -110,7 +111,8 @@ import java.util.Locale;
/** /**
* Represents the possible states of a file write operation as determined by the Generator * Represents the possible states of a file write operation as determined by the Generator
*/ */
@Getter enum State { @Getter
enum State {
Write("w", "Write"), Write("w", "Write"),
WriteIfNewer("n", "Write if New/Updated"), WriteIfNewer("n", "Write if New/Updated"),
Ignored("i", "Ignored"), Ignored("i", "Ignored"),

View File

@ -122,6 +122,7 @@ public class DryRunTemplateManager implements TemplateProcessor {
* been enabled via {@link #enableTemplateDataCapturing()} prior to generation.<br> * 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 * Note: Not all files have template data (e.g. Metadata files) in such case an empty
* map is returned. * map is returned.
*
* @param generatedFile An absolute path to the generated file * @param generatedFile An absolute path to the generated file
* @return Typically one of the *Map types found in {@link org.openapitools.codegen.model} * @return Typically one of the *Map types found in {@link org.openapitools.codegen.model}
*/ */

View File

@ -1,20 +1,13 @@
package org.openapitools.codegen; package org.openapitools.codegen;
import java.util.Arrays; import io.swagger.v3.oas.models.OpenAPI;
import java.util.Collections; import io.swagger.v3.oas.models.media.Schema;
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 org.openapitools.codegen.meta.FeatureSet; import org.openapitools.codegen.meta.FeatureSet;
import org.openapitools.codegen.meta.features.SchemaSupportFeature; import org.openapitools.codegen.meta.features.SchemaSupportFeature;
import org.openapitools.codegen.utils.ModelUtils; import org.openapitools.codegen.utils.ModelUtils;
import io.swagger.v3.oas.models.OpenAPI; import java.util.*;
import io.swagger.v3.oas.models.media.Schema; import java.util.stream.Stream;
public interface IJsonSchemaValidationProperties { public interface IJsonSchemaValidationProperties {
CodegenProperty getContains(); CodegenProperty getContains();
@ -116,6 +109,7 @@ public interface IJsonSchemaValidationProperties {
* 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. * 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(); boolean getIsOptional();
void setIsOptional(boolean isOptional); void setIsOptional(boolean isOptional);
boolean getIsArray(); 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.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.util.Json; 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.*;
import io.swagger.v3.oas.models.PathItem.HttpMethod; import io.swagger.v3.oas.models.PathItem.HttpMethod;
import io.swagger.v3.oas.models.callbacks.Callback; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.util.*; import java.util.*;
public class InlineModelResolver { public class InlineModelResolver {

View File

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

View File

@ -35,7 +35,6 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.openapitools.codegen.utils.StringUtils.getUniqueString; import static org.openapitools.codegen.utils.StringUtils.getUniqueString;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class OpenAPINormalizer { public class OpenAPINormalizer {
private OpenAPI openAPI; private OpenAPI openAPI;
@ -1013,7 +1012,6 @@ public class OpenAPINormalizer {
} }
/** /**
* If the schema contains anyOf/oneOf and properties, remove oneOf/anyOf as these serve as rules to * 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. * 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.Optional;
import java.util.Set; import java.util.Set;
@Getter @Setter @Getter
@Setter
public class SpecValidationException extends RuntimeException { public class SpecValidationException extends RuntimeException {
private Set<String> errors; private Set<String> 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 * 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. * 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 * Supporting files are generated once for an entire application while api/model bound definitions are generated multiple
* times according to their target use. * times according to their target use.
*/ */
@Getter public class SupportingFile extends TemplateDefinition { @Getter
public class SupportingFile extends TemplateDefinition {
private boolean canOverwrite = true; private boolean canOverwrite = true;
public SupportingFile(String templateFile, String destinationFilename) { public SupportingFile(String templateFile, String destinationFilename) {

View File

@ -13,8 +13,14 @@ import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.*; import java.nio.file.Files;
import java.util.*; 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; import java.util.regex.Pattern;
/** /**
@ -87,7 +93,6 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
* Gets a normalized classpath resource location according to OS-specific file separator * Gets a normalized classpath resource location according to OS-specific file separator
* *
* @param name The name of the resource file/directory to find * @param name The name of the resource file/directory to find
*
* @return A normalized string according to OS-specific file separator * @return A normalized string according to OS-specific file separator
*/ */
public static String getCPResourcePath(final String name) { public static String getCPResourcePath(final String name) {
@ -153,7 +158,6 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
* @param data Input data * @param data Input data
* @param template Input template location * @param template Input template location
* @param target The targeted file output location * @param target The targeted file output location
*
* @return The actual file * @return The actual file
*/ */
@Override @Override

View File

@ -6,7 +6,8 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; 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_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"), 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

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

View File

@ -96,9 +96,10 @@ public class DynamicSettings {
* <p>Constructor for DynamicSettings.</p> * <p>Constructor for DynamicSettings.</p>
*/ */
@JsonCreator @JsonCreator
public DynamicSettings() { } public DynamicSettings() {
}
private void excludeSettingsFromDynamicProperties(){ private void excludeSettingsFromDynamicProperties() {
Set<String> fieldNames = new HashSet<>(); Set<String> fieldNames = new HashSet<>();
for (Field field : GeneratorSettings.class.getDeclaredFields()) { for (Field field : GeneratorSettings.class.getDeclaredFields()) {
fieldNames.add(field.getName()); 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, * 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 * 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). * 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 * This provides a set of properties specific to the executing thread, such that the generator may not modify system properties
* consumed by other threads. * consumed by other threads.
* *

View File

@ -1,32 +1,24 @@
package org.openapitools.codegen.config; 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.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.util.ArrayList; import java.util.*;
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.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; 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 { public class MergedSpecBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(MergedSpecBuilder.class); private static final Logger LOGGER = LoggerFactory.getLogger(MergedSpecBuilder.class);
@ -93,7 +85,7 @@ public class MergedSpecBuilder {
Map<String, Object> paths = new HashMap<>(); Map<String, Object> paths = new HashMap<>();
spec.put("paths", paths); spec.put("paths", paths);
for(SpecWithPaths specWithPaths : allPaths) { for (SpecWithPaths specWithPaths : allPaths) {
for (String path : specWithPaths.paths) { for (String path : specWithPaths.paths) {
String specRelatedPath = "./" + specWithPaths.specRelatedPath + "#/paths/" + path.replace("/", "~1"); String specRelatedPath = "./" + specWithPaths.specRelatedPath + "#/paths/" + path.replace("/", "~1");
paths.put(path, ImmutableMap.of( paths.put(path, ImmutableMap.of(
@ -134,10 +126,12 @@ public class MergedSpecBuilder {
private void deleteMergedFileFromPreviousRun() { private void deleteMergedFileFromPreviousRun() {
try { try {
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".json")); Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".json"));
} catch (IOException e) { } } catch (IOException e) {
}
try { try {
Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".yaml")); Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".yaml"));
} catch (IOException e) { } } catch (IOException e) {
}
} }
private static class SpecWithPaths { private static class SpecWithPaths {

View File

@ -398,6 +398,7 @@ public class ExampleGenerator {
/** /**
* Transverse and resolves all property examples for `allOf` composed schemas into `values` map object * Transverse and resolves all property examples for `allOf` composed schemas into `values` map object
*
* @param mediaType MIME type * @param mediaType MIME type
* @param schema OAS schema * @param schema OAS schema
* @param processedModels Set containing all processed models * @param processedModels Set containing all processed models

View File

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

View File

@ -25,7 +25,10 @@ import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; 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; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
@ -113,7 +116,7 @@ public class CodegenIgnoreProcessor {
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore // 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 // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
if( if (
//: A blank line matches no files, so it can serve as a separator for readability. //: A blank line matches no files, so it can serve as a separator for readability.
line.length() == 0 line.length() == 0
) continue; ) continue;
@ -121,7 +124,7 @@ public class CodegenIgnoreProcessor {
Rule rule = Rule.create(line); Rule rule = Rule.create(line);
// rule could be null here if it's a COMMENT, for example // rule could be null here if it's a COMMENT, for example
if(rule != null) { if (rule != null) {
if (Boolean.TRUE.equals(rule.getNegated())) { if (Boolean.TRUE.equals(rule.getNegated())) {
inclusionRules.add(rule); inclusionRules.add(rule);
} else { } 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). * @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed).
*/ */
public boolean allowsFile(final File targetFile) { 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()); File file = new File(this.ignoreFile.getAbsoluteFile().getParentFile().toURI().relativize(targetFile.toURI()).getPath());
boolean directoryExcluded = false; boolean directoryExcluded = false;
boolean exclude = false; boolean exclude = false;
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) { if (exclusionRules.size() == 0 && inclusionRules.size() == 0) {
return true; return true;
} }
@ -154,12 +157,12 @@ public class CodegenIgnoreProcessor {
Rule current = exclusionRules.get(i); Rule current = exclusionRules.get(i);
Rule.Operation op = current.evaluate(file.getPath()); Rule.Operation op = current.evaluate(file.getPath());
switch (op){ switch (op) {
case EXCLUDE: case EXCLUDE:
exclude = true; exclude = true;
// Include rule can't override rules that exclude a file by some parent directory. // Include rule can't override rules that exclude a file by some parent directory.
if(current instanceof DirectoryRule) { if (current instanceof DirectoryRule) {
directoryExcluded = true; directoryExcluded = true;
} }
break; break;
@ -174,7 +177,7 @@ public class CodegenIgnoreProcessor {
} }
} }
if(exclude) { if (exclude) {
// Only need to process inclusion rules if we've been excluded // Only need to process inclusion rules if we've been excluded
for (int i = 0; exclude && i < inclusionRules.size(); i++) { for (int i = 0; exclude && i < inclusionRules.size(); i++) {
Rule current = inclusionRules.get(i); Rule current = inclusionRules.get(i);
@ -182,8 +185,8 @@ public class CodegenIgnoreProcessor {
// At this point exclude=true means the file should be ignored. // At this point exclude=true means the file should be ignored.
// op == INCLUDE means we have to flip that flag. // op == INCLUDE means we have to flip that flag.
if(op.equals(Rule.Operation.INCLUDE)) { if (op.equals(Rule.Operation.INCLUDE)) {
if(current instanceof DirectoryRule && directoryExcluded) { if (current instanceof DirectoryRule && directoryExcluded) {
// e.g // e.g
// baz/ // baz/
// !foo/bar/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 * 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. * 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. * 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. * @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(); StringBuilder sb = new StringBuilder();
sb.append("glob:"); sb.append("glob:");
sb.append(pattern); sb.append(pattern);
if(!pattern.endsWith("/")) sb.append("/"); if (!pattern.endsWith("/")) sb.append("/");
directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString()); directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());
sb.append("**"); sb.append("**");
contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString()); contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString());

View File

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

View File

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

View File

@ -21,7 +21,8 @@ import lombok.Getter;
import java.util.List; import java.util.List;
@Getter public class InvalidRule extends Rule { @Getter
public class InvalidRule extends Rule {
private final String reason; private final String reason;
InvalidRule(List<Part> syntax, String definition, 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; import lombok.Getter;
@Getter class Part { @Getter
class Part {
private final IgnoreLineParser.Token token; private final IgnoreLineParser.Token token;
private final String value; private final String value;

View File

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

View File

@ -38,7 +38,7 @@ public abstract class Rule {
public abstract Boolean matches(String relativePath); public abstract Boolean matches(String relativePath);
protected String getPattern() { protected String getPattern() {
if(syntax == null) return this.definition; if (syntax == null) return this.definition;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (Part current : syntax) { for (Part current : syntax) {
@ -75,7 +75,7 @@ public abstract class Rule {
public Operation evaluate(String relativePath) { public Operation evaluate(String relativePath) {
if (Boolean.TRUE.equals(matches(relativePath))) { if (Boolean.TRUE.equals(matches(relativePath))) {
if(Boolean.TRUE.equals(this.getNegated())) { if (Boolean.TRUE.equals(this.getNegated())) {
return this.getIncludeOperation(); return this.getIncludeOperation();
} }
return this.getExcludeOperation(); return this.getExcludeOperation();
@ -83,8 +83,13 @@ public abstract class Rule {
return Operation.NOOP; return Operation.NOOP;
} }
protected Operation getIncludeOperation(){ return Operation.INCLUDE; } protected Operation getIncludeOperation() {
protected Operation getExcludeOperation(){ return Operation.EXCLUDE; } return Operation.INCLUDE;
}
protected Operation getExcludeOperation() {
return Operation.EXCLUDE;
}
public static Rule create(String definition) { public static Rule create(String definition) {
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore // 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.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*; import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.ClientModificationFeature; import org.openapitools.codegen.meta.features.*;
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.model.ModelMap; import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationMap; import org.openapitools.codegen.model.OperationMap;

View File

@ -18,10 +18,9 @@
package org.openapitools.codegen.languages; package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Lambda;
import com.samskivert.mustache.Template; import com.samskivert.mustache.Template;
import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.Schema;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; 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) { public static Double asDouble(String strNum) {
if (strNum == null) { if (strNum == null) {
return 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) { public static Integer asInteger(String strNum) {
if (strNum == null) { if (strNum == null) {
return null; return null;
@ -751,7 +754,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
property.name = patchPropertyName(model, property.name); property.name = patchPropertyName(model, property.name);
String[] nestedTypes = { "List", "Collection", "ICollection", "Dictionary" }; String[] nestedTypes = {"List", "Collection", "ICollection", "Dictionary"};
Arrays.stream(nestedTypes).forEach(nestedType -> { Arrays.stream(nestedTypes).forEach(nestedType -> {
// fix incorrect data types for maps of maps // fix incorrect data types for maps of maps
@ -835,6 +838,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
httpStatusesWithReturn.add(status); httpStatusesWithReturn.add(status);
} }
} }
private HashMap<String, String> duplicateOf = new HashMap<String, String>(); private HashMap<String, String> duplicateOf = new HashMap<String, String>();
@Override @Override
@ -876,7 +880,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
} }
String code = response.code.toLowerCase(Locale.ROOT); String code = response.code.toLowerCase(Locale.ROOT);
switch(code) { switch (code) {
case "default": case "default":
case "0": case "0":
postProcessResponseCode(response, "Default", httpStatusesWithReturn); postProcessResponseCode(response, "Default", httpStatusesWithReturn);
@ -1242,7 +1246,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
} }
protected void processOperation(CodegenOperation operation) { protected void processOperation(CodegenOperation operation) {
String[] nestedTypes = { "List", "Collection", "ICollection", "Dictionary" }; String[] nestedTypes = {"List", "Collection", "ICollection", "Dictionary"};
Arrays.stream(nestedTypes).forEach(nestedType -> { Arrays.stream(nestedTypes).forEach(nestedType -> {
if (operation.returnProperty != null && operation.returnType.contains("<" + nestedType + ">") && operation.returnProperty.items != null) { 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 * @param name The original name
* @return The adjusted name * @return The adjusted name
*/ */
private String adjustNamingStyle(String name) private String adjustNamingStyle(String name) {
{
switch (getEnumPropertyNaming()) { switch (getEnumPropertyNaming()) {
case camelCase: case camelCase:
// NOTE: Removes hyphens and underscores // NOTE: Removes hyphens and underscores
@ -1765,7 +1768,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
return (this.getValueTypes().contains(var.dataType) || var.isEnum); return (this.getValueTypes().contains(var.dataType) || var.isEnum);
} }
protected boolean useNet60OrLater() { return false; } protected boolean useNet60OrLater() {
return false;
}
protected boolean useDateOnly() { protected boolean useDateOnly() {
return useNet60OrLater() && !useDateTimeForDateFlag; return useNet60OrLater() && !useDateTimeForDateFlag;
@ -1915,7 +1920,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
// only process files with .cs extension // only process files with .cs extension
if ("cs".equals(FilenameUtils.getExtension(file.toString()))) { if ("cs".equals(FilenameUtils.getExtension(file.toString()))) {
this.executePostProcessor(new String[] {csharpPostProcessFile, file.toString()}); this.executePostProcessor(new String[]{csharpPostProcessFile, file.toString()});
} }
} }
@ -1956,7 +1961,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen {
for (char c : pattern.substring(end).toCharArray()) { for (char c : pattern.substring(end).toCharArray()) {
if (optionsMap.containsKey(c)) { if (optionsMap.containsKey(c)) {
modifiers.add(optionsMap.get(c)); modifiers.add(optionsMap.get(c));
} else if (c == 'l'){ } else if (c == 'l') {
modifiers.remove("CultureInvariant"); modifiers.remove("CultureInvariant");
} else { } else {
vendorExtensions.put("x-modifier-" + c, c); 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.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda; import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.servers.Server; 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 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.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.model.ModelMap; import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.templating.mustache.IndentedLambda; import org.openapitools.codegen.templating.mustache.IndentedLambda;
@ -38,11 +37,7 @@ import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
abstract public class AbstractCppCodegen extends DefaultCodegen implements CodegenConfig { abstract public class AbstractCppCodegen extends DefaultCodegen implements CodegenConfig {
private final Logger LOGGER = LoggerFactory.getLogger(AbstractCppCodegen.class); 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 // only process files with cpp extension
if ("cpp".equals(FilenameUtils.getExtension(file.toString())) || "h".equals(FilenameUtils.getExtension(file.toString()))) { 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 // process all files with dart extension
if ("dart".equals(FilenameUtils.getExtension(file.toString()))) { if ("dart".equals(FilenameUtils.getExtension(file.toString()))) {
// currently supported is "dartfmt -w" and "dart format" // currently supported is "dartfmt -w" and "dart format"
this.executePostProcessor(new String[] {dartPostProcessFile, file.toString()}); this.executePostProcessor(new String[]{dartPostProcessFile, file.toString()});
} }
} }

View File

@ -632,5 +632,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
} }
@Override @Override
public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.EIFFEL; } public GeneratorLanguage generatorLanguage() {
return GeneratorLanguage.EIFFEL;
}
} }

View File

@ -18,7 +18,6 @@ package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda; import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.core.util.Json; import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.Schema;
import lombok.Getter; import lombok.Getter;
@ -30,7 +29,7 @@ import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationMap; import org.openapitools.codegen.model.OperationMap;
import org.openapitools.codegen.model.OperationsMap; import org.openapitools.codegen.model.OperationsMap;
import org.openapitools.codegen.templating.mustache.*; import org.openapitools.codegen.templating.mustache.CamelCaseAndSanitizeLambda;
import org.openapitools.codegen.utils.ModelUtils; import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -1050,7 +1049,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
// only process files with .fs extension // only process files with .fs extension
if ("fs".equals(FilenameUtils.getExtension(file.toString()))) { if ("fs".equals(FilenameUtils.getExtension(file.toString()))) {
this.executePostProcessor(new String[] {fsharpPostProcessFile, file.toString()}); this.executePostProcessor(new String[]{fsharpPostProcessFile, file.toString()});
} }
} }

View File

@ -1005,7 +1005,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
if ("go".equals(FilenameUtils.getExtension(file.toString()))) { if ("go".equals(FilenameUtils.getExtension(file.toString()))) {
// e.g. "gofmt -w yourcode.go" // e.g. "gofmt -w yourcode.go"
// e.g. "go fmt path/to/your/package" // e.g. "go fmt path/to/your/package"
this.executePostProcessor(new String[] {goPostProcessFile, file.toString()}); this.executePostProcessor(new String[]{goPostProcessFile, file.toString()});
} }
} }

View File

@ -26,7 +26,10 @@ import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.examples.Example; import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.media.*; import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.servers.Server;
@ -144,7 +147,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Getter @Setter @Getter @Setter
protected String testFolder = projectTestFolder + "/java"; protected String testFolder = projectTestFolder + "/java";
protected static enum ENUM_PROPERTY_NAMING_TYPE {MACRO_CASE, legacy}; protected enum ENUM_PROPERTY_NAMING_TYPE {MACRO_CASE, legacy}
protected static final String ENUM_PROPERTY_NAMING_DESC = "Naming convention for enum properties: 'MACRO_CASE' and 'legacy'"; protected static final String ENUM_PROPERTY_NAMING_DESC = "Naming convention for enum properties: 'MACRO_CASE' and 'legacy'";
@Getter protected ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = ENUM_PROPERTY_NAMING_TYPE.MACRO_CASE; @Getter protected ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = ENUM_PROPERTY_NAMING_TYPE.MACRO_CASE;
@ -428,10 +432,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
convertPropertyToStringAndWriteBack(BOOLEAN_GETTER_PREFIX, this::setBooleanGetterPrefix); convertPropertyToStringAndWriteBack(BOOLEAN_GETTER_PREFIX, this::setBooleanGetterPrefix);
convertPropertyToBooleanAndWriteBack(IGNORE_ANYOF_IN_ENUM, this::setIgnoreAnyOfInEnum); convertPropertyToBooleanAndWriteBack(IGNORE_ANYOF_IN_ENUM, this::setIgnoreAnyOfInEnum);
convertPropertyToTypeAndWriteBack(ADDITIONAL_MODEL_TYPE_ANNOTATIONS, convertPropertyToTypeAndWriteBack(ADDITIONAL_MODEL_TYPE_ANNOTATIONS,
annotations-> Arrays.asList(annotations.trim().split("\\s*(;|\\r?\\n)\\s*")), annotations -> Arrays.asList(annotations.trim().split("\\s*(;|\\r?\\n)\\s*")),
this::setAdditionalModelTypeAnnotations); this::setAdditionalModelTypeAnnotations);
convertPropertyToTypeAndWriteBack(ADDITIONAL_ONE_OF_TYPE_ANNOTATIONS, convertPropertyToTypeAndWriteBack(ADDITIONAL_ONE_OF_TYPE_ANNOTATIONS,
annotations-> Arrays.asList(annotations.trim().split("\\s*(;|\\r?\\n)\\s*")), annotations -> Arrays.asList(annotations.trim().split("\\s*(;|\\r?\\n)\\s*")),
this::setAdditionalOneOfTypeAnnotations); this::setAdditionalOneOfTypeAnnotations);
convertPropertyToTypeAndWriteBack(ADDITIONAL_ENUM_TYPE_ANNOTATIONS, convertPropertyToTypeAndWriteBack(ADDITIONAL_ENUM_TYPE_ANNOTATIONS,
annotations -> Arrays.asList(annotations.split(";")), annotations -> Arrays.asList(annotations.split(";")),
@ -549,7 +553,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
convertPropertyToStringAndWriteBack(CodegenConstants.SOURCE_FOLDER, this::setSourceFolder); convertPropertyToStringAndWriteBack(CodegenConstants.SOURCE_FOLDER, this::setSourceFolder);
convertPropertyToBooleanAndWriteBack(CodegenConstants.SERIALIZABLE_MODEL, this::setSerializableModel); convertPropertyToBooleanAndWriteBack(CodegenConstants.SERIALIZABLE_MODEL, this::setSerializableModel);
convertPropertyToStringAndWriteBack(CodegenConstants.LIBRARY, this::setLibrary); convertPropertyToStringAndWriteBack(CodegenConstants.LIBRARY, this::setLibrary);
convertPropertyToBooleanAndWriteBack(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, this::setSerializeBigDecimalAsString ); convertPropertyToBooleanAndWriteBack(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, this::setSerializeBigDecimalAsString);
// need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string
// additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); // additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel);
@ -655,7 +659,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
additionalProperties.put("sanitizeGeneric", (Mustache.Lambda) (fragment, writer) -> { additionalProperties.put("sanitizeGeneric", (Mustache.Lambda) (fragment, writer) -> {
String content = removeAnnotations(fragment.execute()); String content = removeAnnotations(fragment.execute());
for (final String s: List.of("<", ">", ",", " ")) { for (final String s : List.of("<", ">", ",", " ")) {
content = content.replace(s, ""); content = content.replace(s, "");
} }
writer.write(content); writer.write(content);
@ -667,6 +671,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
/** /**
* Analyse and post process all Models. * Analyse and post process all Models.
*
* @param objs the models map. * @param objs the models map.
* @return the processed models map. * @return the processed models map.
**/ **/
@ -715,7 +720,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
propertyHash.put(property.name, property); propertyHash.put(property.name, property);
} }
List<CodegenModel> parentModelList = getParentModelList(codegenModel); List<CodegenModel> parentModelList = getParentModelList(codegenModel);
for (CodegenModel parentCodegenModel: parentModelList) { for (CodegenModel parentCodegenModel : parentModelList) {
for (final CodegenProperty property : parentCodegenModel.vars) { for (final CodegenProperty property : parentCodegenModel.vars) {
// helper list of parentVars simplifies templating // helper list of parentVars simplifies templating
if (!propertyHash.containsKey(property.name)) { if (!propertyHash.containsKey(property.name)) {
@ -739,10 +744,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
codegenModel.parentRequiredVars = new ArrayList<>(codegenModel.getParentModel().requiredVars); codegenModel.parentRequiredVars = new ArrayList<>(codegenModel.getParentModel().requiredVars);
} }
// There must be a better way ... // There must be a better way ...
for (String imp: inheritedImports) { for (String imp : inheritedImports) {
String qimp = importMapping().get(imp); String qimp = importMapping().get(imp);
if (qimp != null) { if (qimp != null) {
Map<String,String> toAdd = new HashMap<>(); Map<String, String> toAdd = new HashMap<>();
toAdd.put("import", qimp); toAdd.put("import", qimp);
modelsAttrs.getImports().add(toAdd); modelsAttrs.getImports().add(toAdd);
} }
@ -1052,7 +1057,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
int idxLt = typeDeclaration.indexOf('<'); int idxLt = typeDeclaration.indexOf('<');
int idx = idxLt < 0 ? int idx = idxLt < 0 ?
typeDeclaration.lastIndexOf('.'): typeDeclaration.lastIndexOf('.') :
// last dot before the generic like in List<com.mycompany.Container<java.lang.Object> // last dot before the generic like in List<com.mycompany.Container<java.lang.Object>
typeDeclaration.substring(0, idxLt).lastIndexOf('.'); typeDeclaration.substring(0, idxLt).lastIndexOf('.');
if (idx > 0) { if (idx > 0) {
@ -1410,16 +1415,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
private String getDefaultCollectionType(Schema schema, String defaultValues) { private String getDefaultCollectionType(Schema schema, String defaultValues) {
String arrayFormat = "new %s<>(Arrays.asList(%s))"; String arrayFormat = "new %s<>(Arrays.asList(%s))";
if(defaultValues == null || defaultValues.isEmpty()){ if (defaultValues == null || defaultValues.isEmpty()) {
defaultValues = ""; defaultValues = "";
arrayFormat = "new %s<>()"; arrayFormat = "new %s<>()";
} }
if (ModelUtils.isSet(schema)) { if (ModelUtils.isSet(schema)) {
return String.format(Locale.ROOT, arrayFormat, return String.format(Locale.ROOT, arrayFormat,
instantiationTypes().getOrDefault("set", "LinkedHashSet"),defaultValues); instantiationTypes().getOrDefault("set", "LinkedHashSet"), defaultValues);
} }
return String.format(Locale.ROOT, arrayFormat, instantiationTypes().getOrDefault("array", "ArrayList"),defaultValues); return String.format(Locale.ROOT, arrayFormat, instantiationTypes().getOrDefault("array", "ArrayList"), defaultValues);
} }
@Override @Override
@ -1642,7 +1647,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public String toExampleValue(Schema p) { public String toExampleValue(Schema p) {
if (p.getExample() != null) { if (p.getExample() != null) {
if (p.getExample() instanceof Date) { if (p.getExample() instanceof Date) {
Date date = (Date)p.getExample(); Date date = (Date) p.getExample();
return DateTimeFormatter.ISO_LOCAL_DATE.format(ZonedDateTime.ofInstant(date.toInstant(), UTC)); return DateTimeFormatter.ISO_LOCAL_DATE.format(ZonedDateTime.ofInstant(date.toInstant(), UTC));
} }
return escapeText(p.getExample().toString()); return escapeText(p.getExample().toString());
@ -1725,7 +1730,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
private void addAdditionalImports(CodegenModel model, CodegenComposedSchemas composedSchemas) { private void addAdditionalImports(CodegenModel model, CodegenComposedSchemas composedSchemas) {
if(composedSchemas == null) { if (composedSchemas == null) {
return; return;
} }
@ -1733,9 +1738,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
composedSchemas.getAnyOf(), composedSchemas.getAnyOf(),
composedSchemas.getOneOf(), composedSchemas.getOneOf(),
composedSchemas.getAllOf()); composedSchemas.getAllOf());
for(final List<CodegenProperty> propertyList : propertyLists){ for (final List<CodegenProperty> propertyList : propertyLists) {
if(propertyList == null) if (propertyList == null) {
{
continue; continue;
} }
for (CodegenProperty cp : propertyList) { for (CodegenProperty cp : propertyList) {
@ -1820,7 +1824,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
/** /**
* Remove annotations from the given data type string. * Remove annotations from the given data type string.
* * <p>
* For example: * For example:
* <ul> * <ul>
* <li>{@code @Min(0) @Max(10)Integer} -> {@code Integer}</li> * <li>{@code @Min(0) @Max(10)Integer} -> {@code Integer}</li>
@ -1996,9 +2000,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
private static String[] getAccepts(OpenAPI openAPIArg, Operation operation) { private static String[] getAccepts(OpenAPI openAPIArg, Operation operation) {
final Set<String> producesInfo = getProducesInfo(openAPIArg, operation); final Set<String> producesInfo = getProducesInfo(openAPIArg, operation);
if (producesInfo != null && !producesInfo.isEmpty()) { if (producesInfo != null && !producesInfo.isEmpty()) {
return producesInfo.toArray(new String[] {}); return producesInfo.toArray(new String[]{});
} }
return new String[] { "application/json" }; // default media type return new String[]{"application/json"}; // default media type
} }
@Override @Override
@ -2285,7 +2289,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// only process files with java extension // only process files with java extension
if ("java".equals(FilenameUtils.getExtension(file.toString()))) { if ("java".equals(FilenameUtils.getExtension(file.toString()))) {
this.executePostProcessor(new String[] {javaPostProcessFile, file.toString()}); this.executePostProcessor(new String[]{javaPostProcessFile, file.toString()});
} }
} }

View File

@ -49,7 +49,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
protected static final String X_MICROPROFILE_OPEN_API_RETURN_UNIQUE_ITEMS = "x-microprofile-open-api-return-unique-items"; protected static final String X_MICROPROFILE_OPEN_API_RETURN_UNIQUE_ITEMS = "x-microprofile-open-api-return-unique-items";
protected static final String X_MICROPROFILE_OPEN_API_SCHEMA_TYPE = "x-microprofile-open-api-schema-type"; protected static final String X_MICROPROFILE_OPEN_API_SCHEMA_TYPE = "x-microprofile-open-api-schema-type";
protected static final String SCHEMA_TYPE_ARRAY = "org.eclipse.microprofile.openapi.annotations.enums.SchemaType.ARRAY"; protected static final String SCHEMA_TYPE_ARRAY = "org.eclipse.microprofile.openapi.annotations.enums.SchemaType.ARRAY";
protected static final Map<String,String> ARRAY_OF_MICROPROFILE_OPEN_API_SCHEMA_TYPES; protected static final Map<String, String> ARRAY_OF_MICROPROFILE_OPEN_API_SCHEMA_TYPES;
static { static {
final Map<String, String> schemaTypes = new HashMap<>(); final Map<String, String> schemaTypes = new HashMap<>();
schemaTypes.put("integer", "org.eclipse.microprofile.openapi.annotations.enums.SchemaType.INTEGER"); schemaTypes.put("integer", "org.eclipse.microprofile.openapi.annotations.enums.SchemaType.INTEGER");
@ -96,7 +97,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC).defaultValue(implFolder)); cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC).defaultValue(implFolder));
cliOptions.add(new CliOption("title", "a title describing the application").defaultValue(title)); cliOptions.add(new CliOption("title", "a title describing the application").defaultValue(title));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations",useBeanValidation)); cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations", useBeanValidation));
cliOptions.add(new CliOption(SERVER_PORT, "The port on which the server should be started").defaultValue(serverPort)); cliOptions.add(new CliOption(SERVER_PORT, "The port on which the server should be started").defaultValue(serverPort));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames")); cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
} }

View File

@ -16,16 +16,24 @@
package org.openapitools.codegen.languages; package org.openapitools.codegen.languages;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.servers.Server;
import lombok.Setter; import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.openapitools.codegen.*; import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.ClientModificationFeature; import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
import org.openapitools.codegen.meta.features.ParameterFeature;
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.model.ModelsMap; import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.templating.mustache.EscapeChar;
import org.openapitools.codegen.utils.CamelizeOption;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -33,27 +41,8 @@ import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import static org.openapitools.codegen.utils.StringUtils.camelize; import static org.openapitools.codegen.utils.StringUtils.camelize;
import org.openapitools.codegen.utils.CamelizeOption;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache.Lambda;
import org.openapitools.codegen.templating.mustache.EscapeChar;
public abstract class AbstractJuliaCodegen extends DefaultCodegen { public abstract class AbstractJuliaCodegen extends DefaultCodegen {
protected final Logger LOGGER = LoggerFactory.getLogger(AbstractJuliaCodegen.class); protected final Logger LOGGER = LoggerFactory.getLogger(AbstractJuliaCodegen.class);
@ -419,9 +408,9 @@ public abstract class AbstractJuliaCodegen extends DefaultCodegen {
Object _default_obj = schema.getDefault(); Object _default_obj = schema.getDefault();
String _default; String _default;
if (_default_obj instanceof DateTime) { if (_default_obj instanceof DateTime) {
_default = DATE_TIME_FORMAT.format((DateTime)_default_obj); _default = DATE_TIME_FORMAT.format((DateTime) _default_obj);
} else if (_default_obj instanceof OffsetDateTime) { } else if (_default_obj instanceof OffsetDateTime) {
_default = OFFSET_DATE_TIME_FORMAT.format((OffsetDateTime)_default_obj); _default = OFFSET_DATE_TIME_FORMAT.format((OffsetDateTime) _default_obj);
} else { } else {
_default = _default_obj.toString(); _default = _default_obj.toString();
} }

View File

@ -363,7 +363,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
Schema<?> schema = unaliasSchema(p); Schema<?> schema = unaliasSchema(p);
Schema<?> target = ModelUtils.isGenerateAliasAsModel() ? p : schema; Schema<?> target = ModelUtils.isGenerateAliasAsModel() ? p : schema;
if (ModelUtils.isArraySchema(target)) { if (ModelUtils.isArraySchema(target)) {
Schema<?> items = ModelUtils.getSchemaItems( schema); Schema<?> items = ModelUtils.getSchemaItems(schema);
return getSchemaType(target) + "<" + getItemsTypeDeclaration(items) + ">"; return getSchemaType(target) + "<" + getItemsTypeDeclaration(items) + ">";
} else if (ModelUtils.isMapSchema(target)) { } else if (ModelUtils.isMapSchema(target)) {
// Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
@ -977,7 +977,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
// only process files with kt extension // only process files with kt extension
if ("kt".equals(FilenameUtils.getExtension(file.toString()))) { if ("kt".equals(FilenameUtils.getExtension(file.toString()))) {
this.executePostProcessor(new String[] {kotlinPostProcessFile, file.toString()}); this.executePostProcessor(new String[]{kotlinPostProcessFile, file.toString()});
} }
} }
@ -1012,18 +1012,15 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
return fixNumberValue(schema.getDefault().toString(), schema); return fixNumberValue(schema.getDefault().toString(), schema);
} }
} } else if (ModelUtils.isIntegerSchema(schema)) {
else if (ModelUtils.isIntegerSchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
return fixNumberValue(schema.getDefault().toString(), schema); return fixNumberValue(schema.getDefault().toString(), schema);
} }
} } else if (ModelUtils.isURISchema(schema)) {
else if (ModelUtils.isURISchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
return importMapping.get("URI") + ".create(\"" + schema.getDefault() + "\")"; return importMapping.get("URI") + ".create(\"" + schema.getDefault() + "\")";
} }
} } else if (ModelUtils.isArraySchema(schema)) {
else if (ModelUtils.isArraySchema(schema)) {
return toArrayDefaultValue(cp, schema); return toArrayDefaultValue(cp, schema);
} else if (ModelUtils.isStringSchema(schema)) { } else if (ModelUtils.isStringSchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {

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