From 7b5e5c8289895fdb300decf88693d6dca3280627 Mon Sep 17 00:00:00 2001 From: James Schubert Date: Mon, 30 Oct 2017 15:23:50 -0400 Subject: [PATCH 01/13] [csharp] Treat enum models consistently C# works differently from most languages in that enums are not considered objects. This means default(EnumType) will choose a default of the first enum option. This isn't desirable because it breaks the required = false functionality of swagger specs, which defines a property which isn't required to exist in the message body. Rather than force consumers to use enum values such as UNSPECIFIED, UNKNOWN, NOT_SET, etc... we can treat enums as primitives. This means any non-required enum will become Nullable regardless of whether it is defined as an inline enum or a referenced enum model. --- .../io/swagger/codegen/CodegenConstants.java | 8 + .../io/swagger/codegen/DefaultGenerator.java | 60 +++-- .../languages/AbstractCSharpCodegen.java | 63 ++++++ .../languages/CSharpClientCodegen.java | 6 - .../resources/csharp/modelGeneric.mustache | 14 +- .../codegen/AbstractIntegrationTest.java | 12 +- .../CsharpClientEnumRefIntegrationTest.java | 53 +++++ ...CsharpClientInlineEnumIntegrationTest.java | 53 +++++ .../codegen/csharp/CsharpModelEnumTest.java | 1 + .../testutils/IntegrationTestPathsConfig.java | 10 +- .../Model/MyClassWithOptionalEnum.cs | 206 ++++++++++++++++++ .../csharp/enum-inline-spec.json | 59 +++++ .../csharp/enum-inline.ignore | 9 + .../Model/MyClassWithOptionalEnum.cs | 156 +++++++++++++ .../src/IO.Swagger/Model/WeekDays.cs | 77 +++++++ .../csharp/enum-ref-spec.json | 62 ++++++ .../integrationtests/csharp/enum-ref.ignore | 9 + 17 files changed, 826 insertions(+), 32 deletions(-) create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientInlineEnumIntegrationTest.java create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-spec.json create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline.ignore create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-spec.json create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref.ignore diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 4dea75e8208..a650422f224 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -4,6 +4,14 @@ package io.swagger.codegen; * A class for storing constants that are used throughout the project. */ public class CodegenConstants { + public static final String APIS = "apis"; + public static final String MODELS = "models"; + public static final String SUPPORTING_FILES = "supportingFiles"; + public static final String MODEL_TESTS = "modelTests"; + public static final String MODEL_DOCS = "modelDocs"; + public static final String API_TESTS = "apiTests"; + public static final String API_DOCS = "apiDocs"; + public static final String API_PACKAGE = "apiPackage"; public static final String API_PACKAGE_DESC = "package for generated api classes"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 80033e12699..ccfdda11082 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -33,9 +33,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { private Boolean generateApiDocumentation = null; private Boolean generateModelTests = null; private Boolean generateModelDocumentation = null; + private Boolean generateSwaggerMetadata = true; private String basePath; private String basePathWithoutHost; private String contextPath; + private Map generatorPropertyDefaults = new HashMap<>(); @Override public Generator opts(ClientOptInput opts) { @@ -61,6 +63,31 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return this; } + public void setGenerateSwaggerMetadata(Boolean generateSwaggerMetadata) { + this.generateSwaggerMetadata = generateSwaggerMetadata; + } + + /** + * Set generator properties otherwise pulled from system properties. + * Useful for running tests in parallel without relying on System.properties. + * @param key The system property key + * @param value The system property value + */ + public void setGeneratorPropertyDefault(final String key, final String value) { + this.generatorPropertyDefaults.put(key, value); + } + + private Boolean getGeneratorPropertyDefaultSwitch(final String key, final Boolean defaultValue) { + String result = null; + if (this.generatorPropertyDefaults.containsKey(key)) { + result = this.generatorPropertyDefaults.get(key); + } + if (result != null) { + return Boolean.valueOf(result); + } + return defaultValue; + } + private String getScheme() { String scheme; if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { @@ -88,11 +115,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } private void configureGeneratorProperties() { - // allows generating only models by specifying a CSV of models to generate, or empty for all - generateApis = System.getProperty("apis") != null ? true : null; - generateModels = System.getProperty("models") != null ? true : null; - generateSupportingFiles = System.getProperty("supportingFiles") != null ? true : null; + generateApis = System.getProperty(CodegenConstants.APIS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.APIS, null); + generateModels = System.getProperty(CodegenConstants.MODELS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODELS, null); + generateSupportingFiles = System.getProperty(CodegenConstants.SUPPORTING_FILES) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.SUPPORTING_FILES, null); if (generateApis == null && generateModels == null && generateSupportingFiles == null) { // no specifics are set, generate everything @@ -110,10 +136,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } // model/api tests and documentation options rely on parent generate options (api or model) and no other options. // They default to true in all scenarios and can only be marked false explicitly - generateModelTests = System.getProperty("modelTests") != null ? Boolean.valueOf(System.getProperty("modelTests")) : true; - generateModelDocumentation = System.getProperty("modelDocs") != null ? Boolean.valueOf(System.getProperty("modelDocs")) : true; - generateApiTests = System.getProperty("apiTests") != null ? Boolean.valueOf(System.getProperty("apiTests")) : true; - generateApiDocumentation = System.getProperty("apiDocs") != null ? Boolean.valueOf(System.getProperty("apiDocs")) : true; + generateModelTests = System.getProperty(CodegenConstants.MODEL_TESTS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.MODEL_TESTS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODEL_TESTS, true); + generateModelDocumentation = System.getProperty(CodegenConstants.MODEL_DOCS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.MODEL_DOCS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODEL_DOCS, true); + generateApiTests = System.getProperty(CodegenConstants.API_TESTS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.API_TESTS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_TESTS, true); + generateApiDocumentation = System.getProperty(CodegenConstants.API_DOCS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.API_DOCS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_DOCS, true); // Additional properties added for tests to exclude references in project related files @@ -595,7 +621,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { final String swaggerCodegenIgnore = ".swagger-codegen-ignore"; String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore; File ignoreFile = new File(ignoreFileNameTarget); - if (!ignoreFile.exists()) { + if (generateSwaggerMetadata && !ignoreFile.exists()) { String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore; String ignoreFileContents = readResourceContents(ignoreFileNameSource); try { @@ -606,13 +632,15 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { files.add(ignoreFile); } - final String swaggerVersionMetadata = config.outputFolder() + File.separator + ".swagger-codegen" + File.separator + "VERSION"; - File swaggerVersionMetadataFile = new File(swaggerVersionMetadata); - try { - writeToFile(swaggerVersionMetadata, ImplementationVersion.read()); - files.add(swaggerVersionMetadataFile); - } catch (IOException e) { - throw new RuntimeException("Could not generate supporting file '" + swaggerVersionMetadata + "'", e); + if(generateSwaggerMetadata) { + final String swaggerVersionMetadata = config.outputFolder() + File.separator + ".swagger-codegen" + File.separator + "VERSION"; + File swaggerVersionMetadataFile = new File(swaggerVersionMetadata); + try { + writeToFile(swaggerVersionMetadata, ImplementationVersion.read()); + files.add(swaggerVersionMetadataFile); + } catch (IOException e) { + throw new RuntimeException("Could not generate supporting file '" + swaggerVersionMetadata + "'", e); + } } /* diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index bbd06e02421..c2dc53c205c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.utils.ModelUtils; import io.swagger.models.properties.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -296,6 +297,11 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); } + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + } + @Override public Map postProcessModels(Map objs) { List models = (List) objs.get("models"); @@ -309,12 +315,69 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if (var.name.equalsIgnoreCase(cm.name)) { var.name = "_" + var.name; } + + if(var.isEnum) { + // In C#, Enums are considered primitives because they're compiled to numerical types (int by default) + var.isPrimitiveType = true; + + // HACK: Consider Nullable as a container so we can properly handle unsupplied enum values as null. + var.isContainer = var.required; + } } } // process enum in models return postProcessModelsEnum(objs); } + @Override + public Map postProcessAllModels(Map objs) { + final Map processed = super.postProcessAllModels(objs); + postProcessEnumRefs(processed); + return processed; + } + + /** + * C# differs from other languages in that Enums are not _true_ objects; enums are compiled to integral types. + * So, in C#, an enum is considers more like a user-defined primitive. + * + * When working with enums, we can't always assume a RefModel is a nullable type (where default(YourType) == null), + * so this post processing runs through all models to find RefModel'd enums. Then, it runs through all vars and modifies + * those vars referencing RefModel'd enums to work the same as inlined enums rather than as objects. + * @param models + */ + private void postProcessEnumRefs(final Map models) { + Map enumRefs = new HashMap(); + for (Map.Entry entry : models.entrySet()) { + CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models); + if (model.isEnum) { + enumRefs.put(entry.getKey(), model); + } + } + + for (Map.Entry entry : models.entrySet()) { + String swaggerName = entry.getKey(); + CodegenModel model = ModelUtils.getModelByName(swaggerName, models); + if (model != null) { + for (CodegenProperty var : model.allVars) { + if (enumRefs.containsKey(var.datatype)) { + // Handle any enum properties referred to by $ref. + // This is different in C# than most other generators, because enums in C# are compiled to integral types, + // while enums in many other languages are true objects. + CodegenModel refModel = enumRefs.get(var.datatype); + var.allowableValues = refModel.allowableValues; + updateCodegenPropertyEnum(var); + + // We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. + var.isPrimitiveType = true; + var.isEnum = true; + } + } + } else { + LOGGER.warn("Expected to retrieve model %s by name, but no model was found. Check your -Dmodels inclusions.", swaggerName); + } + } + } + @Override public Map postProcessOperations(Map objs) { super.postProcessOperations(objs); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 69bee7bd9c9..5816ccd3ea6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -505,11 +505,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { this.packageGuid = packageGuid; } - @Override - public Map postProcessModels(Map objMap) { - return super.postProcessModels(objMap); - } - @Override public void postProcessParameter(CodegenParameter parameter) { postProcessPattern(parameter.pattern, parameter.vendorExtensions); @@ -522,7 +517,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { super.postProcessModelProperty(model, property); } - /* * The swagger pattern spec follows the Perl convention and style of modifiers. .NET * does not support this syntax directly so we need to convert the pattern to a .NET compatible diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 990818fd328..ef9d93b8e3b 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -12,16 +12,18 @@ {{>visibility}} partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}>{{^netStandard}}{{#validatable}}, IValidatableObject{{/validatable}}{{/netStandard}} { {{#vars}} - {{#isEnum}} -{{>modelInnerEnum}} - {{/isEnum}} {{#items.isEnum}} {{#items}} + {{^complexType}} {{>modelInnerEnum}} + {{/complexType}} {{/items}} {{/items.isEnum}} - {{/vars}} - {{#vars}} + {{#isEnum}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/isEnum}} {{#isEnum}} /// /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} @@ -30,7 +32,7 @@ /// {{description}} {{/description}} [DataMember(Name="{{baseName}}", EmitDefaultValue={{emitDefaultValue}})] - public {{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} { get; set; } + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}?{{/isContainer}} {{name}} { get; set; } {{/isEnum}} {{/vars}} {{#hasRequired}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java index e65340b55bf..846ef4446bd 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java @@ -3,6 +3,7 @@ package io.swagger.codegen; import static io.swagger.codegen.testutils.AssertFile.assertPathEqualsRecursively; import java.io.IOException; +import java.util.HashMap; import java.util.Map; import org.testng.annotations.Test; @@ -20,10 +21,19 @@ public abstract class AbstractIntegrationTest { protected abstract Map configProperties(); + protected Boolean generateSwaggerMetadata = true; + + protected Map systemPropertyOverrides = new HashMap<>(); + // @wing328: ignore for the time being until we fix the error with the integration test @Test(enabled = false) public void generatesCorrectDirectoryStructure() throws IOException { DefaultGenerator codeGen = new DefaultGenerator(); + codeGen.setGenerateSwaggerMetadata(generateSwaggerMetadata); + for (Map.Entry propertyOverride : systemPropertyOverrides.entrySet()) { + codeGen.setGeneratorPropertyDefault(propertyOverride.getKey(), propertyOverride.getValue()); + } + IntegrationTestPathsConfig integrationTestPathsConfig = getIntegrationTestPathsConfig(); String specContent = Files.readFile(integrationTestPathsConfig.getSpecPath().toFile()); @@ -31,7 +41,7 @@ public abstract class AbstractIntegrationTest { CodegenConfig codegenConfig = getCodegenConfig(); codegenConfig.setOutputDir(integrationTestPathsConfig.getOutputPath().toString()); - + codegenConfig.setIgnoreFilePathOverride(integrationTestPathsConfig.getIgnoreFilePath().toFile().toString()); ClientOpts clientOpts = new ClientOpts(); clientOpts.setProperties(configProperties()); ClientOptInput opts = new ClientOptInput() diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java new file mode 100644 index 00000000000..59df570bb19 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java @@ -0,0 +1,53 @@ +package io.swagger.codegen.csharp; + +import com.google.common.collect.ImmutableMap; +import io.swagger.codegen.AbstractIntegrationTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.CSharpClientCodegen; +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class CsharpClientEnumRefIntegrationTest extends AbstractIntegrationTest { + public CsharpClientEnumRefIntegrationTest() { + generateSwaggerMetadata = false; + + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + systemPropertyOverrides = builder + .put(CodegenConstants.APIS, Boolean.FALSE.toString()) + .put(CodegenConstants.MODELS, Boolean.TRUE.toString()) + .put(CodegenConstants.API_DOCS, Boolean.FALSE.toString()) + .put(CodegenConstants.MODEL_DOCS, Boolean.FALSE.toString()) + .put(CodegenConstants.API_TESTS, Boolean.FALSE.toString()) + .put(CodegenConstants.MODEL_TESTS, Boolean.FALSE.toString()) + .put(CodegenConstants.SUPPORTING_FILES, Boolean.FALSE.toString()) + .build(); + } + + @Override + protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { + return new IntegrationTestPathsConfig("csharp/enum-ref"); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return new CSharpClientCodegen(); + } + + @Override + protected Map configProperties() { + Map properties = new HashMap<>(); + properties.put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE.toString()); + return properties; + } + + // TODO: Remove this when super.generatesCorrectDirectoryStructure() is re-enabled. + @Test(description = "Verify csharp enums as ref properties") + public void test() throws IOException { + this.generatesCorrectDirectoryStructure(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientInlineEnumIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientInlineEnumIntegrationTest.java new file mode 100644 index 00000000000..d5825c0621a --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientInlineEnumIntegrationTest.java @@ -0,0 +1,53 @@ +package io.swagger.codegen.csharp; + +import com.google.common.collect.ImmutableMap; +import io.swagger.codegen.AbstractIntegrationTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.CSharpClientCodegen; +import io.swagger.codegen.testutils.IntegrationTestPathsConfig; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class CsharpClientInlineEnumIntegrationTest extends AbstractIntegrationTest { + public CsharpClientInlineEnumIntegrationTest() { + generateSwaggerMetadata = false; + + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + systemPropertyOverrides = builder + .put(CodegenConstants.APIS, Boolean.FALSE.toString()) + .put(CodegenConstants.MODELS, Boolean.TRUE.toString()) + .put(CodegenConstants.API_DOCS, Boolean.FALSE.toString()) + .put(CodegenConstants.MODEL_DOCS, Boolean.FALSE.toString()) + .put(CodegenConstants.API_TESTS, Boolean.FALSE.toString()) + .put(CodegenConstants.MODEL_TESTS, Boolean.FALSE.toString()) + .put(CodegenConstants.SUPPORTING_FILES, Boolean.FALSE.toString()) + .build(); + } + + @Override + protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { + return new IntegrationTestPathsConfig("csharp/enum-inline"); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return new CSharpClientCodegen(); + } + + @Override + protected Map configProperties() { + Map properties = new HashMap<>(); + properties.put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE.toString()); + return properties; + } + + // TODO: Remove this when super.generatesCorrectDirectoryStructure() is re-enabled. + @Test(description = "Verify csharp enums as ref properties") + public void test() throws IOException { + this.generatesCorrectDirectoryStructure(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java index 8a8b0a726b1..ae13bad0b36 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java @@ -10,6 +10,7 @@ import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.RefModel; import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java index 4335c69dd2d..bb08d0bce27 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java @@ -8,15 +8,17 @@ public class IntegrationTestPathsConfig { private final Path outputPath; private final Path specPath; private final Path expectedPath; + private final Path ignoreFilePath; public IntegrationTestPathsConfig(String location) { - this(location + "-spec.json", location + "-result", location + "-expected"); + this(location + "-spec.json", location + "-result", location + "-expected", location + ".ignore"); } - public IntegrationTestPathsConfig(String specLocation, String outputLocation, String expectedLocation) { + public IntegrationTestPathsConfig(String specLocation, String outputLocation, String expectedLocation, String ignoreFileLocation) { outputPath = INTEGRATION_TEST_PATH.resolve(outputLocation); expectedPath = INTEGRATION_TEST_PATH.resolve(expectedLocation); specPath = INTEGRATION_TEST_PATH.resolve(specLocation); + ignoreFilePath = INTEGRATION_TEST_PATH.resolve(ignoreFileLocation); } public Path getOutputPath() { @@ -30,4 +32,6 @@ public class IntegrationTestPathsConfig { public Path getExpectedPath() { return expectedPath; } -} \ No newline at end of file + + public Path getIgnoreFilePath() { return ignoreFilePath; } +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs new file mode 100644 index 00000000000..a15588f0d2d --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs @@ -0,0 +1,206 @@ +/* + * My title + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: 1 + * + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// MyClassWithOptionalEnum + /// + [DataContract] + public partial class MyClassWithOptionalEnum : IEquatable, IValidatableObject + { + /// + /// Gets or Sets Days + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum DaysEnum + { + + /// + /// Enum Sun for "sun" + /// + [EnumMember(Value = "sun")] + Sun, + + /// + /// Enum Mon for "mon" + /// + [EnumMember(Value = "mon")] + Mon, + + /// + /// Enum Tue for "tue" + /// + [EnumMember(Value = "tue")] + Tue, + + /// + /// Enum Wed for "wed" + /// + [EnumMember(Value = "wed")] + Wed, + + /// + /// Enum Thu for "thu" + /// + [EnumMember(Value = "thu")] + Thu, + + /// + /// Enum Fri for "fri" + /// + [EnumMember(Value = "fri")] + Fri, + + /// + /// Enum Sat for "sat" + /// + [EnumMember(Value = "sat")] + Sat + } + + /// + /// Gets or Sets Days + /// + [DataMember(Name="days", EmitDefaultValue=false)] + public DaysEnum? Days { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// Quarantine. + /// Grayware. + /// Days. + public MyClassWithOptionalEnum(bool? Quarantine = default(bool?), bool? Grayware = default(bool?), DaysEnum? Days = default(DaysEnum?)) + { + this.Quarantine = Quarantine; + this.Grayware = Grayware; + this.Days = Days; + } + + /// + /// Gets or Sets Quarantine + /// + [DataMember(Name="quarantine", EmitDefaultValue=false)] + public bool? Quarantine { get; set; } + + /// + /// Gets or Sets Grayware + /// + [DataMember(Name="grayware", EmitDefaultValue=false)] + public bool? Grayware { get; set; } + + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MyClassWithOptionalEnum {\n"); + sb.Append(" Quarantine: ").Append(Quarantine).Append("\n"); + sb.Append(" Grayware: ").Append(Grayware).Append("\n"); + sb.Append(" Days: ").Append(Days).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as MyClassWithOptionalEnum); + } + + /// + /// Returns true if MyClassWithOptionalEnum instances are equal + /// + /// Instance of MyClassWithOptionalEnum to be compared + /// Boolean + public bool Equals(MyClassWithOptionalEnum input) + { + if (input == null) + return false; + + return + ( + this.Quarantine == input.Quarantine || + (this.Quarantine != null && + this.Quarantine.Equals(input.Quarantine)) + ) && + ( + this.Grayware == input.Grayware || + (this.Grayware != null && + this.Grayware.Equals(input.Grayware)) + ) && + ( + this.Days == input.Days || + (this.Days != null && + this.Days.Equals(input.Days)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Quarantine != null) + hashCode = hashCode * 59 + this.Quarantine.GetHashCode(); + if (this.Grayware != null) + hashCode = hashCode * 59 + this.Grayware.GetHashCode(); + if (this.Days != null) + hashCode = hashCode * 59 + this.Days.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-spec.json new file mode 100644 index 00000000000..d3860aa3449 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-spec.json @@ -0,0 +1,59 @@ +{ + "swagger": "2.0", + "info": { + "version": "1", + "title": "My title" + }, + "host": "localhost:10010", + "basePath": "/", + "schemes": [ + "http", + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/": { + "get": { + "operationId": "getRoot", + "summary": "Root operation", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "200 OK Response" + } + } + } + } + }, + "definitions": { + "My_Class_With_Optional_Enum": { + "properties": { + "quarantine": { + "type": "boolean" + }, + "grayware": { + "type": "boolean" + }, + "days": { + "type": "string", + "enum": [ + "sun", + "mon", + "tue", + "wed", + "thu", + "fri", + "sat" + ] + } + } + } + } +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline.ignore b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline.ignore new file mode 100644 index 00000000000..48a88a03835 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline.ignore @@ -0,0 +1,9 @@ +!**/IO.Swagger/Model/*.cs +**/Api/ +**/Client/ +**/Properties +**/IO.Swagger.Test/ +**/* +*/* +.swagger-codegen/ +*/.* diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs new file mode 100644 index 00000000000..870174af6ec --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs @@ -0,0 +1,156 @@ +/* + * My title + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: 1 + * + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// MyClassWithOptionalEnum + /// + [DataContract] + public partial class MyClassWithOptionalEnum : IEquatable, IValidatableObject + { + /// + /// Gets or Sets Days + /// + [DataMember(Name="days", EmitDefaultValue=false)] + public WeekDays? Days { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// Quarantine. + /// Grayware. + /// Days. + public MyClassWithOptionalEnum(bool? Quarantine = default(bool?), bool? Grayware = default(bool?), WeekDays? Days = default(WeekDays?)) + { + this.Quarantine = Quarantine; + this.Grayware = Grayware; + this.Days = Days; + } + + /// + /// Gets or Sets Quarantine + /// + [DataMember(Name="quarantine", EmitDefaultValue=false)] + public bool? Quarantine { get; set; } + + /// + /// Gets or Sets Grayware + /// + [DataMember(Name="grayware", EmitDefaultValue=false)] + public bool? Grayware { get; set; } + + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MyClassWithOptionalEnum {\n"); + sb.Append(" Quarantine: ").Append(Quarantine).Append("\n"); + sb.Append(" Grayware: ").Append(Grayware).Append("\n"); + sb.Append(" Days: ").Append(Days).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as MyClassWithOptionalEnum); + } + + /// + /// Returns true if MyClassWithOptionalEnum instances are equal + /// + /// Instance of MyClassWithOptionalEnum to be compared + /// Boolean + public bool Equals(MyClassWithOptionalEnum input) + { + if (input == null) + return false; + + return + ( + this.Quarantine == input.Quarantine || + (this.Quarantine != null && + this.Quarantine.Equals(input.Quarantine)) + ) && + ( + this.Grayware == input.Grayware || + (this.Grayware != null && + this.Grayware.Equals(input.Grayware)) + ) && + ( + this.Days == input.Days || + (this.Days != null && + this.Days.Equals(input.Days)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Quarantine != null) + hashCode = hashCode * 59 + this.Quarantine.GetHashCode(); + if (this.Grayware != null) + hashCode = hashCode * 59 + this.Grayware.GetHashCode(); + if (this.Days != null) + hashCode = hashCode * 59 + this.Days.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs new file mode 100644 index 00000000000..ae81432d79b --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs @@ -0,0 +1,77 @@ +/* + * My title + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: 1 + * + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Defines WeekDays + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum WeekDays + { + + /// + /// Enum Sun for "sun" + /// + [EnumMember(Value = "sun")] + Sun, + + /// + /// Enum Mon for "mon" + /// + [EnumMember(Value = "mon")] + Mon, + + /// + /// Enum Tue for "tue" + /// + [EnumMember(Value = "tue")] + Tue, + + /// + /// Enum Wed for "wed" + /// + [EnumMember(Value = "wed")] + Wed, + + /// + /// Enum Thu for "thu" + /// + [EnumMember(Value = "thu")] + Thu, + + /// + /// Enum Fri for "fri" + /// + [EnumMember(Value = "fri")] + Fri, + + /// + /// Enum Sat for "sat" + /// + [EnumMember(Value = "sat")] + Sat + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-spec.json new file mode 100644 index 00000000000..2330bc718a3 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-spec.json @@ -0,0 +1,62 @@ +{ + "swagger": "2.0", + "info": { + "version": "1", + "title": "My title" + }, + "host": "localhost:10010", + "basePath": "/", + "schemes": [ + "http", + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/": { + "get": { + "operationId": "getRoot", + "summary": "Root operation", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "200 OK Response" + } + } + } + } + }, + "definitions": { + "WeekDays": { + "type": "string", + "enum": [ + "sun", + "mon", + "tue", + "wed", + "thu", + "fri", + "sat" + ] + }, + "My_Class_With_Optional_Enum": { + "properties": { + "quarantine": { + "type": "boolean" + }, + "grayware": { + "type": "boolean" + }, + "days": { + "$ref": "#/definitions/WeekDays" + } + } + } + } +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref.ignore b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref.ignore new file mode 100644 index 00000000000..48a88a03835 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref.ignore @@ -0,0 +1,9 @@ +!**/IO.Swagger/Model/*.cs +**/Api/ +**/Client/ +**/Properties +**/IO.Swagger.Test/ +**/* +*/* +.swagger-codegen/ +*/.* From 08c8773b500e64805034e2f990b1fe18d187b575 Mon Sep 17 00:00:00 2001 From: James Schubert Date: Tue, 31 Oct 2017 12:48:29 -0400 Subject: [PATCH 02/13] Categorizing C# integration test for enums as general --- .../CsharpClientEnumRefIntegrationTest.java | 2 +- ...entGeneralEnumSupportIntegrationTest.java} | 8 +- .../Model/MyClassWithOptionalEnum.cs | 0 .../src/IO.Swagger/Model/WeekDays.cs | 0 .../csharp/{ => general}/enum-ref-spec.json | 0 .../csharp/{ => general}/enum-ref.ignore | 0 .../Model/MyClassWithOptionalEnum.cs | 54 +---- .../Model/MyClassWithOptionalInlineEnum.cs | 206 ++++++++++++++++++ .../src/IO.Swagger/Model/WeekDays.cs | 77 +++++++ .../enum-support-spec.json} | 25 +++ .../enum-support.ignore} | 0 11 files changed, 315 insertions(+), 57 deletions(-) rename modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/{CsharpClientInlineEnumIntegrationTest.java => CsharpClientGeneralEnumSupportIntegrationTest.java} (84%) rename modules/swagger-codegen/src/test/resources/integrationtests/csharp/{ => general}/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs (100%) rename modules/swagger-codegen/src/test/resources/integrationtests/csharp/{ => general}/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs (100%) rename modules/swagger-codegen/src/test/resources/integrationtests/csharp/{ => general}/enum-ref-spec.json (100%) rename modules/swagger-codegen/src/test/resources/integrationtests/csharp/{ => general}/enum-ref.ignore (100%) rename modules/swagger-codegen/src/test/resources/integrationtests/csharp/{enum-inline-expected => general/enum-support-expected}/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs (78%) create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs rename modules/swagger-codegen/src/test/resources/integrationtests/csharp/{enum-inline-spec.json => general/enum-support-spec.json} (68%) rename modules/swagger-codegen/src/test/resources/integrationtests/csharp/{enum-inline.ignore => general/enum-support.ignore} (100%) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java index 59df570bb19..34cbc0da9c6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java @@ -30,7 +30,7 @@ public class CsharpClientEnumRefIntegrationTest extends AbstractIntegrationTest @Override protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("csharp/enum-ref"); + return new IntegrationTestPathsConfig("csharp/general/enum-ref"); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientInlineEnumIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientGeneralEnumSupportIntegrationTest.java similarity index 84% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientInlineEnumIntegrationTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientGeneralEnumSupportIntegrationTest.java index d5825c0621a..3dc36696119 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientInlineEnumIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientGeneralEnumSupportIntegrationTest.java @@ -12,8 +12,8 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -public class CsharpClientInlineEnumIntegrationTest extends AbstractIntegrationTest { - public CsharpClientInlineEnumIntegrationTest() { +public class CsharpClientGeneralEnumSupportIntegrationTest extends AbstractIntegrationTest { + public CsharpClientGeneralEnumSupportIntegrationTest() { generateSwaggerMetadata = false; ImmutableMap.Builder builder = new ImmutableMap.Builder(); @@ -30,7 +30,7 @@ public class CsharpClientInlineEnumIntegrationTest extends AbstractIntegrationTe @Override protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("csharp/enum-inline"); + return new IntegrationTestPathsConfig("csharp/general/enum-support"); } @Override @@ -46,7 +46,7 @@ public class CsharpClientInlineEnumIntegrationTest extends AbstractIntegrationTe } // TODO: Remove this when super.generatesCorrectDirectoryStructure() is re-enabled. - @Test(description = "Verify csharp enums as ref properties") + @Test(description = "Verify csharp enum support, generalized across supported C# versions.") public void test() throws IOException { this.generatesCorrectDirectoryStructure(); } diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs similarity index 100% rename from modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs rename to modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs similarity index 100% rename from modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs rename to modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-spec.json similarity index 100% rename from modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref-spec.json rename to modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-spec.json diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref.ignore b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref.ignore similarity index 100% rename from modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-ref.ignore rename to modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref.ignore diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs similarity index 78% rename from modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs rename to modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs index a15588f0d2d..870174af6ec 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs @@ -30,68 +30,18 @@ namespace IO.Swagger.Model [DataContract] public partial class MyClassWithOptionalEnum : IEquatable, IValidatableObject { - /// - /// Gets or Sets Days - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum DaysEnum - { - - /// - /// Enum Sun for "sun" - /// - [EnumMember(Value = "sun")] - Sun, - - /// - /// Enum Mon for "mon" - /// - [EnumMember(Value = "mon")] - Mon, - - /// - /// Enum Tue for "tue" - /// - [EnumMember(Value = "tue")] - Tue, - - /// - /// Enum Wed for "wed" - /// - [EnumMember(Value = "wed")] - Wed, - - /// - /// Enum Thu for "thu" - /// - [EnumMember(Value = "thu")] - Thu, - - /// - /// Enum Fri for "fri" - /// - [EnumMember(Value = "fri")] - Fri, - - /// - /// Enum Sat for "sat" - /// - [EnumMember(Value = "sat")] - Sat - } - /// /// Gets or Sets Days /// [DataMember(Name="days", EmitDefaultValue=false)] - public DaysEnum? Days { get; set; } + public WeekDays? Days { get; set; } /// /// Initializes a new instance of the class. /// /// Quarantine. /// Grayware. /// Days. - public MyClassWithOptionalEnum(bool? Quarantine = default(bool?), bool? Grayware = default(bool?), DaysEnum? Days = default(DaysEnum?)) + public MyClassWithOptionalEnum(bool? Quarantine = default(bool?), bool? Grayware = default(bool?), WeekDays? Days = default(WeekDays?)) { this.Quarantine = Quarantine; this.Grayware = Grayware; diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs new file mode 100644 index 00000000000..2146daae4de --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs @@ -0,0 +1,206 @@ +/* + * My title + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: 1 + * + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// MyClassWithOptionalInlineEnum + /// + [DataContract] + public partial class MyClassWithOptionalInlineEnum : IEquatable, IValidatableObject + { + /// + /// Gets or Sets Days + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum DaysEnum + { + + /// + /// Enum Sun for "sun" + /// + [EnumMember(Value = "sun")] + Sun, + + /// + /// Enum Mon for "mon" + /// + [EnumMember(Value = "mon")] + Mon, + + /// + /// Enum Tue for "tue" + /// + [EnumMember(Value = "tue")] + Tue, + + /// + /// Enum Wed for "wed" + /// + [EnumMember(Value = "wed")] + Wed, + + /// + /// Enum Thu for "thu" + /// + [EnumMember(Value = "thu")] + Thu, + + /// + /// Enum Fri for "fri" + /// + [EnumMember(Value = "fri")] + Fri, + + /// + /// Enum Sat for "sat" + /// + [EnumMember(Value = "sat")] + Sat + } + + /// + /// Gets or Sets Days + /// + [DataMember(Name="days", EmitDefaultValue=false)] + public DaysEnum? Days { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// Quarantine. + /// Grayware. + /// Days. + public MyClassWithOptionalInlineEnum(bool? Quarantine = default(bool?), bool? Grayware = default(bool?), DaysEnum? Days = default(DaysEnum?)) + { + this.Quarantine = Quarantine; + this.Grayware = Grayware; + this.Days = Days; + } + + /// + /// Gets or Sets Quarantine + /// + [DataMember(Name="quarantine", EmitDefaultValue=false)] + public bool? Quarantine { get; set; } + + /// + /// Gets or Sets Grayware + /// + [DataMember(Name="grayware", EmitDefaultValue=false)] + public bool? Grayware { get; set; } + + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MyClassWithOptionalInlineEnum {\n"); + sb.Append(" Quarantine: ").Append(Quarantine).Append("\n"); + sb.Append(" Grayware: ").Append(Grayware).Append("\n"); + sb.Append(" Days: ").Append(Days).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as MyClassWithOptionalInlineEnum); + } + + /// + /// Returns true if MyClassWithOptionalInlineEnum instances are equal + /// + /// Instance of MyClassWithOptionalInlineEnum to be compared + /// Boolean + public bool Equals(MyClassWithOptionalInlineEnum input) + { + if (input == null) + return false; + + return + ( + this.Quarantine == input.Quarantine || + (this.Quarantine != null && + this.Quarantine.Equals(input.Quarantine)) + ) && + ( + this.Grayware == input.Grayware || + (this.Grayware != null && + this.Grayware.Equals(input.Grayware)) + ) && + ( + this.Days == input.Days || + (this.Days != null && + this.Days.Equals(input.Days)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Quarantine != null) + hashCode = hashCode * 59 + this.Quarantine.GetHashCode(); + if (this.Grayware != null) + hashCode = hashCode * 59 + this.Grayware.GetHashCode(); + if (this.Days != null) + hashCode = hashCode * 59 + this.Days.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs new file mode 100644 index 00000000000..ae81432d79b --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs @@ -0,0 +1,77 @@ +/* + * My title + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: 1 + * + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Defines WeekDays + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum WeekDays + { + + /// + /// Enum Sun for "sun" + /// + [EnumMember(Value = "sun")] + Sun, + + /// + /// Enum Mon for "mon" + /// + [EnumMember(Value = "mon")] + Mon, + + /// + /// Enum Tue for "tue" + /// + [EnumMember(Value = "tue")] + Tue, + + /// + /// Enum Wed for "wed" + /// + [EnumMember(Value = "wed")] + Wed, + + /// + /// Enum Thu for "thu" + /// + [EnumMember(Value = "thu")] + Thu, + + /// + /// Enum Fri for "fri" + /// + [EnumMember(Value = "fri")] + Fri, + + /// + /// Enum Sat for "sat" + /// + [EnumMember(Value = "sat")] + Sat + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-spec.json similarity index 68% rename from modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-spec.json rename to modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-spec.json index d3860aa3449..ac230b1c5b8 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline-spec.json +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-spec.json @@ -33,7 +33,32 @@ } }, "definitions": { + "WeekDays": { + "type": "string", + "enum": [ + "sun", + "mon", + "tue", + "wed", + "thu", + "fri", + "sat" + ] + }, "My_Class_With_Optional_Enum": { + "properties": { + "quarantine": { + "type": "boolean" + }, + "grayware": { + "type": "boolean" + }, + "days": { + "$ref": "#/definitions/WeekDays" + } + } + }, + "My_Class_With_Optional_Inline_Enum": { "properties": { "quarantine": { "type": "boolean" diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline.ignore b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support.ignore similarity index 100% rename from modules/swagger-codegen/src/test/resources/integrationtests/csharp/enum-inline.ignore rename to modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support.ignore From 8be610b9a44a5acd1c28daaff61328044cdd7992 Mon Sep 17 00:00:00 2001 From: James Schubert Date: Tue, 31 Oct 2017 12:49:50 -0400 Subject: [PATCH 03/13] [csharp] Remove enum-ref integration test --- .../CsharpClientEnumRefIntegrationTest.java | 53 ------ .../Model/MyClassWithOptionalEnum.cs | 156 ------------------ .../src/IO.Swagger/Model/WeekDays.cs | 77 --------- .../csharp/general/enum-ref-spec.json | 62 ------- .../csharp/general/enum-ref.ignore | 9 - 5 files changed, 357 deletions(-) delete mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java delete mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs delete mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs delete mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-spec.json delete mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref.ignore diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java deleted file mode 100644 index 34cbc0da9c6..00000000000 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpClientEnumRefIntegrationTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.swagger.codegen.csharp; - -import com.google.common.collect.ImmutableMap; -import io.swagger.codegen.AbstractIntegrationTest; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.languages.CSharpClientCodegen; -import io.swagger.codegen.testutils.IntegrationTestPathsConfig; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class CsharpClientEnumRefIntegrationTest extends AbstractIntegrationTest { - public CsharpClientEnumRefIntegrationTest() { - generateSwaggerMetadata = false; - - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - systemPropertyOverrides = builder - .put(CodegenConstants.APIS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODELS, Boolean.TRUE.toString()) - .put(CodegenConstants.API_DOCS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODEL_DOCS, Boolean.FALSE.toString()) - .put(CodegenConstants.API_TESTS, Boolean.FALSE.toString()) - .put(CodegenConstants.MODEL_TESTS, Boolean.FALSE.toString()) - .put(CodegenConstants.SUPPORTING_FILES, Boolean.FALSE.toString()) - .build(); - } - - @Override - protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("csharp/general/enum-ref"); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return new CSharpClientCodegen(); - } - - @Override - protected Map configProperties() { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE.toString()); - return properties; - } - - // TODO: Remove this when super.generatesCorrectDirectoryStructure() is re-enabled. - @Test(description = "Verify csharp enums as ref properties") - public void test() throws IOException { - this.generatesCorrectDirectoryStructure(); - } -} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs deleted file mode 100644 index 870174af6ec..00000000000 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/MyClassWithOptionalEnum.cs +++ /dev/null @@ -1,156 +0,0 @@ -/* - * My title - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1 - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; - -namespace IO.Swagger.Model -{ - /// - /// MyClassWithOptionalEnum - /// - [DataContract] - public partial class MyClassWithOptionalEnum : IEquatable, IValidatableObject - { - /// - /// Gets or Sets Days - /// - [DataMember(Name="days", EmitDefaultValue=false)] - public WeekDays? Days { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// Quarantine. - /// Grayware. - /// Days. - public MyClassWithOptionalEnum(bool? Quarantine = default(bool?), bool? Grayware = default(bool?), WeekDays? Days = default(WeekDays?)) - { - this.Quarantine = Quarantine; - this.Grayware = Grayware; - this.Days = Days; - } - - /// - /// Gets or Sets Quarantine - /// - [DataMember(Name="quarantine", EmitDefaultValue=false)] - public bool? Quarantine { get; set; } - - /// - /// Gets or Sets Grayware - /// - [DataMember(Name="grayware", EmitDefaultValue=false)] - public bool? Grayware { get; set; } - - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class MyClassWithOptionalEnum {\n"); - sb.Append(" Quarantine: ").Append(Quarantine).Append("\n"); - sb.Append(" Grayware: ").Append(Grayware).Append("\n"); - sb.Append(" Days: ").Append(Days).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return this.Equals(input as MyClassWithOptionalEnum); - } - - /// - /// Returns true if MyClassWithOptionalEnum instances are equal - /// - /// Instance of MyClassWithOptionalEnum to be compared - /// Boolean - public bool Equals(MyClassWithOptionalEnum input) - { - if (input == null) - return false; - - return - ( - this.Quarantine == input.Quarantine || - (this.Quarantine != null && - this.Quarantine.Equals(input.Quarantine)) - ) && - ( - this.Grayware == input.Grayware || - (this.Grayware != null && - this.Grayware.Equals(input.Grayware)) - ) && - ( - this.Days == input.Days || - (this.Days != null && - this.Days.Equals(input.Days)) - ); - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Quarantine != null) - hashCode = hashCode * 59 + this.Quarantine.GetHashCode(); - if (this.Grayware != null) - hashCode = hashCode * 59 + this.Grayware.GetHashCode(); - if (this.Days != null) - hashCode = hashCode * 59 + this.Days.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs deleted file mode 100644 index ae81432d79b..00000000000 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-expected/src/IO.Swagger/Model/WeekDays.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * My title - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1 - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; - -namespace IO.Swagger.Model -{ - /// - /// Defines WeekDays - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum WeekDays - { - - /// - /// Enum Sun for "sun" - /// - [EnumMember(Value = "sun")] - Sun, - - /// - /// Enum Mon for "mon" - /// - [EnumMember(Value = "mon")] - Mon, - - /// - /// Enum Tue for "tue" - /// - [EnumMember(Value = "tue")] - Tue, - - /// - /// Enum Wed for "wed" - /// - [EnumMember(Value = "wed")] - Wed, - - /// - /// Enum Thu for "thu" - /// - [EnumMember(Value = "thu")] - Thu, - - /// - /// Enum Fri for "fri" - /// - [EnumMember(Value = "fri")] - Fri, - - /// - /// Enum Sat for "sat" - /// - [EnumMember(Value = "sat")] - Sat - } - -} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-spec.json deleted file mode 100644 index 2330bc718a3..00000000000 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref-spec.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1", - "title": "My title" - }, - "host": "localhost:10010", - "basePath": "/", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/": { - "get": { - "operationId": "getRoot", - "summary": "Root operation", - "produces": [ - "application/json" - ], - "responses": { - "200": { - "description": "200 OK Response" - } - } - } - } - }, - "definitions": { - "WeekDays": { - "type": "string", - "enum": [ - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - ] - }, - "My_Class_With_Optional_Enum": { - "properties": { - "quarantine": { - "type": "boolean" - }, - "grayware": { - "type": "boolean" - }, - "days": { - "$ref": "#/definitions/WeekDays" - } - } - } - } -} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref.ignore b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref.ignore deleted file mode 100644 index 48a88a03835..00000000000 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-ref.ignore +++ /dev/null @@ -1,9 +0,0 @@ -!**/IO.Swagger/Model/*.cs -**/Api/ -**/Client/ -**/Properties -**/IO.Swagger.Test/ -**/* -*/* -.swagger-codegen/ -*/.* From 72b9ab6cab137a578ebefebd6796eb939ec10081 Mon Sep 17 00:00:00 2001 From: James Schubert Date: Tue, 31 Oct 2017 14:17:13 -0400 Subject: [PATCH 04/13] [csharp] Clean up general enum support integration test, validate different enum usage cases. --- .../io/swagger/codegen/DefaultGenerator.java | 8 + .../languages/AbstractCSharpCodegen.java | 14 +- .../resources/csharp/modelGeneric.mustache | 4 +- ...yClassWithInvalidRequiredEnumUsageOnRef.cs | 140 +++++++++++ .../Model/MyClassWithRequiredInlineEnum.cs | 219 ++++++++++++++++++ .../csharp/general/enum-support-spec.json | 41 ++++ .../csharp/general/enum-support.sh | 14 ++ 7 files changed, 430 insertions(+), 10 deletions(-) create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithInvalidRequiredEnumUsageOnRef.cs create mode 100644 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs create mode 100755 modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support.sh diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index ccfdda11082..2c166e69577 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -63,6 +63,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return this; } + /** + * Programmatically disable the output of .swagger-codegen/VERSION, .swagger-codegen-ignore, + * or other metadata files used by Swagger Codegen. + * @param generateSwaggerMetadata true: enable outputs, false: disable outputs + */ + @SuppressWarnings("WeakerAccess") public void setGenerateSwaggerMetadata(Boolean generateSwaggerMetadata) { this.generateSwaggerMetadata = generateSwaggerMetadata; } @@ -73,6 +79,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { * @param key The system property key * @param value The system property value */ + @SuppressWarnings("WeakerAccess") public void setGeneratorPropertyDefault(final String key, final String value) { this.generatorPropertyDefaults.put(key, value); } @@ -116,6 +123,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { private void configureGeneratorProperties() { // allows generating only models by specifying a CSV of models to generate, or empty for all + // NOTE: Boolean.TRUE is required below rather than `true` because of JVM boxing constraints and type inference. generateApis = System.getProperty(CodegenConstants.APIS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.APIS, null); generateModels = System.getProperty(CodegenConstants.MODELS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODELS, null); generateSupportingFiles = System.getProperty(CodegenConstants.SUPPORTING_FILES) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.SUPPORTING_FILES, null); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index c2dc53c205c..243c75d8bd1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -315,20 +315,18 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if (var.name.equalsIgnoreCase(cm.name)) { var.name = "_" + var.name; } - - if(var.isEnum) { - // In C#, Enums are considered primitives because they're compiled to numerical types (int by default) - var.isPrimitiveType = true; - - // HACK: Consider Nullable as a container so we can properly handle unsupplied enum values as null. - var.isContainer = var.required; - } } } // process enum in models return postProcessModelsEnum(objs); } + /** + * Invoked by {@link DefaultGenerator} after all models have been post-processed, allowing for a last pass of codegen-specific model cleanup. + * + * @param objs Current state of codegen object model. + * @return An in-place modified state of the codegen object model. + */ @Override public Map postProcessAllModels(Map objs) { final Map processed = super.postProcessAllModels(objs); diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index ef9d93b8e3b..74d2bddc1e8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -32,7 +32,7 @@ /// {{description}} {{/description}} [DataMember(Name="{{baseName}}", EmitDefaultValue={{emitDefaultValue}})] - public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}?{{/isContainer}} {{name}} { get; set; } + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } {{/isEnum}} {{/vars}} {{#hasRequired}} @@ -55,7 +55,7 @@ {{#hasOnlyReadOnly}} [JsonConstructorAttribute] {{/hasOnlyReadOnly}} - public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}){{#parent}} : base({{#parentVars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/parentVars}}){{/parent}} + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}} {{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}){{#parent}} : base({{#parentVars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/parentVars}}){{/parent}} { {{#vars}} {{^isInherited}} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithInvalidRequiredEnumUsageOnRef.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithInvalidRequiredEnumUsageOnRef.cs new file mode 100644 index 00000000000..2a9a895ecb2 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithInvalidRequiredEnumUsageOnRef.cs @@ -0,0 +1,140 @@ +/* + * My title + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: 1 + * + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// Invalid use of required on $ref enum, per Swagger 2.0 spec: Any members other than '$ref' in a JSON Reference object SHALL be ignored. See My_Class_With_Required_Inline_Enum for appropriate usage. + /// + [DataContract] + public partial class MyClassWithInvalidRequiredEnumUsageOnRef : IEquatable, IValidatableObject + { + /// + /// Gets or Sets Days + /// + [DataMember(Name="days", EmitDefaultValue=false)] + public WeekDays? Days { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// First. + /// Days. + public MyClassWithInvalidRequiredEnumUsageOnRef(bool? First = default(bool?), WeekDays? Days = default(WeekDays?)) + { + this.First = First; + this.Days = Days; + } + + /// + /// Gets or Sets First + /// + [DataMember(Name="first", EmitDefaultValue=false)] + public bool? First { get; set; } + + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MyClassWithInvalidRequiredEnumUsageOnRef {\n"); + sb.Append(" First: ").Append(First).Append("\n"); + sb.Append(" Days: ").Append(Days).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as MyClassWithInvalidRequiredEnumUsageOnRef); + } + + /// + /// Returns true if MyClassWithInvalidRequiredEnumUsageOnRef instances are equal + /// + /// Instance of MyClassWithInvalidRequiredEnumUsageOnRef to be compared + /// Boolean + public bool Equals(MyClassWithInvalidRequiredEnumUsageOnRef input) + { + if (input == null) + return false; + + return + ( + this.First == input.First || + (this.First != null && + this.First.Equals(input.First)) + ) && + ( + this.Days == input.Days || + (this.Days != null && + this.Days.Equals(input.Days)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.First != null) + hashCode = hashCode * 59 + this.First.GetHashCode(); + if (this.Days != null) + hashCode = hashCode * 59 + this.Days.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs new file mode 100644 index 00000000000..fb43dccce3f --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs @@ -0,0 +1,219 @@ +/* + * My title + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: 1 + * + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; +using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; + +namespace IO.Swagger.Model +{ + /// + /// MyClassWithRequiredInlineEnum + /// + [DataContract] + public partial class MyClassWithRequiredInlineEnum : IEquatable, IValidatableObject + { + /// + /// Gets or Sets Days + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum DaysEnum + { + + /// + /// Enum Sun for "sun" + /// + [EnumMember(Value = "sun")] + Sun, + + /// + /// Enum Mon for "mon" + /// + [EnumMember(Value = "mon")] + Mon, + + /// + /// Enum Tue for "tue" + /// + [EnumMember(Value = "tue")] + Tue, + + /// + /// Enum Wed for "wed" + /// + [EnumMember(Value = "wed")] + Wed, + + /// + /// Enum Thu for "thu" + /// + [EnumMember(Value = "thu")] + Thu, + + /// + /// Enum Fri for "fri" + /// + [EnumMember(Value = "fri")] + Fri, + + /// + /// Enum Sat for "sat" + /// + [EnumMember(Value = "sat")] + Sat + } + + /// + /// Gets or Sets Days + /// + [DataMember(Name="days", EmitDefaultValue=false)] + public DaysEnum Days { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected MyClassWithRequiredInlineEnum() { } + /// + /// Initializes a new instance of the class. + /// + /// Quarantine. + /// Grayware. + /// Days (required). + public MyClassWithRequiredInlineEnum(bool? Quarantine = default(bool?), bool? Grayware = default(bool?), DaysEnum Days = default(DaysEnum)) + { + // to ensure "Days" is required (not null) + if (Days == null) + { + throw new InvalidDataException("Days is a required property for MyClassWithRequiredInlineEnum and cannot be null"); + } + else + { + this.Days = Days; + } + this.Quarantine = Quarantine; + this.Grayware = Grayware; + } + + /// + /// Gets or Sets Quarantine + /// + [DataMember(Name="quarantine", EmitDefaultValue=false)] + public bool? Quarantine { get; set; } + + /// + /// Gets or Sets Grayware + /// + [DataMember(Name="grayware", EmitDefaultValue=false)] + public bool? Grayware { get; set; } + + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MyClassWithRequiredInlineEnum {\n"); + sb.Append(" Quarantine: ").Append(Quarantine).Append("\n"); + sb.Append(" Grayware: ").Append(Grayware).Append("\n"); + sb.Append(" Days: ").Append(Days).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as MyClassWithRequiredInlineEnum); + } + + /// + /// Returns true if MyClassWithRequiredInlineEnum instances are equal + /// + /// Instance of MyClassWithRequiredInlineEnum to be compared + /// Boolean + public bool Equals(MyClassWithRequiredInlineEnum input) + { + if (input == null) + return false; + + return + ( + this.Quarantine == input.Quarantine || + (this.Quarantine != null && + this.Quarantine.Equals(input.Quarantine)) + ) && + ( + this.Grayware == input.Grayware || + (this.Grayware != null && + this.Grayware.Equals(input.Grayware)) + ) && + ( + this.Days == input.Days || + (this.Days != null && + this.Days.Equals(input.Days)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Quarantine != null) + hashCode = hashCode * 59 + this.Quarantine.GetHashCode(); + if (this.Grayware != null) + hashCode = hashCode * 59 + this.Grayware.GetHashCode(); + if (this.Days != null) + hashCode = hashCode * 59 + this.Days.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-spec.json b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-spec.json index ac230b1c5b8..99f0dba3974 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-spec.json +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-spec.json @@ -58,6 +58,23 @@ } } }, + + "My_Class_With_Invalid_Required_Enum_Usage_On_Ref": { + "description": "Invalid use of required on $ref enum, per Swagger 2.0 spec: Any members other than '$ref' in a JSON Reference object SHALL be ignored. See My_Class_With_Required_Inline_Enum for appropriate usage.", + "properties": { + "first": { + "type": "boolean" + }, + "days": { + "$ref": "#/definitions/WeekDays", + "required": true + }, + "second": { + "type": "int" + } + } + }, + "My_Class_With_Optional_Inline_Enum": { "properties": { "quarantine": { @@ -79,6 +96,30 @@ ] } } + }, + + "My_Class_With_Required_Inline_Enum": { + "required": [ "days" ], + "properties": { + "quarantine": { + "type": "boolean" + }, + "grayware": { + "type": "boolean" + }, + "days": { + "type": "string", + "enum": [ + "sun", + "mon", + "tue", + "wed", + "thu", + "fri", + "sat" + ] + } + } } } } diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support.sh b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support.sh new file mode 100755 index 00000000000..896022ab737 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +set -euo pipefail + +declare opts="-DdebugModels -Dproject -Dmodels -DmodelTests=false -DmodelDocs=false $JAVA_OPTS" +declare curdir=$(cd $(dirname "${BASH_SOURCE}") && pwd) + +# NOTE: This is sensitive to the location of this script. +declare clijar=${SWAGGER_CODEGEN_CLI_JAR:-$(cd $curdir && cd ../../../../../../../swagger-codegen-cli/target/ && echo $PWD)/swagger-codegen-cli.jar} + +exec \java ${opts} -jar ${clijar} generate \ + -i enum-support-spec.json -l csharp \ + --additional-properties targetFramework=v4.5 \ + -o enum-support-expected; From 1058728777b64acc11dc2e109758e2c3a2bf0592 Mon Sep 17 00:00:00 2001 From: James Schubert Date: Sat, 4 Nov 2017 17:22:23 -0400 Subject: [PATCH 05/13] [csharp] Clean up ref/inner enum struture Enums defines as ref models have a different object structure (CodegenModel) than those defined as inner enums (CodegenProperty). To make these look as similar as possible, we walk all ref model enums and reassign enumVars with the same properties inherited from the top level CodegenProperty so CodegenModel enums can use the same templates as inner enums. --- .../io/swagger/codegen/DefaultCodegen.java | 2 + .../languages/AbstractCSharpCodegen.java | 132 ++++++++++++++---- .../languages/CSharpClientCodegen.java | 17 +-- .../main/resources/csharp/enumClass.mustache | 17 --- .../main/resources/csharp/modelEnum.mustache | 12 +- .../resources/csharp/modelInnerEnum.mustache | 12 +- .../Model/MyClassWithOptionalInlineEnum.cs | 16 +-- .../Model/MyClassWithRequiredInlineEnum.cs | 16 +-- .../src/IO.Swagger/Model/WeekDays.cs | 16 ++- 9 files changed, 146 insertions(+), 94 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 2e8b0ebab5b..c80f2373bff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1955,6 +1955,8 @@ public class DefaultCodegen { if (property.defaultValue != null) { property.defaultValue = property.defaultValue.replace(baseItem.baseType, toEnumName(baseItem)); } + + updateCodegenPropertyEnum(property); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 243c75d8bd1..a97545615e3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -1,5 +1,7 @@ package io.swagger.codegen.languages; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; import io.swagger.codegen.*; import io.swagger.codegen.utils.ModelUtils; import io.swagger.models.properties.*; @@ -8,6 +10,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.io.IOException; +import java.io.Writer; import java.util.*; public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig { @@ -343,6 +347,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co * those vars referencing RefModel'd enums to work the same as inlined enums rather than as objects. * @param models */ + @SuppressWarnings({ "unchecked" }) private void postProcessEnumRefs(final Map models) { Map enumRefs = new HashMap(); for (Map.Entry entry : models.entrySet()) { @@ -354,6 +359,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co for (Map.Entry entry : models.entrySet()) { String swaggerName = entry.getKey(); + CodegenModel model = ModelUtils.getModelByName(swaggerName, models); if (model != null) { for (CodegenProperty var : model.allVars) { @@ -363,11 +369,57 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // while enums in many other languages are true objects. CodegenModel refModel = enumRefs.get(var.datatype); var.allowableValues = refModel.allowableValues; + var.isEnum = true; + updateCodegenPropertyEnum(var); - // We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. + // We do this after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. var.isPrimitiveType = true; - var.isEnum = true; + } + } + + // We're looping all models here. + if (model.isEnum) { + // We now need to make allowableValues.enumVars look like the context of CodegenProperty + Boolean isString = false; + Boolean isInteger = false; + Boolean isLong = false; + Boolean isByte = false; + + if (model.dataType.startsWith("byte")) { + // C# Actually supports byte and short enums, swagger spec only supports byte. + isByte = true; + model.vendorExtensions.put("x-enum-byte", true); + } else if (model.dataType.startsWith("int32")) { + isInteger = true; + model.vendorExtensions.put("x-enum-integer", true); + } else if (model.dataType.startsWith("int64")) { + isLong = true; + model.vendorExtensions.put("x-enum-long", true); + } else { + // C# doesn't support non-integral enums, so we need to treat everything else as strings (e.g. to not lose precision or data integrity) + isString = true; + model.vendorExtensions.put("x-enum-string", true); + } + + // Since we iterate enumVars for modelnnerEnum and enumClass templates, and CodegenModel is missing some of CodegenProperty's properties, + // we can take advantage of Mustache's contextual lookup to add the same "properties" to the model's enumVars scope rather than CodegenProperty's scope. + List> enumVars = (ArrayList>)model.allowableValues.get("enumVars"); + List> newEnumVars = new ArrayList>(); + for (Map enumVar : enumVars) { + Map mixedVars = new HashMap(); + mixedVars.putAll(enumVar); + + mixedVars.put("isString", isString); + mixedVars.put("isLong", isLong); + mixedVars.put("isInteger", isInteger); + mixedVars.put("isByte", isByte); + + newEnumVars.add(mixedVars); + } + + if (!newEnumVars.isEmpty()) { + model.allowableValues.put("enumVars", newEnumVars); } } } else { @@ -376,6 +428,42 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co } } + /** + * Update codegen property's enum by adding "enumVars" (with name and value) + * + * @param var list of CodegenProperty + */ + @Override + public void updateCodegenPropertyEnum(CodegenProperty var) { + if (var.vendorExtensions == null) { + var.vendorExtensions = new HashMap<>(); + } + + super.updateCodegenPropertyEnum(var); + + // Because C# uses nullable primitives for datatype, and datatype is used in DefaultCodegen for determining enum-ness, guard against weirdness here. + if (var.isEnum) { + if ("byte".equals(var.dataFormat)) {// C# Actually supports byte and short enums. + var.vendorExtensions.put("x-enum-byte", true); + var.isString = false; + var.isLong = false; + var.isInteger = false; + } else if ("int32".equals(var.dataFormat)) { + var.isInteger = true; + var.isString = false; + var.isLong = false; + } else if ("int64".equals(var.dataFormat)) { + var.isLong = true; + var.isString = false; + var.isInteger = false; + } else {// C# doesn't support non-integral enums, so we need to treat everything else as strings (e.g. to not lose precision or data integrity) + var.isString = true; + var.isInteger = false; + var.isLong = false; + } + } + } + @Override public Map postProcessOperations(Map objs) { super.postProcessOperations(objs); @@ -746,6 +834,19 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co this.interfacePrefix = interfacePrefix; } + @Override + public String toEnumValue(String value, String datatype) { + // C# only supports enums as literals for int, int?, long, long?, byte, and byte?. All else must be treated as strings. + // Per: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // but we're not supporting unsigned integral types or shorts. + if(datatype.startsWith("int") || datatype.startsWith("long") || datatype.startsWith("byte")) { + return value; + } + + return escapeText(value); + } + @Override public String toEnumVarName(String name, String datatype) { if (name.length() == 0) { @@ -776,32 +877,6 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co return sanitizeName(camelize(property.name)) + "Enum"; } - /* - @Override - public String toEnumName(CodegenProperty property) { - String enumName = sanitizeName(property.name); - if (!StringUtils.isEmpty(modelNamePrefix)) { - enumName = modelNamePrefix + "_" + enumName; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - enumName = enumName + "_" + modelNameSuffix; - } - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(enumName)) { - LOGGER.warn(enumName + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + enumName)); - enumName = "model_" + enumName; // e.g. return => ModelReturn (after camelize) - } - - if (enumName.matches("\\d.*")) { // starts with number - return "_" + enumName; - } else { - return enumName; - } - } - */ - public String testPackageName() { return this.packageName + ".Test"; } @@ -816,5 +891,4 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*").replace("--", "- -"); } - } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 5816ccd3ea6..b40bdff2a9c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -611,19 +611,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { return codegenModel; } - @Override - public String toEnumValue(String value, String datatype) { - if ("int?".equalsIgnoreCase(datatype) || "long?".equalsIgnoreCase(datatype) || - "double?".equalsIgnoreCase(datatype) || "float?".equalsIgnoreCase(datatype)) { - return value; - } else if ("float?".equalsIgnoreCase(datatype)) { - // for float in C#, append "f". e.g. 3.14 => 3.14f - return value + "f"; - } else { - return "\"" + escapeText(value) + "\""; - } - } - @Override public String toEnumVarName(String value, String datatype) { if (value.length() == 0) { @@ -636,8 +623,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { } // number - if ("int?".equals(datatype) || "long?".equals(datatype) || - "double?".equals(datatype) || "float?".equals(datatype)) { + if(datatype.startsWith("int") || datatype.startsWith("long") || + datatype.startsWith("double") || datatype.startsWith("float")) { String varName = "NUMBER_" + value; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); diff --git a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache deleted file mode 100644 index d8d5d4185dd..00000000000 --- a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache +++ /dev/null @@ -1,17 +0,0 @@ - /// - /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} - /// - {{#description}} - /// {{description}} - {{/description}} - [JsonConverter(typeof(StringEnumConverter))] - {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} - { - {{#allowableValues}}{{#enumVars}} - /// - /// Enum {{name}} for {{{value}}} - /// - [EnumMember(Value = {{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isFloat}}"{{/isFloat}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isFloat}}"{{/isFloat}})] - {{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^-last}}, - {{/-last}}{{/enumVars}}{{/allowableValues}} - } diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache index 64e50883f8d..9d91ab60e0e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache @@ -4,14 +4,16 @@ {{#description}} /// {{description}} {{/description}} + {{#allowableValues}}{{#enumVars}}{{#-first}}{{#isString}} [JsonConverter(typeof(StringEnumConverter))] - {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{/isString}}{{/-first}}{{/enumVars}}{{/allowableValues}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} { {{#allowableValues}}{{#enumVars}} /// - /// Enum {{name}} for {{{value}}} + /// Enum {{name}} for value: {{{value}}} /// - [EnumMember(Value = {{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}})] - {{name}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^-last}}, + {{#isString}}[EnumMember(Value = "{{{value}}}")]{{/isString}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} - } + }{{! NOTE: This model's enumVars is modified to look like CodegenProperty}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache index 7af083a925f..12ba61de347 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache @@ -1,19 +1,21 @@ {{^isContainer}} /// - /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// {{^description}}Defines {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} /// {{#description}} /// {{description}} {{/description}} + {{#isString}} [JsonConverter(typeof(StringEnumConverter))] - {{>visibility}} enum {{#datatypeWithEnum}}{{&.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{/isString}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} { {{#allowableValues}}{{#enumVars}} /// - /// Enum {{name}} for {{{value}}} + /// Enum {{name}} for value: {{{value}}} /// - [EnumMember(Value = {{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isFloat}}"{{/isFloat}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isFloat}}"{{/isFloat}})] - {{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^-last}}, + {{#isString}}[EnumMember(Value = "{{{value}}}")]{{/isString}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} } {{/isContainer}} diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs index 2146daae4de..6ab512ac960 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithOptionalInlineEnum.cs @@ -31,50 +31,50 @@ namespace IO.Swagger.Model public partial class MyClassWithOptionalInlineEnum : IEquatable, IValidatableObject { /// - /// Gets or Sets Days + /// Defines Days /// [JsonConverter(typeof(StringEnumConverter))] public enum DaysEnum { /// - /// Enum Sun for "sun" + /// Enum Sun for value: sun /// [EnumMember(Value = "sun")] Sun, /// - /// Enum Mon for "mon" + /// Enum Mon for value: mon /// [EnumMember(Value = "mon")] Mon, /// - /// Enum Tue for "tue" + /// Enum Tue for value: tue /// [EnumMember(Value = "tue")] Tue, /// - /// Enum Wed for "wed" + /// Enum Wed for value: wed /// [EnumMember(Value = "wed")] Wed, /// - /// Enum Thu for "thu" + /// Enum Thu for value: thu /// [EnumMember(Value = "thu")] Thu, /// - /// Enum Fri for "fri" + /// Enum Fri for value: fri /// [EnumMember(Value = "fri")] Fri, /// - /// Enum Sat for "sat" + /// Enum Sat for value: sat /// [EnumMember(Value = "sat")] Sat diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs index fb43dccce3f..a131c7e774a 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/MyClassWithRequiredInlineEnum.cs @@ -31,50 +31,50 @@ namespace IO.Swagger.Model public partial class MyClassWithRequiredInlineEnum : IEquatable, IValidatableObject { /// - /// Gets or Sets Days + /// Defines Days /// [JsonConverter(typeof(StringEnumConverter))] public enum DaysEnum { /// - /// Enum Sun for "sun" + /// Enum Sun for value: sun /// [EnumMember(Value = "sun")] Sun, /// - /// Enum Mon for "mon" + /// Enum Mon for value: mon /// [EnumMember(Value = "mon")] Mon, /// - /// Enum Tue for "tue" + /// Enum Tue for value: tue /// [EnumMember(Value = "tue")] Tue, /// - /// Enum Wed for "wed" + /// Enum Wed for value: wed /// [EnumMember(Value = "wed")] Wed, /// - /// Enum Thu for "thu" + /// Enum Thu for value: thu /// [EnumMember(Value = "thu")] Thu, /// - /// Enum Fri for "fri" + /// Enum Fri for value: fri /// [EnumMember(Value = "fri")] Fri, /// - /// Enum Sat for "sat" + /// Enum Sat for value: sat /// [EnumMember(Value = "sat")] Sat diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs index ae81432d79b..92d45a5c028 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs +++ b/modules/swagger-codegen/src/test/resources/integrationtests/csharp/general/enum-support-expected/src/IO.Swagger/Model/WeekDays.cs @@ -27,48 +27,50 @@ namespace IO.Swagger.Model /// /// Defines WeekDays /// + [JsonConverter(typeof(StringEnumConverter))] + public enum WeekDays { /// - /// Enum Sun for "sun" + /// Enum Sun for value: sun /// [EnumMember(Value = "sun")] Sun, /// - /// Enum Mon for "mon" + /// Enum Mon for value: mon /// [EnumMember(Value = "mon")] Mon, /// - /// Enum Tue for "tue" + /// Enum Tue for value: tue /// [EnumMember(Value = "tue")] Tue, /// - /// Enum Wed for "wed" + /// Enum Wed for value: wed /// [EnumMember(Value = "wed")] Wed, /// - /// Enum Thu for "thu" + /// Enum Thu for value: thu /// [EnumMember(Value = "thu")] Thu, /// - /// Enum Fri for "fri" + /// Enum Fri for value: fri /// [EnumMember(Value = "fri")] Fri, /// - /// Enum Sat for "sat" + /// Enum Sat for value: sat /// [EnumMember(Value = "sat")] Sat From 018c8d3ece713f62612be389a8ce610d28419ee4 Mon Sep 17 00:00:00 2001 From: James Schubert Date: Mon, 6 Nov 2017 21:12:56 -0500 Subject: [PATCH 06/13] Remove unused imports --- .../io/swagger/codegen/languages/AbstractCSharpCodegen.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index a97545615e3..dfe4e8ff099 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -1,7 +1,5 @@ package io.swagger.codegen.languages; -import com.samskivert.mustache.Mustache; -import com.samskivert.mustache.Template; import io.swagger.codegen.*; import io.swagger.codegen.utils.ModelUtils; import io.swagger.models.properties.*; @@ -10,8 +8,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.io.IOException; -import java.io.Writer; import java.util.*; public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig { From 64fafb5db33267ce094378b7f6b787234764072b Mon Sep 17 00:00:00 2001 From: James Schubert Date: Mon, 13 Nov 2017 21:56:42 -0500 Subject: [PATCH 07/13] [all] sys props in CodegenConstants --- .../swagger/codegen/plugin/CodeGenMojo.java | 22 +++++++++---------- .../io/swagger/codegen/CodegenConstants.java | 4 ++++ .../io/swagger/codegen/DefaultGenerator.java | 2 +- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index a73ed6aa0c0..58fbeda5943 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -405,28 +405,28 @@ public class CodeGenMojo extends AbstractMojo { // Set generation options if (null != generateApis && generateApis) { - System.setProperty("apis", ""); + System.setProperty(CodegenConstants.APIS, ""); } else { - System.clearProperty("apis"); + System.clearProperty(CodegenConstants.APIS); } if (null != generateModels && generateModels) { - System.setProperty("models", modelsToGenerate); + System.setProperty(CodegenConstants.MODELS, modelsToGenerate); } else { - System.clearProperty("models"); + System.clearProperty(CodegenConstants.MODELS); } if (null != generateSupportingFiles && generateSupportingFiles) { - System.setProperty("supportingFiles", supportingFilesToGenerate); + System.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesToGenerate); } else { - System.clearProperty("supportingFiles"); + System.clearProperty(CodegenConstants.SUPPORTING_FILES); } - System.setProperty("modelTests", generateModelTests.toString()); - System.setProperty("modelDocs", generateModelDocumentation.toString()); - System.setProperty("apiTests", generateApiTests.toString()); - System.setProperty("apiDocs", generateApiDocumentation.toString()); - System.setProperty("withXml", withXml.toString()); + System.setProperty(CodegenConstants.MODEL_TESTS, generateModelTests.toString()); + System.setProperty(CodegenConstants.MODEL_DOCS, generateModelDocumentation.toString()); + System.setProperty(CodegenConstants.API_TESTS, generateApiTests.toString()); + System.setProperty(CodegenConstants.API_DOCS, generateApiDocumentation.toString()); + System.setProperty(CodegenConstants.WITH_XML, withXml.toString()); if (configOptions != null) { // Retained for backwards-compataibility with configOptions -> instantiation-types diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index b0b08dfe523..5b307344ccf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -4,6 +4,8 @@ package io.swagger.codegen; * A class for storing constants that are used throughout the project. */ public class CodegenConstants { + /* System Properties */ + // NOTE: We may want to move these to a separate class to avoid confusion or modification. public static final String APIS = "apis"; public static final String MODELS = "models"; public static final String SUPPORTING_FILES = "supportingFiles"; @@ -11,6 +13,8 @@ public class CodegenConstants { public static final String MODEL_DOCS = "modelDocs"; public static final String API_TESTS = "apiTests"; public static final String API_DOCS = "apiDocs"; + public static final String WITH_XML = "withXml"; + /* /end System Properties */ public static final String API_PACKAGE = "apiPackage"; public static final String API_PACKAGE_DESC = "package for generated api classes"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 2c166e69577..e10350207a9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -543,7 +543,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return; } Set supportingFilesToGenerate = null; - String supportingFiles = System.getProperty("supportingFiles"); + String supportingFiles = System.getProperty(CodegenConstants.SUPPORTING_FILES); if (supportingFiles != null && !supportingFiles.isEmpty()) { supportingFilesToGenerate = new HashSet(Arrays.asList(supportingFiles.split(","))); } From bedd4c880e1efcc5c051a50c1a27d1808112e414 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 7 Jan 2018 11:04:48 +0800 Subject: [PATCH 08/13] use openjdk7 in travis to ensure it works with jdk7 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7306d9711dd..49fca1cd8eb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ sudo: required language: java jdk: - - oraclejdk8 + - openjdk7 cache: directories: From 7479fc5361e6081455877b764d23ed6e22c06574 Mon Sep 17 00:00:00 2001 From: Ben Wells Date: Sun, 7 Jan 2018 03:37:40 +0000 Subject: [PATCH 09/13] Generate swagger yaml for go client (#7281) --- .../codegen/languages/AbstractGoCodegen.java | 16 + .../codegen/languages/GoClientCodegen.java | 1 + .../codegen/languages/GoServerCodegen.java | 21 - .../src/main/resources/go/swagger.mustache | 1 + .../petstore/go/go-petstore/api/swagger.yaml | 1538 +++++++++++++++++ .../petstore/go-api-server/go/README.md | 2 +- 6 files changed, 1557 insertions(+), 22 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/go/swagger.mustache create mode 100644 samples/client/petstore/go/go-petstore/api/swagger.yaml diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractGoCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractGoCodegen.java index b03a6a0b30a..73d99e60a28 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractGoCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractGoCodegen.java @@ -5,12 +5,15 @@ import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.parameters.Parameter; +import io.swagger.models.Swagger; import io.swagger.util.Yaml; import java.util.*; import org.apache.commons.lang3.StringUtils; +import com.fasterxml.jackson.core.JsonProcessingException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -362,6 +365,19 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege return postProcessModelsEnum(objs); } + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + return super.postProcessSupportingFileData(objs); + } + @Override protected boolean needToImport(String type) { return !defaultIncludes.contains(type) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index c974e6928c2..8ee82ceb485 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -87,6 +87,7 @@ public class GoClientCodegen extends AbstractGoCodegen { modelPackage = packageName; apiPackage = packageName; + supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java index b8cbd510b75..58f621ae3db 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -5,20 +5,12 @@ import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.parameters.Parameter; -import io.swagger.models.*; -import io.swagger.util.Yaml; import java.io.File; import java.util.*; import org.apache.commons.lang3.StringUtils; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -167,17 +159,4 @@ public class GoServerCodegen extends AbstractGoCodegen { return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } - @Override - public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { - try { - objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage(), e); - } - } - return super.postProcessSupportingFileData(objs); - } - } diff --git a/modules/swagger-codegen/src/main/resources/go/swagger.mustache b/modules/swagger-codegen/src/main/resources/go/swagger.mustache new file mode 100644 index 00000000000..51560926bba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-yaml}}} \ No newline at end of file diff --git a/samples/client/petstore/go/go-petstore/api/swagger.yaml b/samples/client/petstore/go/go-petstore/api/swagger.yaml new file mode 100644 index 00000000000..7edbe6eb94a --- /dev/null +++ b/samples/client/petstore/go/go-petstore/api/swagger.yaml @@ -0,0 +1,1538 @@ +--- +swagger: "2.0" +info: + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache-2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io:80" +basePath: "/v2" +tags: +- name: "pet" + description: "Everything about your Pets" + externalDocs: + description: "Find out more" + url: "http://swagger.io" +- name: "store" + description: "Access to Petstore orders" +- name: "user" + description: "Operations about user" + externalDocs: + description: "Find out more about our store" + url: "http://swagger.io" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + x-exportParamName: "Body" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + x-exportParamName: "Body" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + 405: + description: "Validation exception" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma separated strings" + operationId: "findPetsByStatus" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: true + type: "array" + items: + type: "string" + default: "available" + enum: + - "available" + - "pending" + - "sold" + collectionFormat: "csv" + x-exportParamName: "Status" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: true + type: "array" + items: + type: "string" + collectionFormat: "csv" + x-exportParamName: "Tags" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + deprecated: true + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a single pet" + operationId: "getPetById" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to return" + required: true + type: "integer" + format: "int64" + x-exportParamName: "PetId" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "integer" + format: "int64" + x-exportParamName: "PetId" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + x-exportParamName: "Name" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + x-exportParamName: "Status" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "api_key" + in: "header" + required: false + type: "string" + x-exportParamName: "ApiKey" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + x-exportParamName: "PetId" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + x-exportParamName: "PetId" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + x-exportParamName: "AdditionalMetadata" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + x-exportParamName: "File" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/ApiResponse" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "placeOrder" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: true + schema: + $ref: "#/definitions/Order" + x-exportParamName: "Body" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + /store/order/{order_id}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "order_id" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + maximum: 5 + minimum: 1 + format: "int64" + x-exportParamName: "OrderId" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + delete: + tags: + - "store" + summary: "Delete purchase order by ID" + description: "For valid response try integer IDs with value < 1000. Anything\ + \ above 1000 or nonintegers will generate API errors" + operationId: "deleteOrder" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "order_id" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + x-exportParamName: "OrderId" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: true + schema: + $ref: "#/definitions/User" + x-exportParamName: "Body" + responses: + default: + description: "successful operation" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + x-exportParamName: "Body" + responses: + default: + description: "successful operation" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + x-exportParamName: "Body" + responses: + default: + description: "successful operation" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: true + type: "string" + x-exportParamName: "Username" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: true + type: "string" + x-exportParamName: "Password" + responses: + 200: + description: "successful operation" + schema: + type: "string" + headers: + X-Rate-Limit: + type: "integer" + format: "int32" + description: "calls per hour allowed by the user" + X-Expires-After: + type: "string" + format: "date-time" + description: "date in UTC when toekn expires" + 400: + description: "Invalid username/password supplied" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/xml" + - "application/json" + parameters: [] + responses: + default: + description: "successful operation" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + x-exportParamName: "Username" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/User" + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + x-exportParamName: "Username" + - in: "body" + name: "body" + description: "Updated user object" + required: true + schema: + $ref: "#/definitions/User" + x-exportParamName: "Body" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + x-exportParamName: "Username" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + /fake_classname_test: + patch: + tags: + - "fake_classname_tags 123#$%^" + summary: "To test class name in snake case" + operationId: "testClassname" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "client model" + required: true + schema: + $ref: "#/definitions/Client" + x-exportParamName: "Body" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" + security: + - api_key_query: [] + /fake: + get: + tags: + - "fake" + summary: "To test enum parameters" + description: "To test enum parameters" + operationId: "testEnumParameters" + consumes: + - "*/*" + produces: + - "*/*" + parameters: + - name: "enum_form_string_array" + in: "formData" + description: "Form parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + default: "$" + enum: + - ">" + - "$" + x-exportParamName: "EnumFormStringArray" + - name: "enum_form_string" + in: "formData" + description: "Form parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + x-exportParamName: "EnumFormString" + - name: "enum_header_string_array" + in: "header" + description: "Header parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + default: "$" + enum: + - ">" + - "$" + x-exportParamName: "EnumHeaderStringArray" + - name: "enum_header_string" + in: "header" + description: "Header parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + x-exportParamName: "EnumHeaderString" + - name: "enum_query_string_array" + in: "query" + description: "Query parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + default: "$" + enum: + - ">" + - "$" + x-exportParamName: "EnumQueryStringArray" + - name: "enum_query_string" + in: "query" + description: "Query parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + x-exportParamName: "EnumQueryString" + - name: "enum_query_integer" + in: "query" + description: "Query parameter enum test (double)" + required: false + type: "integer" + format: "int32" + enum: + - 1 + - -2 + x-exportParamName: "EnumQueryInteger" + - name: "enum_query_double" + in: "formData" + description: "Query parameter enum test (double)" + required: false + type: "number" + format: "double" + enum: + - 1.1 + - -1.2 + x-exportParamName: "EnumQueryDouble" + responses: + 400: + description: "Invalid request" + 404: + description: "Not found" + post: + tags: + - "fake" + summary: "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n가짜 엔\ + 드 포인트\n" + description: "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n\ + 가짜 엔드 포인트\n" + operationId: "testEndpointParameters" + consumes: + - "application/xml; charset=utf-8" + - "application/json; charset=utf-8" + produces: + - "application/xml; charset=utf-8" + - "application/json; charset=utf-8" + parameters: + - name: "integer" + in: "formData" + description: "None" + required: false + type: "integer" + maximum: 100 + minimum: 10 + x-exportParamName: "Integer" + - name: "int32" + in: "formData" + description: "None" + required: false + type: "integer" + maximum: 200 + minimum: 20 + format: "int32" + x-exportParamName: "Int32_" + - name: "int64" + in: "formData" + description: "None" + required: false + type: "integer" + format: "int64" + x-exportParamName: "Int64_" + - name: "number" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 543.2 + minimum: 32.1 + x-exportParamName: "Number" + - name: "float" + in: "formData" + description: "None" + required: false + type: "number" + maximum: 987.6 + format: "float" + x-exportParamName: "Float" + - name: "double" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 123.4 + minimum: 67.8 + format: "double" + x-exportParamName: "Double" + - name: "string" + in: "formData" + description: "None" + required: false + type: "string" + pattern: "/[a-z]/i" + x-exportParamName: "String_" + - name: "pattern_without_delimiter" + in: "formData" + description: "None" + required: true + type: "string" + pattern: "^[A-Z].*" + x-exportParamName: "PatternWithoutDelimiter" + - name: "byte" + in: "formData" + description: "None" + required: true + type: "string" + format: "byte" + x-exportParamName: "Byte_" + - name: "binary" + in: "formData" + description: "None" + required: false + type: "string" + format: "binary" + x-exportParamName: "Binary" + - name: "date" + in: "formData" + description: "None" + required: false + type: "string" + format: "date" + x-exportParamName: "Date" + - name: "dateTime" + in: "formData" + description: "None" + required: false + type: "string" + format: "date-time" + x-exportParamName: "DateTime" + - name: "password" + in: "formData" + description: "None" + required: false + type: "string" + maxLength: 64 + minLength: 10 + format: "password" + x-exportParamName: "Password" + - name: "callback" + in: "formData" + description: "None" + required: false + type: "string" + x-exportParamName: "Callback" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + security: + - http_basic_test: [] + patch: + tags: + - "fake" + summary: "To test \"client\" model" + description: "To test \"client\" model" + operationId: "testClientModel" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "client model" + required: true + schema: + $ref: "#/definitions/Client" + x-exportParamName: "Body" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" + /fake/outer/number: + post: + tags: + - "fake" + description: "Test serialization of outer number types" + operationId: "fakeOuterNumberSerialize" + parameters: + - in: "body" + name: "body" + description: "Input number as post body" + required: false + schema: + $ref: "#/definitions/OuterNumber" + x-exportParamName: "Body" + responses: + 200: + description: "Output number" + schema: + $ref: "#/definitions/OuterNumber" + /fake/outer/string: + post: + tags: + - "fake" + description: "Test serialization of outer string types" + operationId: "fakeOuterStringSerialize" + parameters: + - in: "body" + name: "body" + description: "Input string as post body" + required: false + schema: + $ref: "#/definitions/OuterString" + x-exportParamName: "Body" + responses: + 200: + description: "Output string" + schema: + $ref: "#/definitions/OuterString" + /fake/outer/boolean: + post: + tags: + - "fake" + description: "Test serialization of outer boolean types" + operationId: "fakeOuterBooleanSerialize" + parameters: + - in: "body" + name: "body" + description: "Input boolean as post body" + required: false + schema: + $ref: "#/definitions/OuterBoolean" + x-exportParamName: "Body" + responses: + 200: + description: "Output boolean" + schema: + $ref: "#/definitions/OuterBoolean" + /fake/outer/composite: + post: + tags: + - "fake" + description: "Test serialization of object with outer number type" + operationId: "fakeOuterCompositeSerialize" + parameters: + - in: "body" + name: "body" + description: "Input composite as post body" + required: false + schema: + $ref: "#/definitions/OuterComposite" + x-exportParamName: "Body" + responses: + 200: + description: "Output composite" + schema: + $ref: "#/definitions/OuterComposite" + /fake/jsonFormData: + get: + tags: + - "fake" + summary: "test json serialization of form data" + description: "" + operationId: "testJsonFormData" + consumes: + - "application/json" + parameters: + - name: "param" + in: "formData" + description: "field1" + required: true + type: "string" + x-exportParamName: "Param" + - name: "param2" + in: "formData" + description: "field2" + required: true + type: "string" + x-exportParamName: "Param2" + responses: + 200: + description: "successful operation" + /fake/inline-additionalProperties: + post: + tags: + - "fake" + summary: "test inline additionalProperties" + description: "" + operationId: "testInlineAdditionalProperties" + consumes: + - "application/json" + parameters: + - in: "body" + name: "param" + description: "request body" + required: true + schema: + type: "object" + additionalProperties: + type: "string" + x-exportParamName: "Param" + responses: + 200: + description: "successful operation" + /another-fake/dummy: + patch: + tags: + - "$another-fake?" + summary: "To test special tags" + description: "To test special tags" + operationId: "test_special_tags" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "client model" + required: true + schema: + $ref: "#/definitions/Client" + x-exportParamName: "Body" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" +securityDefinitions: + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" + api_key_query: + type: "apiKey" + name: "api_key_query" + in: "query" + http_basic_test: + type: "basic" +definitions: + Order: + type: "object" + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + default: false + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: "2000-01-23T04:56:07.000+00:00" + complete: false + status: "placed" + xml: + name: "Order" + Category: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + example: + name: "name" + id: 6 + xml: + name: "Category" + User: + type: "object" + properties: + id: + type: "integer" + format: "int64" + x-is-unique: true + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + example: + firstName: "firstName" + lastName: "lastName" + password: "password" + userStatus: 6 + phone: "phone" + id: 0 + email: "email" + username: "username" + xml: + name: "User" + Tag: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + example: + name: "name" + id: 1 + xml: + name: "Tag" + Pet: + type: "object" + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + x-is-unique: true + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + example: + photoUrls: + - "photoUrls" + - "photoUrls" + name: "doggie" + id: 0 + category: + name: "name" + id: 6 + tags: + - name: "name" + id: 1 + - name: "name" + id: 1 + status: "available" + xml: + name: "Pet" + ApiResponse: + type: "object" + properties: + code: + type: "integer" + format: "int32" + type: + type: "string" + message: + type: "string" + example: + code: 0 + type: "type" + message: "message" + $special[model.name]: + properties: + $special[property.name]: + type: "integer" + format: "int64" + xml: + name: "$special[model.name]" + Return: + properties: + return: + type: "integer" + format: "int32" + description: "Model for testing reserved words" + xml: + name: "Return" + Name: + required: + - "name" + properties: + name: + type: "integer" + format: "int32" + snake_case: + type: "integer" + format: "int32" + readOnly: true + property: + type: "string" + 123Number: + type: "integer" + readOnly: true + description: "Model for testing model name same as property name" + xml: + name: "Name" + 200_response: + properties: + name: + type: "integer" + format: "int32" + class: + type: "string" + description: "Model for testing model name starting with number" + xml: + name: "Name" + ClassModel: + properties: + _class: + type: "string" + description: "Model for testing model with \"_class\" property" + Dog: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + breed: + type: "string" + Cat: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + declawed: + type: "boolean" + Animal: + type: "object" + required: + - "className" + discriminator: "className" + properties: + className: + type: "string" + color: + type: "string" + default: "red" + AnimalFarm: + type: "array" + items: + $ref: "#/definitions/Animal" + format_test: + type: "object" + required: + - "byte" + - "date" + - "number" + - "password" + properties: + integer: + type: "integer" + minimum: 10 + maximum: 100 + int32: + type: "integer" + format: "int32" + minimum: 20 + maximum: 200 + int64: + type: "integer" + format: "int64" + number: + type: "number" + minimum: 32.1 + maximum: 543.2 + float: + type: "number" + format: "float" + minimum: 54.3 + maximum: 987.6 + double: + type: "number" + format: "double" + minimum: 67.8 + maximum: 123.4 + string: + type: "string" + pattern: "/[a-z]/i" + byte: + type: "string" + format: "byte" + pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$" + binary: + type: "string" + format: "binary" + date: + type: "string" + format: "date" + dateTime: + type: "string" + format: "date-time" + uuid: + type: "string" + format: "uuid" + password: + type: "string" + format: "password" + minLength: 10 + maxLength: 64 + EnumClass: + type: "string" + enum: + - "_abc" + - "-efg" + - "(xyz)" + default: "-efg" + Enum_Test: + type: "object" + properties: + enum_string: + type: "string" + enum: + - "UPPER" + - "lower" + - "" + enum_integer: + type: "integer" + format: "int32" + enum: + - 1 + - -1 + enum_number: + type: "number" + format: "double" + enum: + - 1.1 + - -1.2 + outerEnum: + $ref: "#/definitions/OuterEnum" + AdditionalPropertiesClass: + type: "object" + properties: + map_property: + type: "object" + additionalProperties: + type: "string" + map_of_map_property: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + MixedPropertiesAndAdditionalPropertiesClass: + type: "object" + properties: + uuid: + type: "string" + format: "uuid" + dateTime: + type: "string" + format: "date-time" + map: + type: "object" + additionalProperties: + $ref: "#/definitions/Animal" + List: + type: "object" + properties: + 123-list: + type: "string" + Client: + type: "object" + properties: + client: + type: "string" + example: + client: "client" + ReadOnlyFirst: + type: "object" + properties: + bar: + type: "string" + readOnly: true + baz: + type: "string" + hasOnlyReadOnly: + type: "object" + properties: + bar: + type: "string" + readOnly: true + foo: + type: "string" + readOnly: true + Capitalization: + type: "object" + properties: + smallCamel: + type: "string" + CapitalCamel: + type: "string" + small_Snake: + type: "string" + Capital_Snake: + type: "string" + SCA_ETH_Flow_Points: + type: "string" + ATT_NAME: + type: "string" + description: "Name of the pet\n" + MapTest: + type: "object" + properties: + map_map_of_string: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + map_of_enum_string: + type: "object" + additionalProperties: + type: "string" + enum: + - "UPPER" + - "lower" + ArrayTest: + type: "object" + properties: + array_of_string: + type: "array" + items: + type: "string" + array_array_of_integer: + type: "array" + items: + type: "array" + items: + type: "integer" + format: "int64" + array_array_of_model: + type: "array" + items: + type: "array" + items: + $ref: "#/definitions/ReadOnlyFirst" + NumberOnly: + type: "object" + properties: + JustNumber: + type: "number" + ArrayOfNumberOnly: + type: "object" + properties: + ArrayNumber: + type: "array" + items: + type: "number" + ArrayOfArrayOfNumberOnly: + type: "object" + properties: + ArrayArrayNumber: + type: "array" + items: + type: "array" + items: + type: "number" + EnumArrays: + type: "object" + properties: + just_symbol: + type: "string" + enum: + - ">=" + - "$" + array_enum: + type: "array" + items: + type: "string" + enum: + - "fish" + - "crab" + OuterEnum: + type: "string" + enum: + - "placed" + - "approved" + - "delivered" + OuterComposite: + type: "object" + properties: + my_number: + $ref: "#/definitions/OuterNumber" + my_string: + $ref: "#/definitions/OuterString" + my_boolean: + $ref: "#/definitions/OuterBoolean" + example: + my_string: {} + my_number: {} + my_boolean: {} + OuterNumber: + type: "number" + OuterString: + type: "string" + OuterBoolean: + type: "boolean" +externalDocs: + description: "Find out more about Swagger" + url: "http://swagger.io" diff --git a/samples/server/petstore/go-api-server/go/README.md b/samples/server/petstore/go-api-server/go/README.md index 307542639a5..81e395ff5a9 100644 --- a/samples/server/petstore/go-api-server/go/README.md +++ b/samples/server/petstore/go-api-server/go/README.md @@ -13,7 +13,7 @@ To see how to make this your own, look here: [README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) - API version: 1.0.0 -- Build date: 2017-12-18T09:35:47.160Z +- Build date: 2017-12-20T21:53:07.200Z ### Running the server From 743bc650abeef0351117a3b30cd8b78f83fafc2a Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 7 Jan 2018 11:05:58 +0800 Subject: [PATCH 10/13] add shijinkui to scala technical committee --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0824a62d4f..e660b5d98f3 100644 --- a/README.md +++ b/README.md @@ -1116,7 +1116,7 @@ If you want to join the committee, please kindly apply by sending an email to wi | R | | | Ruby | @cliffano (2017/07) @zlx (2017/09) | | Rust | @frol (2017/07) @farcaller (2017/08) @bjgill (2017/12) | -| Scala | @clasnake (2017/07) @jimschubert (2017/09) | +| Scala | @clasnake (2017/07) @jimschubert (2017/09) @shijinkui (2018/01) | | Swift | @jgavris (2017/07) @ehyche (2017/08) @Edubits (2017/09) @jaz-ah (2017/09) | | TypeScript | @TiFu (2017/07) @taxpon (2017/07) @sebastianhaas (2017/07) @kenisteward (2017/07) @Vrolijkx (2017/09) | From 362625bfa9471c0b4bcb88b34ea287c11765179a Mon Sep 17 00:00:00 2001 From: Stephane Carrez Date: Sun, 7 Jan 2018 11:44:20 +0100 Subject: [PATCH 11/13] [Ada] Add Ada support for server code generator #6680 (#7256) * Add Ada client petstore samples - Add script to generate Ada client support with swagger-codegen - Add files to build the Ada sample - Add main program to use the generated client samples API and connect to the server to perform some operations * Add some description for the samples * Update the documentation to explain how to build, how to use the generated Ada client code * Add server support for path parameters - Update postProcessOperations to scan each path parameter and emit a x-path-index vendor attribute to tell the index of the path parameter * Add and fix Ada server code package declaration - fix declaration of operations - generate a generic package that must be instantiated with the target server implementation and which provides the skeleton (deserialization and serialization of data) * Implement the Ada server side operations - extract body, query parameters, path parameters - serialize the result - register operations to the server according to the path/routes * Update the code generation to generate server Ada implementation code * Improvement of Ada server support: generate the swagger.json template file * Define toModelName operation to the creation of a model identifier * Add support for server permission generation - collect the security scopes in postProcessAuthMethod() method and make sure these scopes have unique identifiers. Some scopes correspond to URLs but others correspond to pseudo identifiers. * Use the #lambdaAdaComment filter to indent correctly a multi-line description * Fix model generation to support arrays * Update the generated GNAT project file * Refactoring and improvement of server code generation - Change the server generated code to pass a Context_Type object to allow the server implementation to get/set headers in the request/response and control what is put in some responses - Generate the security permissions based on the scopes that have been collected * Server code generation improvement - Fix generation of GNAT project - Generate the intermediate Ada packages if necessary - Generate the server main * Ada server main template * Ada server code improvement - Add support to generate server permission verification - Fix the GNAT project definition - Templates for Ada intermediate packages * Skeleton for the server side implementation * Generate an empty Ada server implementation * Templates for the Ada server implementation * Add a README.md file and a GNAT config.gpr file * New templates to document the generated Ada server * Add server configuration file for the Ada server * Fix the log message in the Ada server to report the correct URI to connect to * Generate the Ada server configuration file * Improvement of Ada code model to support nullable types * Update the Ada server templates * Refactor the Ada code generator - separate the Ada client and Ada server code generators - register the Ada server code generator under the name 'ada-server' keep 'ada' for the client Ada code generator - moved the common Ada code operation supports to the AbstractAdaCodegen * Improvement and cleanup of Ada client and server code - new template for the client main program - fix the GNAT project template for client or server programs - remove unused options to better use the --model-package option * Fix the GNAT project file name to use a lower case name Fix the default GNAT config Fix the headers of intermediate Ada package files * Regenerate the model and client Ada files * Update the Ada client sample to take into account the Nullable types * Regenerate some files with Ada Swagger Codegen * Ignore generation of petstore.gpr --- .../codegen/languages/AbstractAdaCodegen.java | 461 +++++++++++++++++- .../swagger/codegen/languages/AdaCodegen.java | 346 ++----------- .../codegen/languages/AdaServerCodegen.java | 111 +++++ .../src/main/resources/Ada/README.mustache | 102 ++++ .../main/resources/Ada/client-body.mustache | 7 +- .../main/resources/Ada/client-spec.mustache | 2 +- .../src/main/resources/Ada/client.mustache | 43 ++ .../src/main/resources/Ada/config.gpr | 88 ++++ .../main/resources/Ada/gnat-project.mustache | 11 +- .../main/resources/Ada/model-body.mustache | 4 +- .../main/resources/Ada/model-spec.mustache | 14 +- .../Ada/package-spec-level1.mustache | 14 + .../Ada/package-spec-level2.mustache | 14 + .../main/resources/Ada/server-body.mustache | 27 +- .../resources/Ada/server-properties.mustache | 22 + .../Ada/server-skeleton-body.mustache | 231 +++++++++ .../Ada/server-skeleton-spec.mustache | 115 +++++ .../main/resources/Ada/server-spec.mustache | 35 +- .../src/main/resources/Ada/server.mustache | 43 ++ .../src/main/resources/Ada/swagger.mustache | 1 + .../services/io.swagger.codegen.CodegenConfig | 1 + .../petstore/ada/.swagger-codegen-ignore | 1 + samples/client/petstore/ada/petstore.gpr | 16 +- .../src/client/samples-petstore-clients.adb | 22 +- .../src/client/samples-petstore-clients.ads | 22 +- .../samples-petstore-models.adb | 14 +- .../samples-petstore-models.ads | 56 ++- samples/client/petstore/ada/src/petstore.adb | 66 +-- .../petstore/ada/src/samples-petstore.ads | 14 +- samples/client/petstore/ada/src/samples.ads | 14 +- 30 files changed, 1498 insertions(+), 419 deletions(-) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/Ada/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/client.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/config.gpr create mode 100644 modules/swagger-codegen/src/main/resources/Ada/package-spec-level1.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/package-spec-level2.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/server-properties.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/server-skeleton-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/server-skeleton-spec.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/server.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Ada/swagger.mustache rename samples/client/petstore/ada/src/{client => model}/samples-petstore-models.adb (99%) rename samples/client/petstore/ada/src/{client => model}/samples-petstore-models.ads (86%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractAdaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractAdaCodegen.java index eb6e0263ac9..9b3cf2132ef 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractAdaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractAdaCodegen.java @@ -1,13 +1,26 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.models.properties.Property; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.samskivert.mustache.Escapers; +import com.samskivert.mustache.Mustache; +import io.swagger.codegen.*; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Response; +import io.swagger.models.Swagger; +import io.swagger.models.properties.*; +import io.swagger.util.Json; -import java.util.Arrays; +import java.util.*; abstract public class AbstractAdaCodegen extends DefaultCodegen implements CodegenConfig { + protected String packageName = "swagger"; + protected String projectName = "Swagger"; + protected List> orderedModels; + protected Map> modelDepends; + protected Map nullableTypeMapping; + protected HashMap operationsScopes; + protected int scopeIndex = 0; public AbstractAdaCodegen() { super(); @@ -90,6 +103,56 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg "with", "xor") ); + + typeMapping = new HashMap(); + typeMapping.put("date", "Swagger.Date"); + typeMapping.put("DateTime", "Swagger.Datetime"); + typeMapping.put("string", "Swagger.UString"); + typeMapping.put("integer", "Integer"); + typeMapping.put("long", "Swagger.Long"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("array", "Swagger.Vector"); + typeMapping.put("map", "Swagger.Map"); + typeMapping.put("object", "Swagger.Object"); + typeMapping.put("number", "Swagger.Number"); + typeMapping.put("UUID", "Swagger.UString"); + typeMapping.put("file", "Swagger.Http_Content_Type"); + typeMapping.put("binary", "Swagger.Binary"); + + nullableTypeMapping = new HashMap(); + nullableTypeMapping.put("date", "Swagger.Nullable_Date"); + nullableTypeMapping.put("DateTime", "Swagger.Nullable_Date"); + nullableTypeMapping.put("string", "Swagger.Nullable_UString"); + nullableTypeMapping.put("integer", "Swagger.Nullable_Integer"); + nullableTypeMapping.put("long", "Swagger.Nullable_Long"); + nullableTypeMapping.put("boolean", "Swagger.Nullable_Boolean"); + nullableTypeMapping.put("object", "Swagger.Object"); + + modelDepends = new HashMap>(); + orderedModels = new ArrayList>(); + operationsScopes = new HashMap(); + super.importMapping = new HashMap(); + + // CLI options + addOption(CodegenConstants.PROJECT_NAME, "GNAT project name", + this.projectName); + + modelNameSuffix = "_Type"; + embeddedTemplateDir = templateDir = "Ada"; + + languageSpecificPrimitives = new HashSet( + Arrays.asList("integer", "boolean", "Integer", "Character", "Boolean", "long", "float", "double")); + } + + protected void addOption(String key, String description, String defaultValue) { + CliOption option = new CliOption(key, description); + if (defaultValue != null) + option.defaultValue(defaultValue); + cliOptions.add(option); + } + + public String toFilename(String name) { + return name.replace(".", "-").toLowerCase(); } /** @@ -152,12 +215,394 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg return toAdaIdentifier(super.toParamName(name), "P_"); } + /** + * Output the proper model name (capitalized). + * In case the name belongs to the TypeSystem it won't be renamed. + * + * @param name the name of the model + * @return capitalized model name + */ + public String toModelName(final String name) { + String result = super.toModelName(name); + if (result.matches("^\\d.*") || result.startsWith("_")) { + result = "Model_" + result; + } + return result.replaceAll("[\\.-]", "_").replaceAll("__+", "_"); + } + @Override public CodegenProperty fromProperty(String name, Property p) { CodegenProperty property = super.fromProperty(name, p); - String nameInCamelCase = property.nameInCamelCase; - nameInCamelCase = sanitizeName(nameInCamelCase); - property.nameInCamelCase = nameInCamelCase; + if (property != null) { + String nameInCamelCase = property.nameInCamelCase; + nameInCamelCase = sanitizeName(nameInCamelCase); + property.nameInCamelCase = nameInCamelCase; + } return property; } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle + * escaping those terms here. This logic is only called if a variable + * matches the reserved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "p_" + name; // add an underscore to the name + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*").replace("-", "_"); + } + + /** + * Override the Mustache compiler configuration. + * + * We don't want to have special characters escaped + * + * @param compiler the compiler. + * @return the compiler to use. + */ + @Override + public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { + compiler = super.processCompiler(compiler).emptyStringIsFalse(true); + + return compiler.withEscaper(Escapers.NONE); + } + + /** + * Optional - type declaration. This is a String which is used by the + * templates to instantiate your types. There is typically special handling + * for different property types + * + * @return a string value used as the `dataType` field for model templates, + * `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + + if (swaggerType != null) { + swaggerType = swaggerType.replace("-", "_"); + } + + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getTypeDeclaration(inner) + "_Vectors.Vector"; + } + if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + String name = getTypeDeclaration(inner) + "_Map"; + if (name.startsWith("Swagger.")) { + return name; + } else { + return "Swagger." + name; + } + } + if (typeMapping.containsKey(swaggerType)) { + if (p.getRequired()) { + return typeMapping.get(swaggerType); + } else { + return nullableTypeMapping.get(swaggerType); + } + } + // LOGGER.info("Swagger type " + swaggerType); + if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + String modelType = toModelName(swaggerType).replace("-", "_"); + if (p instanceof StringProperty || p instanceof DateProperty + || p instanceof DateTimeProperty || p instanceof FileProperty + || languageSpecificPrimitives.contains(modelType)) { + return modelType; + } + + return modelPackage + ".Models." + modelType; + } + + /** + * Overrides postProcessParameter to add a vendor extension "x-is-model-type". + * This boolean indicates that the parameter comes from the model package. + * + * @param parameter CodegenParameter object to be processed. + */ + @Override + public void postProcessParameter(CodegenParameter parameter){ + // Give the base class a chance to process + super.postProcessParameter(parameter); + + if (parameter.dataType == null) { + return; + } + boolean isModel = parameter.dataType.startsWith(modelPackage); + if (!isModel && !parameter.isPrimitiveType && !parameter.isDate + && !parameter.isString && !parameter.isContainer && !parameter.isFile) { + isModel = true; + } + parameter.vendorExtensions.put("x-is-model-type", isModel); + } + + /** + * Post process the media types (produces and consumes) for Ada code generator. + * + * For each media type, add a adaMediaType member that gives the Ada enum constant + * for the corresponding type. + * + * @param types the list of media types. + * @return the number of media types. + */ + protected int postProcessMediaTypes(List> types) { + int count = 0; + if (types != null) { + for (Map media : types) { + String mt = media.get("mediaType"); + if (mt != null) { + mt = mt.replace('/', '_'); + media.put("adaMediaType", mt.toUpperCase()); + count++; + } + } + } + return count; + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + + if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { + Response methodResponse = findMethodResponse(operation.getResponses()); + + if (methodResponse != null) { + if (methodResponse.getSchema() != null) { + CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + op.vendorExtensions.put("x-codegen-response", cm); + if(cm.datatype == "HttpContent") { + op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); + } + } + } + } + return op; + } + + @SuppressWarnings("unchecked") + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + + for (CodegenOperation op1 : operationList) { + if (op1.summary != null) { + op1.summary = op1.summary.trim(); + } + if (op1.notes != null) { + op1.notes = op1.notes.trim(); + } + op1.vendorExtensions.put("x-has-uniq-produces", postProcessMediaTypes(op1.produces) == 1); + op1.vendorExtensions.put("x-has-uniq-consumes", postProcessMediaTypes(op1.consumes) == 1); + op1.vendorExtensions.put("x-has-notes", op1.notes != null && op1.notes.length() > 0); + + // Set the file parameter type for both allParams and formParams. + for (CodegenParameter p : op1.allParams) { + if (p.isFormParam && p.isFile) { + p.dataType = "Swagger.File_Part_Type"; + } + } + for (CodegenParameter p : op1.formParams) { + if (p.isFile) { + p.dataType = "Swagger.File_Part_Type"; + } + } + postProcessAuthMethod(op1.authMethods); + + /* + * Scan the path parameter to construct a x-path-index that tells the index of + * the path parameter. + */ + for (CodegenParameter p : op1.pathParams) { + String path = op1.path; + int pos = 0; + int index = 0; + while (pos >= 0 && pos < path.length()) { + int last; + pos = path.indexOf('{', pos); + if (pos < 0) { + break; + } + pos++; + last = path.indexOf('}', pos); + index++; + if (last < 0) { + break; + } + if (path.substring(pos, last - 1) == p.baseName) { + break; + } + pos = last + 1; + } + p.vendorExtensions.put("x-path-index", index); + } + } + return objs; + } + + @Override + public Map postProcessModels(Map objs) { + // Collect the model dependencies. + List> models = (List>) objs.get("models"); + for (Map model : models) { + Object v = model.get("model"); + if (v instanceof CodegenModel) { + CodegenModel m = (CodegenModel) v; + List d = new ArrayList(); + for (CodegenProperty p : m.allVars) { + boolean isModel = false; + CodegenProperty item = p; + if (p.isContainer) { + item = p.items; + } + if (item != null && !item.isString && !item.isPrimitiveType && !item.isContainer && !item.isInteger) { + if (!d.contains(item.datatype)) { + // LOGGER.info("Model " + m.name + " uses " + p.datatype); + d.add(item.datatype); + isModel = true; + } + } + p.vendorExtensions.put("x-is-model-type", isModel); + } + modelDepends.put(m.name, d); + orderedModels.add(model); + } + } + + // Sort the models according to dependencies so that model that depend + // on others appear at end of the list. + final Map> deps = modelDepends; + Collections.sort(orderedModels, new Comparator>() { + @Override + public int compare(Map lhs, Map rhs) { + Object v = lhs.get("model"); + String lhsName = ((CodegenModel) v).name; + v = rhs.get("model"); + String rhsName = ((CodegenModel) v).name; + List lhsList = deps.get(lhsName); + List rhsList = deps.get(rhsName); + if (lhsList == rhsList) { + // LOGGER.info("First compare " + lhsName + "<" + rhsName); + return lhsName.compareTo(rhsName); + } + // Put models without dependencies first. + if (lhsList == null) { + // LOGGER.info(" Empty " + lhsName + ", no check " + rhsName); + return -1; + } + if (rhsList == null) { + // LOGGER.info(" No check " + lhsName + ", empty " + rhsName); + return 1; + } + // Put models that depend on another after. + if (lhsList.contains(rhsName)) { + // LOGGER.info(" LSH " + lhsName + " uses " + rhsName); + return 1; + } + if (rhsList.contains(lhsName)) { + // LOGGER.info(" RHS " + rhsName + " uses " + lhsName); + return -1; + } + // Put models with less dependencies first. + if (lhsList.size() < rhsList.size()) { + // LOGGER.info(" LSH size " + lhsName + " < RHS size " + rhsName); + return -1; + } + if (lhsList.size() > rhsList.size()) { + // LOGGER.info(" LSH size " + lhsName + " > RHS size " + rhsName); + return 1; + } + // Sort models on their name. + // LOGGER.info("Compare " + lhsName + "<" + rhsName); + return lhsName.compareTo(rhsName); + } + }); + /* for (Map model : orderedModels) { + Object v = model.get("model"); + if (v instanceof CodegenModel) { + CodegenModel m = (CodegenModel) v; + LOGGER.info("Order: " + m.name); + } + }*/ + return postProcessModelsEnum(objs); + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + objs.put("orderedModels", orderedModels); + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + String host = swagger.getBasePath(); + try { + swagger.setHost("SWAGGER_HOST"); + objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n")); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + swagger.setHost(host); + } + + /** + * Collect the scopes to generate unique identifiers for each of them. + */ + List authMethods = (List) objs.get("authMethods"); + postProcessAuthMethod(authMethods); + + return super.postProcessSupportingFileData(objs); + } + + /** + * Collect the scopes to generate a unique identifier for each of them. + * + * @param authMethods the auth methods with their scopes. + */ + private void postProcessAuthMethod(List authMethods) { + if (authMethods != null) { + for (CodegenSecurity authMethod : authMethods) { + if (authMethod.scopes != null) { + for (Map scope : authMethod.scopes) { + String name = (String) scope.get("scope"); + if (operationsScopes.containsKey(name)) { + scope.put("ident", operationsScopes.get(name)); + } else { + String ident; + if (name.startsWith("https://")) { + int pos = name.lastIndexOf('/'); + ident = name.substring(pos + 1); + } else { + ident = name; + } + scopeIndex++; + ident = toAdaIdentifier(sanitizeName(ident.replaceAll(":", "_")), "S_"); + if (operationsScopes.containsValue(ident)) { + ident = ident + "_" + scopeIndex; + } + operationsScopes.put(name, ident); + scope.put("ident", ident); + } + } + } + authMethod.name = camelize(sanitizeName(authMethod.name), true); + } + } + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaCodegen.java index 309f9a2bada..84e5443ce6c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaCodegen.java @@ -1,58 +1,17 @@ package io.swagger.codegen.languages; import java.io.File; -import java.util.*; +import java.io.IOException; +import java.io.Writer; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; import io.swagger.codegen.*; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Response; -import io.swagger.models.Swagger; -import io.swagger.models.properties.*; public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig { - protected String packageName = "swagger"; - protected String projectName = "Swagger"; - protected List> orderedModels; - protected Map> modelDepends; public AdaCodegen() { super(); - - modelNameSuffix = "_Type"; - orderedModels = new ArrayList>(); - modelDepends = new HashMap>(); - embeddedTemplateDir = templateDir = "Ada"; - - // CLI options - addOption(CodegenConstants.PROJECT_NAME, "GNAT project name", - this.projectName); - addOption(CodegenConstants.PACKAGE_NAME, "Ada package name (convention: name.space.model).", - this.modelPackage); - addOption(CodegenConstants.MODEL_PACKAGE, "Ada package for models (convention: name.space.model).", - this.modelPackage); - addOption(CodegenConstants.API_PACKAGE, "Ada package for apis (convention: name.space.api).", - this.apiPackage); - - languageSpecificPrimitives = new HashSet( - Arrays.asList("integer", "boolean", "Integer", "Character", "Boolean", "long", "float", "double", "int32_t", "int64_t")); - - typeMapping = new HashMap(); - typeMapping.put("date", "Swagger.Date"); - typeMapping.put("DateTime", "Swagger.Datetime"); - typeMapping.put("string", "Swagger.UString"); - typeMapping.put("integer", "Integer"); - typeMapping.put("long", "Swagger.Long"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("array", "Swagger.Vector"); - typeMapping.put("map", "Swagger.Map"); - typeMapping.put("object", "Swagger.Object"); - typeMapping.put("number", "Swagger.Number"); - typeMapping.put("UUID", "Swagger.UString"); - typeMapping.put("file", "Swagger.Http_Content_Type"); - typeMapping.put("binary", "Swagger.Binary"); - - super.importMapping = new HashMap(); } @Override @@ -70,36 +29,22 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig { return "Generates an Ada client implementation (beta)."; } - protected void addOption(String key, String description, String defaultValue) { - CliOption option = new CliOption(key, description); - if (defaultValue != null) - option.defaultValue(defaultValue); - cliOptions.add(option); - } - - public String toFilename(String name) { - return name.replace(".", "-").toLowerCase(); - } - @Override public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME); } - String serverPrefix = "src" + File.separator + "server" + File.separator + toFilename(modelPackage); - String clientPrefix = "src" + File.separator + "client" + File.separator + toFilename(modelPackage); - supportingFiles.add(new SupportingFile("model-spec.mustache", null, clientPrefix + "-models.ads")); - supportingFiles.add(new SupportingFile("model-body.mustache", null, clientPrefix + "-models.adb")); - supportingFiles.add(new SupportingFile("model-spec.mustache", null, serverPrefix + "-models.ads")); - supportingFiles.add(new SupportingFile("model-body.mustache", null, serverPrefix + "-models.adb")); + if (packageName == "") { + packageName = modelPackage; + } + String srcPrefix = "src" + File.separator; + String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage); + String clientPrefix = srcPrefix + "client" + File.separator + toFilename(modelPackage); + supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads")); + supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb")); supportingFiles.add(new SupportingFile("client-spec.mustache", null, clientPrefix + "-clients.ads")); supportingFiles.add(new SupportingFile("client-body.mustache", null, clientPrefix + "-clients.adb")); - supportingFiles.add(new SupportingFile("server-spec.mustache", null, serverPrefix + "-servers.ads")); - supportingFiles.add(new SupportingFile("server-body.mustache", null, serverPrefix + "-servers.adb")); - - // String title = swagger.getInfo().getTitle(); - supportingFiles.add(new SupportingFile("gnat-project.mustache", "", "project.gpr")); if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) { projectName = (String) additionalProperties.get(CodegenConstants.PROJECT_NAME); @@ -108,13 +53,47 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig { // e.g. petstore.api (package name) => petstore_api (project name) projectName = packageName.replaceAll("\\.", "_"); } + String configBaseName = modelPackage.toLowerCase(); + supportingFiles.add(new SupportingFile("gnat-project.mustache", "", toFilename(projectName) + ".gpr")); + // supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("config.gpr", "", "config.gpr")); /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ additionalProperties.put("package", this.modelPackage); + additionalProperties.put("packageConfig", configBaseName); + additionalProperties.put("packageDir", "client"); + additionalProperties.put("mainName", "client"); additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName); + + String names[] = this.modelPackage.split("\\."); + String pkgName = names[0]; + additionalProperties.put("packageLevel1", pkgName); + supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null, + "src" + File.separator + toFilename(names[0]) + ".ads")); + if (names.length > 1) { + String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads"; + pkgName = names[0] + "." + names[1]; + additionalProperties.put("packageLevel2", pkgName); + supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null, + "src" + File.separator + fileName)); + } + pkgName = this.modelPackage; + supportingFiles.add(new SupportingFile("client.mustache", null, + "src" + File.separator + toFilename(pkgName) + "-client.adb")); + additionalProperties.put("packageName", toFilename(pkgName)); + + // add lambda for mustache templates + additionalProperties.put("lambdaAdaComment", new Mustache.Lambda() { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + String content = fragment.execute(); + content = content.trim().replaceAll("\n$", ""); + writer.write(content.replaceAll("\n", "\n -- ")); + } + }); } @Override @@ -126,237 +105,4 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig { public String modelFileFolder() { return outputFolder + "/model/" + modelPackage().replace('.', File.separatorChar); } - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle - * escaping those terms here. This logic is only called if a variable - * matches the reserved words - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - return "p_" + name; // add an underscore to the name - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - - /** - * Optional - type declaration. This is a String which is used by the - * templates to instantiate your types. There is typically special handling - * for different property types - * - * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getTypeDeclaration(inner) + "_Vectors.Vector"; - } - if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return "Swagger." + getTypeDeclaration(inner) + "_Map"; - } - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); - } - // LOGGER.info("Swagger type " + swaggerType); - if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - String modelType = toModelName(swaggerType); - if (p instanceof StringProperty || p instanceof DateProperty - || p instanceof DateTimeProperty || p instanceof FileProperty - || languageSpecificPrimitives.contains(modelType)) { - return modelType; - } - - return modelPackage + ".Models." + modelType; - } - - /** - * Overrides postProcessParameter to add a vendor extension "x-is-model-type". - * This boolean indicates that the parameter comes from the model package. - * - * @param parameter CodegenParameter object to be processed. - */ - @Override - public void postProcessParameter(CodegenParameter parameter){ - // Give the base class a chance to process - super.postProcessParameter(parameter); - - boolean isModel = parameter.dataType.startsWith(modelPackage); - if (!isModel && !parameter.isPrimitiveType && !parameter.isDate - && !parameter.isString && !parameter.isContainer && !parameter.isFile) { - isModel = true; - } - parameter.vendorExtensions.put("x-is-model-type", isModel); - } - - /** - * Post process the media types (produces and consumes) for Ada code generator. - * - * For each media type, add a adaMediaType member that gives the Ada enum constant - * for the corresponding type. - * - * @param types the list of media types. - * @return the number of media types. - */ - protected int postProcessMediaTypes(List> types) { - int count = 0; - if (types != null) { - for (Map media : types) { - String mt = media.get("mediaType"); - if (mt != null) { - mt = mt.replace('/', '_'); - media.put("adaMediaType", mt.toUpperCase()); - count++; - } - } - } - return count; - } - - @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, - Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); - - if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { - Response methodResponse = findMethodResponse(operation.getResponses()); - - if (methodResponse != null) { - if (methodResponse.getSchema() != null) { - CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); - op.vendorExtensions.put("x-codegen-response", cm); - if(cm.datatype == "HttpContent") { - op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); - } - } - } - } - return op; - } - - @SuppressWarnings("unchecked") - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - List operationList = (List) operations.get("operation"); - - for (CodegenOperation op1 : operationList) { - op1.vendorExtensions.put("x-has-uniq-produces", postProcessMediaTypes(op1.produces) == 1); - op1.vendorExtensions.put("x-has-uniq-consumes", postProcessMediaTypes(op1.consumes) == 1); - op1.vendorExtensions.put("x-has-notes", op1.notes.length() > 0); - } - return objs; - } - - @Override - public Map postProcessModels(Map objs) { - // Collect the model dependencies. - List> models = (List>) objs.get("models"); - for (Map model : models) { - Object v = model.get("model"); - if (v instanceof CodegenModel) { - CodegenModel m = (CodegenModel) v; - List d = new ArrayList(); - for (CodegenProperty p : m.allVars) { - boolean isModel = false; - CodegenProperty item = p; - if (p.isContainer) { - item = p.items; - } - if (item != null && !item.isString && !item.isPrimitiveType && !item.isContainer && !item.isInteger) { - if (!d.contains(item.datatype)) { - // LOGGER.info("Model " + m.name + " uses " + p.datatype); - d.add(item.datatype); - isModel = true; - } - } - p.vendorExtensions.put("x-is-model-type", isModel); - } - modelDepends.put(m.name, d); - orderedModels.add(model); - } - } - - // Sort the models according to dependencies so that model that depend - // on others appear at end of the list. - final Map> deps = modelDepends; - Collections.sort(orderedModels, new Comparator>() { - @Override - public int compare(Map lhs, Map rhs) { - Object v = lhs.get("model"); - String lhsName = ((CodegenModel) v).name; - v = rhs.get("model"); - String rhsName = ((CodegenModel) v).name; - List lhsList = deps.get(lhsName); - List rhsList = deps.get(rhsName); - if (lhsList == rhsList) { - // LOGGER.info("First compare " + lhsName + "<" + rhsName); - return lhsName.compareTo(rhsName); - } - // Put models without dependencies first. - if (lhsList == null) { - // LOGGER.info(" Empty " + lhsName + ", no check " + rhsName); - return -1; - } - if (rhsList == null) { - // LOGGER.info(" No check " + lhsName + ", empty " + rhsName); - return 1; - } - // Put models that depend on another after. - if (lhsList.contains(rhsName)) { - // LOGGER.info(" LSH " + lhsName + " uses " + rhsName); - return 1; - } - if (rhsList.contains(lhsName)) { - // LOGGER.info(" RHS " + rhsName + " uses " + lhsName); - return -1; - } - // Put models with less dependencies first. - if (lhsList.size() < rhsList.size()) { - // LOGGER.info(" LSH size " + lhsName + " < RHS size " + rhsName); - return -1; - } - if (lhsList.size() > rhsList.size()) { - // LOGGER.info(" LSH size " + lhsName + " > RHS size " + rhsName); - return 1; - } - // Sort models on their name. - // LOGGER.info("Compare " + lhsName + "<" + rhsName); - return lhsName.compareTo(rhsName); - } - }); - /* for (Map model : orderedModels) { - Object v = model.get("model"); - if (v instanceof CodegenModel) { - CodegenModel m = (CodegenModel) v; - LOGGER.info("Order: " + m.name); - } - }*/ - return postProcessModelsEnum(objs); - } - - @Override - public Map postProcessSupportingFileData(Map objs) { - objs.put("orderedModels", orderedModels); - return super.postProcessSupportingFileData(objs); - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaServerCodegen.java new file mode 100644 index 00000000000..951ebec0f6c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaServerCodegen.java @@ -0,0 +1,111 @@ +package io.swagger.codegen.languages; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import io.swagger.codegen.*; + +public class AdaServerCodegen extends AbstractAdaCodegen implements CodegenConfig { + + public AdaServerCodegen() { + super(); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "ada-server"; + } + + @Override + public String getHelp() { + return "Generates an Ada server implementation (beta)."; + } + + @Override + public void processOpts() { + super.processOpts(); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME); + } + String srcPrefix = "src" + File.separator; + String serverPrefix = srcPrefix + "server" + File.separator + toFilename(modelPackage); + String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage); + String implPrefix = srcPrefix + toFilename(modelPackage); + supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads")); + supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb")); + supportingFiles.add(new SupportingFile("server-skeleton-spec.mustache", null, serverPrefix + "-skeletons.ads")); + supportingFiles.add(new SupportingFile("server-skeleton-body.mustache", null, serverPrefix + "-skeletons.adb")); + supportingFiles.add(new SupportingFile("server-spec.mustache", null, implPrefix + "-servers.ads")); + supportingFiles.add(new SupportingFile("server-body.mustache", null, implPrefix + "-servers.adb")); + + supportingFiles.add(new SupportingFile("swagger.mustache", "web" + File.separator + "swagger", "swagger.json")); + + if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) { + projectName = (String) additionalProperties.get(CodegenConstants.PROJECT_NAME); + } else { + // default: set project based on package name + // e.g. petstore.api (package name) => petstore_api (project name) + projectName = packageName.replaceAll("\\.", "_"); + } + String configBaseName = modelPackage.toLowerCase(); + supportingFiles.add(new SupportingFile("gnat-project.mustache", "", toFilename(projectName) + ".gpr")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("config.gpr", "", "config.gpr")); + supportingFiles.add(new SupportingFile("server-properties.mustache", "", configBaseName + ".properties")); + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("package", this.modelPackage); + additionalProperties.put("packageConfig", configBaseName); + additionalProperties.put("packageDir", "server"); + additionalProperties.put("mainName", "server"); + additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName); + + String names[] = this.modelPackage.split("\\."); + String pkgName = names[0]; + additionalProperties.put("packageLevel1", pkgName); + supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null, + "src" + File.separator + toFilename(names[0]) + ".ads")); + if (names.length > 1) { + String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads"; + pkgName = names[0] + "." + names[1]; + additionalProperties.put("packageLevel2", pkgName); + supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null, + "src" + File.separator + fileName)); + } + pkgName = this.modelPackage; + supportingFiles.add(new SupportingFile("server.mustache", null, + "src" + File.separator + toFilename(pkgName) + "-server.adb")); + additionalProperties.put("packageName", toFilename(pkgName)); + + // add lambda for mustache templates + additionalProperties.put("lambdaAdaComment", new Mustache.Lambda() { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + String content = fragment.execute(); + content = content.trim().replaceAll("\n$", ""); + writer.write(content.replaceAll("\n", "\n -- ")); + } + }); + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + "/model/" + modelPackage().replace('.', File.separatorChar); + } +} diff --git a/modules/swagger-codegen/src/main/resources/Ada/README.mustache b/modules/swagger-codegen/src/main/resources/Ada/README.mustache new file mode 100644 index 00000000000..e6f363236b7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/README.mustache @@ -0,0 +1,102 @@ +# {{appDescription}} - Swagger Ada Server + +## Overview + +This Ada server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, +you can easily generate a server stub. + +## Building + +To build the server you will need the GNAT Ada compiler as well as +the [Swagger Ada library](https://github.com/stcarrez/swagger-ada). + +When the GNAT Ada compiler and Swagger Ada libraries are installed, +run the following command: + +``` + gprbuild -p -P{{projectName}} +``` + +After the build is successfull, you will get the server binary +in bin/{{packageName}}-server and you can start it as follows: +``` + ./bin/{{packageName}}-server +``` + +## Structure of the server + +The server consists of several Ada packages that are generated from +the OpenAPI specification. + +Source file | Package | Description +------------ | ------------- | ------------- +src/{{packageName}}.ads|{{package}}|The server root package declaration +src/{{packageName}}-servers.ads|{{package}}.Servers|The server declaration and instantiation +src/{{packageName}}-servers.adb|{{package}}.Servers|The server implementation (empty stubs) +src/server/{{packageName}}-skeletons.ads|{{package}}.Skeletons|The server skeleton declaration +src/server/{{packageName}}-skeletons.adb|{{package}}.Skeletons|The server skeleton implementation +src/server/{{packageName}}-models.ads|{{package}}.Skeletons|The server model types declaration +src/server/{{packageName}}-models.adb|{{package}}.Skeletons|The server model types implementation +src/{{packageName}}-server.adb|{{package}}.Server|The server main procedure + +Files generated in **src/server** should not be modified. The server implementation +files (**src/{{packageName}}-server.ads** and **src/{{packageName}}-server.adb**) should +be modified to implement the server operations. You can also customize the server +main procedure according to your needs. + +## Server model + +The server instance is represented by the **{{package}}.Servers.Server_Type** Ada type. +The REST API will need an instance of it to make the operation call. Two server model +exists: + +* The instance per request model creates an instance of the server type for each request. +* The shared instance model shares the same instance across all concurrent REST requests. This instance is protected using an Ada protected object which holds the server instance. + +The choice of the server model is made at the compilation time by instantiating either +the **{{package}}.Skeletons.Skeleton** package or the **{{package}}.Skeletons.Shared_Instance** +package. Such instantiation is done in **src/{{packageName}}-server.ads** and the default +is to use the **Shared_Instance**. + +## Implementing a server operation + +All you have to do is implement the server operation in the **src/{{packageName}}-servers.adb** file. +The package already contains the operation with its parameters and you only have to replace +the **null** instruction by real code. + +# Documentation + +## API Documentation + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}[**{{nickname}}**]({{apiDocPath}}{{classname}}.md#{{nickname}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Models +{{#models}}{{#model}} - [{{package}}.Models.{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + +## Authorization +{{^authMethods}} All endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}}## {{{name}}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/Ada/client-body.mustache b/modules/swagger-codegen/src/main/resources/Ada/client-body.mustache index 0aa184749af..bd2632e1d6e 100644 --- a/modules/swagger-codegen/src/main/resources/Ada/client-body.mustache +++ b/modules/swagger-codegen/src/main/resources/Ada/client-body.mustache @@ -7,7 +7,7 @@ package body {{package}}.Clients is {{#operation}} -- {{summary}}{{#vendorExtensions.x-has-notes}} - -- {{unescapedNotes}}{{/vendorExtensions.x-has-notes}} + -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}} procedure {{operationId}} (Client : in out Client_Type{{#hasParams}};{{/hasParams}}{{#allParams}} {{paramName}} : in {{^isFile}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}{{package}}.Models.{{/isContainer}}{{/isPrimitiveType}}{{/isString}}{{/isFile}}{{dataType}}{{#hasMore}};{{/hasMore}}{{/allParams}}{{#returnType}}; @@ -19,8 +19,9 @@ package body {{package}}.Clients is Reply : Swagger.Value_Type; {{/returnType}} begin - Client.Set_Accept (({{#hasProduces}}{{#produces}}{{#vendorExtensions.x-has-uniq-produces}}1 => {{/vendorExtensions.x-has-uniq-produces}}Swagger.Clients.{{adaMediaType}}{{#hasMore}}, - {{/hasMore}}{{/produces}}{{/hasProduces}}));{{#hasBodyParam}} +{{#hasProduces}} + Client.Set_Accept (({{#produces}}{{#vendorExtensions.x-has-uniq-produces}}1 => {{/vendorExtensions.x-has-uniq-produces}}Swagger.Clients.{{adaMediaType}}{{#hasMore}}, + {{/hasMore}}{{/produces}}));{{/hasProduces}}{{#hasBodyParam}} Client.Initialize (Req, ({{#hasConsumes}}{{#consumes}}{{#vendorExtensions.x-has-uniq-consumes}}1 -> {{/vendorExtensions.x-has-uniq-consumes}}Swagger.Clients.{{adaMediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{/hasConsumes}}{{^hasConsumes}}1 => Swagger.Clients.APPLICATION_JSON{{/hasConsumes}}));{{#bodyParams}}{{#vendorExtensions.x-is-model-type}} {{package}}.Models.Serialize (Req.Stream, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}} diff --git a/modules/swagger-codegen/src/main/resources/Ada/client-spec.mustache b/modules/swagger-codegen/src/main/resources/Ada/client-spec.mustache index 67ca7d08c22..097356ffa89 100644 --- a/modules/swagger-codegen/src/main/resources/Ada/client-spec.mustache +++ b/modules/swagger-codegen/src/main/resources/Ada/client-spec.mustache @@ -12,7 +12,7 @@ package {{package}}.Clients is {{#operations}} {{#operation}} -- {{summary}}{{#vendorExtensions.x-has-notes}} - -- {{unescapedNotes}}{{/vendorExtensions.x-has-notes}} + -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}} procedure {{operationId}} (Client : in out Client_Type{{#hasParams}};{{/hasParams}}{{#allParams}} {{paramName}} : in {{^isFile}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}{{package}}.Models.{{/isContainer}}{{/isPrimitiveType}}{{/isString}}{{/isFile}}{{dataType}}{{#hasMore}};{{/hasMore}}{{/allParams}}{{#returnType}}; diff --git a/modules/swagger-codegen/src/main/resources/Ada/client.mustache b/modules/swagger-codegen/src/main/resources/Ada/client.mustache new file mode 100644 index 00000000000..501bad4ec7c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/client.mustache @@ -0,0 +1,43 @@ +with {{package}}.Clients; +with {{package}}.Models; +with Swagger; +with Util.Http.Clients.Curl; +with Ada.Text_IO; +with Ada.Command_Line; +with Ada.Calendar.Formatting; +with Ada.Exceptions; +procedure {{package}}.Client is + + use Ada.Text_IO; + + procedure Usage; + + Server : constant Swagger.UString := Swagger.To_UString ("http://localhost:8080/v2"); + Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; + Arg : Positive := 1; + + procedure Usage is + begin + Put_Line ("Usage: {{projectName}} {params}..."); + end Usage; + +begin + if Arg_Count <= 1 then + Usage; + return; + end if; + Util.Http.Clients.Curl.Register; + declare + Command : constant String := Ada.Command_Line.Argument (Arg); + Item : constant String := Ada.Command_Line.Argument (Arg + 1); + C : {{package}}.Clients.Client_Type; + begin + C.Set_Server (Server); + Arg := Arg + 2; + + exception + when E : Constraint_Error => + Put_Line ("Constraint error raised: " & Ada.Exceptions.Exception_Message (E)); + + end; +end {{package}}.Client; diff --git a/modules/swagger-codegen/src/main/resources/Ada/config.gpr b/modules/swagger-codegen/src/main/resources/Ada/config.gpr new file mode 100644 index 00000000000..d3533ef3398 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/config.gpr @@ -0,0 +1,88 @@ +abstract project Config is + for Source_Dirs use (); + + type Yes_No is ("yes", "no"); + + type Library_Type_Type is ("relocatable", "static"); + + type Mode_Type is ("distrib", "debug", "optimize", "profile"); + Mode : Mode_Type := external ("MODE", "debug"); + + Coverage : Yes_No := External ("COVERAGE", "no"); + Processors := External ("PROCESSORS", "1"); + + package Builder is + case Mode is + when "debug" => + for Default_Switches ("Ada") use ("-g", "-j" & Processors); + when others => + for Default_Switches ("Ada") use ("-g", "-O2", "-j" & Processors); + end case; + end Builder; + + package compiler is + warnings := ("-gnatwua"); + defaults := ("-gnat2012"); + case Mode is + when "distrib" => + for Default_Switches ("Ada") use defaults & ("-gnatafno", "-gnatVa", "-gnatwa"); + + when "debug" => + for Default_Switches ("Ada") use defaults & warnings + & ("-gnata", "-gnatVaMI", "-gnaty3abcefhiklmnprstxM99"); + + when "optimize" => + for Default_Switches ("Ada") use defaults & warnings + & ("-gnatn", "-gnatp", "-fdata-sections", "-ffunction-sections"); + + when "profile" => + for Default_Switches ("Ada") use defaults & warnings & ("-pg"); + end case; + + case Coverage is + when "yes" => + for Default_Switches ("ada") use Compiler'Default_Switches ("Ada") & + ("-fprofile-arcs", "-ftest-coverage"); + when others => + end case; + end compiler; + + package binder is + case Mode is + when "debug" => + for Default_Switches ("Ada") use ("-E"); + + when others => + for Default_Switches ("Ada") use ("-E"); + + end case; + end binder; + + package linker is + case Mode is + when "profile" => + for Default_Switches ("Ada") use ("-pg"); + + when "distrib" => + for Default_Switches ("Ada") use ("-s"); + + when "optimize" => + for Default_Switches ("Ada") use ("-Wl,--gc-sections"); + + when others => + null; + end case; + + case Coverage is + when "yes" => + for Default_Switches ("ada") use Linker'Default_Switches ("ada") & + ("-fprofile-arcs"); + when others => + end case; + end linker; + + package Ide is + for VCS_Kind use "git"; + end Ide; + +end Config; diff --git a/modules/swagger-codegen/src/main/resources/Ada/gnat-project.mustache b/modules/swagger-codegen/src/main/resources/Ada/gnat-project.mustache index f07f3006cc8..5bc6621e968 100644 --- a/modules/swagger-codegen/src/main/resources/Ada/gnat-project.mustache +++ b/modules/swagger-codegen/src/main/resources/Ada/gnat-project.mustache @@ -1,18 +1,21 @@ --- {{{appName}}} +-- {{{appName}}} -- {{{appDescription}}} -- OpenAPI spec version: 1.0.0 -- -- https://github.com/swagger-api/swagger-codegen.git -- - -- NOTE: Auto generated by the swagger code generator program. +-- NOTE: Auto generated by the swagger code generator program. with "config"; with "util"; +with "util_http"; with "asf"; +with "security"; +with "swagger"; project {{{projectName}}} is - Mains := ("{{{appName}}}-server.adb"); + Mains := ("{{{packageName}}}-{{{mainName}}}.adb"); for Main use Mains; - for Source_Dirs use ("src", "src/client", "src/server"); + for Source_Dirs use ("src", "src/model", "src/{{{packageDir}}}"); for Object_Dir use "./" & Config'Exec_Dir & "/bin"; package Binder renames Config.Binder; diff --git a/modules/swagger-codegen/src/main/resources/Ada/model-body.mustache b/modules/swagger-codegen/src/main/resources/Ada/model-body.mustache index 120de7b25cd..cec88232ad9 100644 --- a/modules/swagger-codegen/src/main/resources/Ada/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/Ada/model-body.mustache @@ -5,7 +5,7 @@ package body {{package}}.Models is use Swagger.Streams; {{#orderedModels}} -{{#model}} +{{#model}}{{^isArrayModel}} procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; @@ -56,7 +56,7 @@ package body {{package}}.Models is end loop; end Deserialize; -{{/model}} +{{/isArrayModel}}{{/model}} {{/orderedModels}} end {{package}}.Models; diff --git a/modules/swagger-codegen/src/main/resources/Ada/model-spec.mustache b/modules/swagger-codegen/src/main/resources/Ada/model-spec.mustache index bed1aa4207d..d994ca2c798 100644 --- a/modules/swagger-codegen/src/main/resources/Ada/model-spec.mustache +++ b/modules/swagger-codegen/src/main/resources/Ada/model-spec.mustache @@ -5,11 +5,11 @@ with Swagger.Streams; with Ada.Containers.Vectors; package {{package}}.Models is -{{#orderedModels}}{{#model}} - -- ------------------------------ - -- {{title}} - -- {{description}} - -- ------------------------------ +{{#orderedModels}}{{#model}}{{^isArrayModel}} +{{#title}} -- ------------------------------ + -- {{title}}{{#description}} + -- {{#lambdaAdaComment}}{{description}}{{/lambdaAdaComment}}{{/description}} + -- ------------------------------{{/title}} type {{classname}} is record {{#vars}} @@ -37,7 +37,9 @@ package {{package}}.Models is Name : in String; Value : out {{classname}}_Vectors.Vector); -{{/model}} +{{/isArrayModel}}{{#isArrayModel}} + subtype {{classname}} is {{arrayModelType}}_Type_Vectors.Vector; +{{/isArrayModel}}{{/model}} {{/orderedModels}} end {{package}}.Models; diff --git a/modules/swagger-codegen/src/main/resources/Ada/package-spec-level1.mustache b/modules/swagger-codegen/src/main/resources/Ada/package-spec-level1.mustache new file mode 100644 index 00000000000..3d9f3029d14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/package-spec-level1.mustache @@ -0,0 +1,14 @@ +-- {{{appName}}} +-- {{{appDescription}}} +-- ------------ EDIT NOTE ------------ +-- This file was generated with swagger-codegen. You can modify it to implement +-- the server. After you modify this file, you should add the following line +-- to the .swagger-codegen-ignore file: +-- +-- src/{{packageName}}.ads +-- +-- Then, you can drop this edit note comment. +-- ------------ EDIT NOTE ------------ +package {{packageLevel1}} is + +end {{packageLevel1}}; diff --git a/modules/swagger-codegen/src/main/resources/Ada/package-spec-level2.mustache b/modules/swagger-codegen/src/main/resources/Ada/package-spec-level2.mustache new file mode 100644 index 00000000000..70c0f494f08 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/package-spec-level2.mustache @@ -0,0 +1,14 @@ +-- {{{appName}}} +-- {{{appDescription}}} +-- ------------ EDIT NOTE ------------ +-- This file was generated with swagger-codegen. You can modify it to implement +-- the server. After you modify this file, you should add the following line +-- to the .swagger-codegen-ignore file: +-- +-- src/{{packageName}}.ads +-- +-- Then, you can drop this edit note comment. +-- ------------ EDIT NOTE ------------ +package {{packageLevel2}} is + +end {{packageLevel2}}; diff --git a/modules/swagger-codegen/src/main/resources/Ada/server-body.mustache b/modules/swagger-codegen/src/main/resources/Ada/server-body.mustache index dc1ac8c7528..9804e347728 100644 --- a/modules/swagger-codegen/src/main/resources/Ada/server-body.mustache +++ b/modules/swagger-codegen/src/main/resources/Ada/server-body.mustache @@ -1,14 +1,30 @@ -{{>licenseInfo}} +-- {{{appName}}} +-- {{{appDescription}}} +-- ------------ EDIT NOTE ------------ +-- This file was generated with swagger-codegen. You can modify it to implement +-- the server. After you modify this file, you should add the following line +-- to the .swagger-codegen-ignore file: +-- +-- src/{{packageName}}-servers.adb +-- +-- Then, you can drop this edit note comment. +-- ------------ EDIT NOTE ------------ package body {{package}}.Servers is + {{#apiInfo}} {{#apis}} {{#operations}} {{#operation}} - -- {{summary}} - -- {{notes}} - procedure {{operationId}} ({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; - {{/hasMore}}{{/allParams}}) is + -- {{summary}}{{#vendorExtensions.x-has-notes}} + -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}} + overriding + procedure {{operationId}} + (Server : in out Server_Type{{#hasParams}};{{/hasParams}} + {{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; + {{/hasMore}}{{/allParams}}{{#returnType}}; + Result : out {{returnType}}{{/returnType}}; + Context : in out Swagger.Servers.Context_Type) is begin null; end {{operationId}}; @@ -16,4 +32,5 @@ package body {{package}}.Servers is {{/operations}} {{/apis}} {{/apiInfo}} + end {{package}}.Servers; diff --git a/modules/swagger-codegen/src/main/resources/Ada/server-properties.mustache b/modules/swagger-codegen/src/main/resources/Ada/server-properties.mustache new file mode 100644 index 00000000000..654383c72f3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/server-properties.mustache @@ -0,0 +1,22 @@ +swagger.dir=web +swagger.web.enable=false +swagger.ui.enable=true + +# Configuration for log4j +log4j.rootCategory=DEBUG,console,result +log4j.appender.console=Console +log4j.appender.console.level=DEBUG +log4j.appender.console.layout=level-message +log4j.appender.result=File +log4j.appender.result.File={{projectName}}.log + +# Logger configuration +log4j.logger.log=WARN +log4j.logger.Util.Properties=DEBUG +log4j.logger.Util.Log=WARN +log4j.logger.Util=DEBUG +log4j.logger.ASF=DEBUG +log4j.logger.Util.Serialize.Mappers=WARN +log4j.logger.Util.Serialize.IO=INFO + + diff --git a/modules/swagger-codegen/src/main/resources/Ada/server-skeleton-body.mustache b/modules/swagger-codegen/src/main/resources/Ada/server-skeleton-body.mustache new file mode 100644 index 00000000000..3af43f5c9f1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/server-skeleton-body.mustache @@ -0,0 +1,231 @@ +{{>licenseInfo}} +with Swagger.Streams; +with Swagger.Servers.Operation; +package body {{package}}.Skeletons is + + package body Skeleton is + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + + package API_{{operationId}} is + new Swagger.Servers.Operation (Handler => {{operationId}}, + Method => Swagger.Servers.{{httpMethod}}, + URI => "{{path}}"); + + -- {{summary}} + procedure {{operationId}} + (Req : in out Swagger.Servers.Request'Class; + Reply : in out Swagger.Servers.Response'Class; + Stream : in out Swagger.Servers.Output_Stream'Class; + Context : in out Swagger.Servers.Context_Type) is + {{#hasBodyParam}} + Input : Swagger.Value_Type; + {{/hasBodyParam}} + Impl : Implementation_Type; + {{#allParams}} + {{paramName}} : {{dataType}}; + {{/allParams}} + {{#returnType}} + Result : {{returnType}}; + {{/returnType}} + begin + {{#authMethods}} + {{#scopes}} + if not Context.Has_Permission (ACL_{{ident}}.Permission) then + Context.Set_Error (403, "Permission denied"); + return; + end if; + {{/scopes}} + {{/authMethods}} + {{#queryParams}} + Swagger.Servers.Get_Query_Parameter (Req, "{{baseName}}", {{paramName}}); + {{/queryParams}} + {{#pathParams}} + Swagger.Servers.Get_Path_Parameter (Req, {{vendorExtensions.x-path-index}}, {{paramName}}); + {{/pathParams}} + {{#hasFormParams}} + {{#formParams}} + Swagger.Servers.Get_Parameter (Req, "{{baseName}}", {{paramName}}); + {{/formParams}} + {{/hasFormParams}} + {{#hasParams}} + {{#hasBodyParam}} + Swagger.Servers.Read (Req, Input); + {{#bodyParams}}{{#vendorExtensions.x-is-model-type}} + {{package}}.Models.Deserialize (Input, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}} + -- TODO: Serialize (Input.Stream, "{{basename}}", {{paramName}});{{/isFile}}{{^isFile}}{{^isLong}} + Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{#isLong}} + Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{/isFile}}{{/vendorExtensions.x-is-model-type}}{{/bodyParams}} + {{/hasBodyParam}} + Impl.{{operationId}} + ({{#allParams}}{{paramName}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}{{#returnType}}{{#hasParams}}, {{/hasParams}}Result{{/returnType}}, Context); + {{/hasParams}} + {{^hasParams}} + {{#returnType}} + Impl.{{operationId}} (Result, Context); + {{/returnType}} + {{^returnType}} + Impl.{{operationId}} (Context); + {{/returnType}} + {{/hasParams}} + {{#returnType}} + Stream.Start_Document;{{#vendorExtensions.x-codegen-response.isString}} + Swagger.Streams.Serialize (Stream, "", Result);{{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}{{#returnTypeIsPrimitive}} + Swagger.Streams.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}} + {{package}}.Models.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{/vendorExtensions.x-codegen-response.isString}} + Stream.End_Document;{{/returnType}} + end {{operationId}}; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + procedure Register (Server : in out Swagger.Servers.Application_Type'Class) is + begin +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + Swagger.Servers.Register (Server, API_{{operationId}}.Definition); +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + end Register; + + end Skeleton; + + package body Shared_Instance is + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + + -- {{summary}} + procedure {{operationId}} + (Req : in out Swagger.Servers.Request'Class; + Reply : in out Swagger.Servers.Response'Class; + Stream : in out Swagger.Servers.Output_Stream'Class; + Context : in out Swagger.Servers.Context_Type) is + {{#hasBodyParam}} + Input : Swagger.Value_Type; + {{/hasBodyParam}} + {{#allParams}} + {{paramName}} : {{dataType}}; + {{/allParams}} + {{#returnType}} + Result : {{returnType}}; + {{/returnType}} + begin + {{#queryParams}} + Swagger.Servers.Get_Query_Parameter (Req, "{{baseName}}", {{paramName}}); + {{/queryParams}} + {{#pathParams}} + Swagger.Servers.Get_Path_Parameter (Req, {{vendorExtensions.x-path-index}}, {{paramName}}); + {{/pathParams}} + {{#hasFormParams}} + {{#formParams}} + Swagger.Servers.Get_Parameter (Req, "{{baseName}}", {{paramName}}); + {{/formParams}} + {{/hasFormParams}} + {{#hasParams}} + {{#hasBodyParam}} + Swagger.Servers.Read (Req, Input); + {{#bodyParams}}{{#vendorExtensions.x-is-model-type}} + {{package}}.Models.Deserialize (Input, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}} + -- TODO: Serialize (Input.Stream, "{{basename}}", {{paramName}});{{/isFile}}{{^isFile}}{{^isLong}} + Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{#isLong}} + Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{/isFile}}{{/vendorExtensions.x-is-model-type}}{{/bodyParams}} + {{/hasBodyParam}} + Server.{{operationId}} + ({{#allParams}}{{paramName}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}{{#returnType}}{{#hasParams}}, {{/hasParams}}Result{{/returnType}}, Context); + {{/hasParams}} + {{^hasParams}} + {{#returnType}} + Server.{{operationId}} (Result, Context); + {{/returnType}} + {{^returnType}} + Server.{{operationId}} (Context); + {{/returnType}} + {{/hasParams}} + {{#returnType}} + Stream.Start_Document;{{#vendorExtensions.x-codegen-response.isString}} + Swagger.Streams.Serialize (Stream, "", Result);{{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}{{#returnTypeIsPrimitive}} + Swagger.Streams.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}} + {{package}}.Models.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{/vendorExtensions.x-codegen-response.isString}} + Stream.End_Document;{{/returnType}} + end {{operationId}}; + + package API_{{operationId}} is + new Swagger.Servers.Operation (Handler => {{operationId}}, + Method => Swagger.Servers.{{httpMethod}}, + URI => "{{path}}"); +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + procedure Register (Server : in out Swagger.Servers.Application_Type'Class) is + begin +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + Swagger.Servers.Register (Server, API_{{operationId}}.Definition); +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + end Register; + + protected body Server is +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + -- {{summary}} + {{#hasParams}} + procedure {{operationId}} + ({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; + {{/hasMore}}{{/allParams}}{{#returnType}}; + Result : out {{returnType}}{{/returnType}}; + Context : in out Swagger.Servers.Context_Type) is + begin + Impl.{{operationId}} + ({{#allParams}}{{paramName}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}{{#returnType}}, + Result{{/returnType}}, + Context); + end {{operationId}}; + {{/hasParams}} + {{^hasParams}} + {{#returnType}} + procedure {{operationId}} (Result : out {{returnType}}; + Context : in out Swagger.Servers.Context_Type) is + begin + Impl.{{operationId}} (Result, Context); + end {{operationId}}; + {{/returnType}} + {{^returnType}} + procedure {{operationId}} (Context : in out Swagger.Servers.Context_Type) is + begin + Impl.{{operationId}} (Context); + end {{operationId}}; + {{/returnType}} + {{/hasParams}} + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + end Server; + + end Shared_Instance; + +end {{package}}.Skeletons; diff --git a/modules/swagger-codegen/src/main/resources/Ada/server-skeleton-spec.mustache b/modules/swagger-codegen/src/main/resources/Ada/server-skeleton-spec.mustache new file mode 100644 index 00000000000..e14600dff7b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/server-skeleton-spec.mustache @@ -0,0 +1,115 @@ +{{>licenseInfo}} +{{#imports}}with {{import}}; +{{/imports}} +with Swagger.Servers; +with {{package}}.Models; +with Security.Permissions; +package {{package}}.Skeletons is + use {{package}}.Models; + type Server_Type is limited interface; +{{#authMethods}}{{#scopes}} + -- {{description}} + package ACL_{{ident}} is new Security.Permissions.Definition ("{{scope}}"); +{{/scopes}}{{/authMethods}} + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + + -- {{summary}}{{#vendorExtensions.x-has-notes}} + -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}} + procedure {{operationId}} + (Server : in out Server_Type{{#hasParams}};{{/hasParams}} + {{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; + {{/hasMore}}{{/allParams}}{{#returnType}}; + Result : out {{returnType}}{{/returnType}}; + Context : in out Swagger.Servers.Context_Type) is abstract; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + generic + type Implementation_Type is limited new Server_Type with private; + package Skeleton is + + procedure Register (Server : in out Swagger.Servers.Application_Type'Class); + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + + -- {{summary}} + procedure {{operationId}} + (Req : in out Swagger.Servers.Request'Class; + Reply : in out Swagger.Servers.Response'Class; + Stream : in out Swagger.Servers.Output_Stream'Class; + Context : in out Swagger.Servers.Context_Type); + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + end Skeleton; + + generic + type Implementation_Type is limited new Server_Type with private; + package Shared_Instance is + + procedure Register (Server : in out Swagger.Servers.Application_Type'Class); + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + + -- {{summary}} + procedure {{operationId}} + (Req : in out Swagger.Servers.Request'Class; + Reply : in out Swagger.Servers.Response'Class; + Stream : in out Swagger.Servers.Output_Stream'Class; + Context : in out Swagger.Servers.Context_Type); + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + private + protected Server is + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + -- {{summary}} + {{#hasParams}} + procedure {{operationId}} + ({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; + {{/hasMore}}{{/allParams}}{{#returnType}}; + Result : out {{returnType}}{{/returnType}}; + Context : in out Swagger.Servers.Context_Type); + {{/hasParams}} + {{^hasParams}} + {{#returnType}} + procedure {{operationId}} + (Result : out {{returnType}}; + Context : in out Swagger.Servers.Context_Type); + {{/returnType}} + {{^returnType}} + procedure {{operationId}} (Context : in out Swagger.Servers.Context_Type); + {{/returnType}} + {{/hasParams}} + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + private + Impl : Implementation_Type; + end Server; + end Shared_Instance; + +end {{package}}.Skeletons; diff --git a/modules/swagger-codegen/src/main/resources/Ada/server-spec.mustache b/modules/swagger-codegen/src/main/resources/Ada/server-spec.mustache index 0d887b15d36..c57f229f383 100644 --- a/modules/swagger-codegen/src/main/resources/Ada/server-spec.mustache +++ b/modules/swagger-codegen/src/main/resources/Ada/server-spec.mustache @@ -1,20 +1,43 @@ -{{>licenseInfo}} +-- {{{appName}}} +-- {{{appDescription}}} +-- ------------ EDIT NOTE ------------ +-- This file was generated with swagger-codegen. You can modify it to implement +-- the server. After you modify this file, you should add the following line +-- to the .swagger-codegen-ignore file: +-- +-- src/{{packageName}}-servers.ads +-- +-- Then, you can drop this edit note comment. +-- ------------ EDIT NOTE ------------ {{#imports}}with {{import}}; {{/imports}} +with Swagger.Servers; with {{package}}.Models; +with {{package}}.Skeletons; package {{package}}.Servers is + use {{package}}.Models; + type Server_Type is limited new {{package}}.Skeletons.Server_Type with null record; + {{#apiInfo}} {{#apis}} {{#operations}} {{#operation}} - -- {{summary}} - -- {{notes}} - procedure {{operationId}} ({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; - {{/hasMore}}{{/allParams}}); - + -- {{summary}}{{#vendorExtensions.x-has-notes}} + -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}} + overriding + procedure {{operationId}} + (Server : in out Server_Type{{#hasParams}};{{/hasParams}} + {{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; + {{/hasMore}}{{/allParams}}{{#returnType}}; + Result : out {{returnType}}{{/returnType}}; + Context : in out Swagger.Servers.Context_Type); {{/operation}} {{/operations}} {{/apis}} {{/apiInfo}} + + package Server_Impl is + new {{package}}.Skeletons.Shared_Instance (Server_Type); + end {{package}}.Servers; diff --git a/modules/swagger-codegen/src/main/resources/Ada/server.mustache b/modules/swagger-codegen/src/main/resources/Ada/server.mustache new file mode 100644 index 00000000000..08aba9f071a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/server.mustache @@ -0,0 +1,43 @@ +with Ada.IO_Exceptions; +with AWS.Config.Set; +with Swagger.Servers.AWS; +with Swagger.Servers.Applications; +with Util.Log.Loggers; +with Util.Properties; +with {{package}}.Servers; +procedure {{package}}.Server is + procedure Configure (Config : in out AWS.Config.Object); + + CONFIG_PATH : constant String := "{{packageConfig}}.properties"; + + procedure Configure (Config : in out AWS.Config.Object) is + begin + AWS.Config.Set.Server_Port (Config, 8080); + AWS.Config.Set.Max_Connection (Config, 8); + AWS.Config.Set.Accept_Queue_Size (Config, 512); + end Configure; + + App : aliased Swagger.Servers.Applications.Application_Type; + WS : Swagger.Servers.AWS.AWS_Container; + Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("{{package}}.Server"); + Props : Util.Properties.Manager; +begin + Props.Load_Properties (CONFIG_PATH); + Util.Log.Loggers.Initialize (Props); + + App.Configure (Props); + {{package}}.Servers.Server_Impl.Register (App); + + WS.Configure (Configure'Access); + WS.Register_Application ("{{basePathWithoutHost}}", App'Unchecked_Access); + App.Dump_Routes (Util.Log.INFO_LEVEL); + Log.Info ("Connect you browser to: http://localhost:8080{{basePathWithoutHost}}/ui/index.html"); + + WS.Start; + + delay 6000.0; + +exception + when Ada.IO_Exceptions.Name_Error => + Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); +end {{package}}.Server; diff --git a/modules/swagger-codegen/src/main/resources/Ada/swagger.mustache b/modules/swagger-codegen/src/main/resources/Ada/swagger.mustache new file mode 100644 index 00000000000..0a7a2006155 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Ada/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-json}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 97724a5d0e4..dbf38a7be08 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -1,4 +1,5 @@ io.swagger.codegen.languages.AdaCodegen +io.swagger.codegen.languages.AdaServerCodegen io.swagger.codegen.languages.AkkaScalaClientCodegen io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.Apache2ConfigCodegen diff --git a/samples/client/petstore/ada/.swagger-codegen-ignore b/samples/client/petstore/ada/.swagger-codegen-ignore index c5fa491b4c5..9b9a09a8588 100644 --- a/samples/client/petstore/ada/.swagger-codegen-ignore +++ b/samples/client/petstore/ada/.swagger-codegen-ignore @@ -21,3 +21,4 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md +petstore.gpr diff --git a/samples/client/petstore/ada/petstore.gpr b/samples/client/petstore/ada/petstore.gpr index ffcd99fd76c..8d28dc71535 100644 --- a/samples/client/petstore/ada/petstore.gpr +++ b/samples/client/petstore/ada/petstore.gpr @@ -1,15 +1,23 @@ +-- Swagger Petstore +-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. +-- OpenAPI spec version: 1.0.0 +-- +-- https://github.com/swagger-api/swagger-codegen.git +-- +-- NOTE: Auto generated by the swagger code generator program. with "config"; with "util"; with "util_http"; +with "asf"; +with "security"; with "swagger"; project Petstore is Mains := ("petstore.adb"); for Main use Mains; - for Source_Dirs use ("src", "src/client"); - for Object_Dir use "./obj"; - for Exec_Dir use "./bin"; - + for Source_Dirs use ("src", "src/model", "src/client"); + for Object_Dir use "./" & Config'Exec_Dir & "/bin"; + package Binder renames Config.Binder; package Builder renames Config.Builder; package Compiler renames Config.Compiler; diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb index 37e99fb6575..c9fba09ea69 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb @@ -1,5 +1,5 @@ -- Swagger Petstore --- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. +-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. -- -- OpenAPI spec version: 1.0.0 -- Contact: apiteam@swagger.io @@ -31,7 +31,7 @@ package body Samples.Petstore.Clients is procedure Delete_Pet (Client : in out Client_Type; Pet_Id : in Swagger.Long; - Api_Key : in Swagger.UString) is + Api_Key : in Swagger.Nullable_UString) is URI : Swagger.Clients.URI_Type; begin Client.Set_Accept ((Swagger.Clients.APPLICATION_XML, @@ -46,7 +46,7 @@ package body Samples.Petstore.Clients is -- Multiple status values can be provided with comma separated strings procedure Find_Pets_By_Status (Client : in out Client_Type; - Status : in Swagger.UString_Vectors.Vector; + Status : in Swagger.Nullable_UString_Vectors.Vector; Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector) is URI : Swagger.Clients.URI_Type; Reply : Swagger.Value_Type; @@ -64,7 +64,7 @@ package body Samples.Petstore.Clients is -- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. procedure Find_Pets_By_Tags (Client : in out Client_Type; - Tags : in Swagger.UString_Vectors.Vector; + Tags : in Swagger.Nullable_UString_Vectors.Vector; Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector) is URI : Swagger.Clients.URI_Type; Reply : Swagger.Value_Type; @@ -117,8 +117,8 @@ package body Samples.Petstore.Clients is procedure Update_Pet_With_Form (Client : in out Client_Type; Pet_Id : in Swagger.Long; - Name : in Swagger.UString; - Status : in Swagger.UString) is + Name : in Swagger.Nullable_UString; + Status : in Swagger.Nullable_UString) is URI : Swagger.Clients.URI_Type; Req : Swagger.Clients.Request_Type; begin @@ -137,8 +137,8 @@ package body Samples.Petstore.Clients is procedure Upload_File (Client : in out Client_Type; Pet_Id : in Swagger.Long; - Additional_Metadata : in Swagger.UString; - File : in Swagger.Http_Content_Type; + Additional_Metadata : in Swagger.Nullable_UString; + File : in Swagger.File_Part_Type; Result : out Samples.Petstore.Models.ApiResponse_Type) is URI : Swagger.Clients.URI_Type; Req : Swagger.Clients.Request_Type; @@ -156,7 +156,7 @@ package body Samples.Petstore.Clients is end Upload_File; -- Delete purchase order by ID - -- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + -- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors procedure Delete_Order (Client : in out Client_Type; Order_Id : in Swagger.UString) is @@ -174,7 +174,7 @@ package body Samples.Petstore.Clients is -- Returns a map of status codes to quantities procedure Get_Inventory (Client : in out Client_Type; - Result : out Swagger.Integer_Map) is + Result : out Swagger.Nullable_Integer_Map) is URI : Swagger.Clients.URI_Type; Reply : Swagger.Value_Type; begin @@ -186,7 +186,7 @@ package body Samples.Petstore.Clients is end Get_Inventory; -- Find purchase order by ID - -- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + -- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions procedure Get_Order_By_Id (Client : in out Client_Type; Order_Id : in Swagger.Long; diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads index e10d1ab4cd1..5821707ea0c 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads @@ -1,5 +1,5 @@ -- Swagger Petstore --- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. +-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. -- -- OpenAPI spec version: 1.0.0 -- Contact: apiteam@swagger.io @@ -22,20 +22,20 @@ package Samples.Petstore.Clients is procedure Delete_Pet (Client : in out Client_Type; Pet_Id : in Swagger.Long; - Api_Key : in Swagger.UString); + Api_Key : in Swagger.Nullable_UString); -- Finds Pets by status -- Multiple status values can be provided with comma separated strings procedure Find_Pets_By_Status (Client : in out Client_Type; - Status : in Swagger.UString_Vectors.Vector; + Status : in Swagger.Nullable_UString_Vectors.Vector; Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector); -- Finds Pets by tags -- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. procedure Find_Pets_By_Tags (Client : in out Client_Type; - Tags : in Swagger.UString_Vectors.Vector; + Tags : in Swagger.Nullable_UString_Vectors.Vector; Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector); -- Find pet by ID @@ -54,19 +54,19 @@ package Samples.Petstore.Clients is procedure Update_Pet_With_Form (Client : in out Client_Type; Pet_Id : in Swagger.Long; - Name : in Swagger.UString; - Status : in Swagger.UString); + Name : in Swagger.Nullable_UString; + Status : in Swagger.Nullable_UString); -- uploads an image procedure Upload_File (Client : in out Client_Type; Pet_Id : in Swagger.Long; - Additional_Metadata : in Swagger.UString; - File : in Swagger.Http_Content_Type; + Additional_Metadata : in Swagger.Nullable_UString; + File : in Swagger.File_Part_Type; Result : out Samples.Petstore.Models.ApiResponse_Type); -- Delete purchase order by ID - -- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + -- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors procedure Delete_Order (Client : in out Client_Type; Order_Id : in Swagger.UString); @@ -75,10 +75,10 @@ package Samples.Petstore.Clients is -- Returns a map of status codes to quantities procedure Get_Inventory (Client : in out Client_Type; - Result : out Swagger.Integer_Map); + Result : out Swagger.Nullable_Integer_Map); -- Find purchase order by ID - -- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + -- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions procedure Get_Order_By_Id (Client : in out Client_Type; Order_Id : in Swagger.Long; diff --git a/samples/client/petstore/ada/src/client/samples-petstore-models.adb b/samples/client/petstore/ada/src/model/samples-petstore-models.adb similarity index 99% rename from samples/client/petstore/ada/src/client/samples-petstore-models.adb rename to samples/client/petstore/ada/src/model/samples-petstore-models.adb index 2c2cf97126d..542b67a2fd9 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-models.adb +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.adb @@ -1,5 +1,5 @@ -- Swagger Petstore --- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. +-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. -- -- OpenAPI spec version: 1.0.0 -- Contact: apiteam@swagger.io @@ -13,6 +13,7 @@ package body Samples.Petstore.Models is use Swagger.Streams; + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in ApiResponse_Type) is @@ -61,6 +62,8 @@ package body Samples.Petstore.Models is end Deserialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Category_Type) is @@ -107,6 +110,8 @@ package body Samples.Petstore.Models is end Deserialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Tag_Type) is @@ -153,6 +158,8 @@ package body Samples.Petstore.Models is end Deserialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in User_Type) is @@ -211,6 +218,8 @@ package body Samples.Petstore.Models is end Deserialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Order_Type) is @@ -265,6 +274,8 @@ package body Samples.Petstore.Models is end Deserialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Pet_Type) is @@ -319,4 +330,5 @@ package body Samples.Petstore.Models is end Deserialize; + end Samples.Petstore.Models; diff --git a/samples/client/petstore/ada/src/client/samples-petstore-models.ads b/samples/client/petstore/ada/src/model/samples-petstore-models.ads similarity index 86% rename from samples/client/petstore/ada/src/client/samples-petstore-models.ads rename to samples/client/petstore/ada/src/model/samples-petstore-models.ads index 81152ad52cc..9a5759d85e4 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-models.ads +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.ads @@ -1,5 +1,5 @@ -- Swagger Petstore --- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. +-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. -- -- OpenAPI spec version: 1.0.0 -- Contact: apiteam@swagger.io @@ -18,9 +18,9 @@ package Samples.Petstore.Models is -- ------------------------------ type ApiResponse_Type is record - Code : Integer; - P_Type : Swagger.UString; - Message : Swagger.UString; + Code : Swagger.Nullable_Integer; + P_Type : Swagger.Nullable_UString; + Message : Swagger.Nullable_UString; end record; package ApiResponse_Type_Vectors is @@ -44,14 +44,15 @@ package Samples.Petstore.Models is Value : out ApiResponse_Type_Vectors.Vector); + -- ------------------------------ -- Pet category -- A category for a pet -- ------------------------------ type Category_Type is record - Id : Swagger.Long; - Name : Swagger.UString; + Id : Swagger.Nullable_Long; + Name : Swagger.Nullable_UString; end record; package Category_Type_Vectors is @@ -75,14 +76,15 @@ package Samples.Petstore.Models is Value : out Category_Type_Vectors.Vector); + -- ------------------------------ -- Pet Tag -- A tag for a pet -- ------------------------------ type Tag_Type is record - Id : Swagger.Long; - Name : Swagger.UString; + Id : Swagger.Nullable_Long; + Name : Swagger.Nullable_UString; end record; package Tag_Type_Vectors is @@ -106,20 +108,21 @@ package Samples.Petstore.Models is Value : out Tag_Type_Vectors.Vector); + -- ------------------------------ -- a User -- A User who is purchasing from the pet store -- ------------------------------ type User_Type is record - Id : Swagger.Long; - Username : Swagger.UString; - First_Name : Swagger.UString; - Last_Name : Swagger.UString; - Email : Swagger.UString; - Password : Swagger.UString; - Phone : Swagger.UString; - User_Status : Integer; + Id : Swagger.Nullable_Long; + Username : Swagger.Nullable_UString; + First_Name : Swagger.Nullable_UString; + Last_Name : Swagger.Nullable_UString; + Email : Swagger.Nullable_UString; + Password : Swagger.Nullable_UString; + Phone : Swagger.Nullable_UString; + User_Status : Swagger.Nullable_Integer; end record; package User_Type_Vectors is @@ -143,18 +146,19 @@ package Samples.Petstore.Models is Value : out User_Type_Vectors.Vector); + -- ------------------------------ -- Pet Order -- An order for a pets from the pet store -- ------------------------------ type Order_Type is record - Id : Swagger.Long; - Pet_Id : Swagger.Long; - Quantity : Integer; - Ship_Date : Swagger.Datetime; - Status : Swagger.UString; - Complete : Boolean; + Id : Swagger.Nullable_Long; + Pet_Id : Swagger.Nullable_Long; + Quantity : Swagger.Nullable_Integer; + Ship_Date : Swagger.Nullable_Date; + Status : Swagger.Nullable_UString; + Complete : Swagger.Nullable_Boolean; end record; package Order_Type_Vectors is @@ -178,18 +182,19 @@ package Samples.Petstore.Models is Value : out Order_Type_Vectors.Vector); + -- ------------------------------ -- a Pet -- A pet for sale in the pet store -- ------------------------------ type Pet_Type is record - Id : Swagger.Long; + Id : Swagger.Nullable_Long; Category : Samples.Petstore.Models.Category_Type; Name : Swagger.UString; - Photo_Urls : Swagger.UString_Vectors.Vector; + Photo_Urls : Swagger.Nullable_UString_Vectors.Vector; Tags : Samples.Petstore.Models.Tag_Type_Vectors.Vector; - Status : Swagger.UString; + Status : Swagger.Nullable_UString; end record; package Pet_Type_Vectors is @@ -213,4 +218,5 @@ package Samples.Petstore.Models is Value : out Pet_Type_Vectors.Vector); + end Samples.Petstore.Models; diff --git a/samples/client/petstore/ada/src/petstore.adb b/samples/client/petstore/ada/src/petstore.adb index b14200f0001..9c1db2490ad 100644 --- a/samples/client/petstore/ada/src/petstore.adb +++ b/samples/client/petstore/ada/src/petstore.adb @@ -5,10 +5,12 @@ with Util.Http.Clients.Curl; with Ada.Text_IO; with Ada.Command_Line; with Ada.Calendar.Formatting; +with Ada.Strings.Unbounded; with Ada.Exceptions; procedure Test is use Ada.Text_IO; + use type Ada.Strings.Unbounded.Unbounded_String; procedure Usage; procedure Print_Pet (Pet : in Samples.Petstore.Models.Pet_Type); @@ -48,14 +50,14 @@ procedure Test is procedure Print_Pet (Pet : in Samples.Petstore.Models.Pet_Type) is Need_Indent : Boolean := False; begin - Put_Line ("Id : " & Swagger.Long'Image (Pet.Id)); + Put_Line ("Id : " & Swagger.Long'Image (Pet.Id.Value)); Put_Line ("Name : " & Swagger.To_String (Pet.Name)); - Put_Line ("Status : " & Swagger.To_String (Pet.Status)); + Put_Line ("Status : " & Swagger.To_String (Pet.Status.Value)); if not Pet.Tags.Is_Empty then Put ("Tags : "); for Tag of Pet.Tags loop Put_Line ((if Need_Indent then " " else "") - & Swagger.To_String (Tag.Name)); + & Swagger.To_String (Tag.Name.Value)); Need_Indent := True; end loop; end if; @@ -63,7 +65,7 @@ procedure Test is Need_Indent := False; Put ("URLs : "); for Url of Pet.Photo_Urls loop - Put_Line ((if Need_Indent then " " else "") & Url); + Put_Line ((if Need_Indent then " " else "") & Swagger.To_String (Url.Value)); Need_Indent := True; end loop; end if; @@ -71,12 +73,12 @@ procedure Test is procedure Print_Order (Order : in Samples.Petstore.Models.Order_Type) is begin - Put_Line ("Id : " & Swagger.Long'Image (Order.Id)); - Put_Line ("Pet id : " & Swagger.Long'Image (Order.Pet_Id)); - Put_Line ("Quantity : " & Integer'Image (Order.Quantity)); - Put_Line ("Status : " & Swagger.To_String (Order.Status)); - Put_Line ("Ship date : " & Ada.Calendar.Formatting.Image (Order.Ship_Date)); - Put_Line ("Complete : " & Boolean'Image (Order.Complete)); + Put_Line ("Id : " & Swagger.Long'Image (Order.Id.Value)); + Put_Line ("Pet id : " & Swagger.Long'Image (Order.Pet_Id.Value)); + Put_Line ("Quantity : " & Integer'Image (Order.Quantity.Value)); + Put_Line ("Status : " & Swagger.To_String (Order.Status.Value)); + Put_Line ("Ship date : " & Ada.Calendar.Formatting.Image (Order.Ship_Date.Value)); + Put_Line ("Complete : " & Boolean'Image (Order.Complete.Value)); end Print_Order; procedure Get_User (C : in out Samples.Petstore.Clients.Client_Type) is @@ -85,13 +87,13 @@ procedure Test is begin for I in Arg .. Arg_Count loop C.Get_User_By_Name (Swagger.To_UString (Ada.Command_Line.Argument (I)), User); - Put_Line ("Id : " & Swagger.Long'Image (User.Id)); - Put_Line ("Username : " & Swagger.To_String (User.Username)); - Put_Line ("Firstname: " & Swagger.To_String (User.First_Name)); - Put_Line ("Lastname : " & Swagger.To_String (User.Last_Name)); - Put_Line ("Email : " & Swagger.To_String (User.Email)); - Put_Line ("Password : " & Swagger.To_String (User.Password)); - Put_Line ("Phone : " & Swagger.To_String (User.Phone)); + Put_Line ("Id : " & Swagger.Long'Image (User.Id.Value)); + Put_Line ("Username : " & Swagger.To_String (User.Username.Value)); + Put_Line ("Firstname: " & Swagger.To_String (User.First_Name.Value)); + Put_Line ("Lastname : " & Swagger.To_String (User.Last_Name.Value)); + Put_Line ("Email : " & Swagger.To_String (User.Email.Value)); + Put_Line ("Password : " & Swagger.To_String (User.Password.Value)); + Put_Line ("Phone : " & Swagger.To_String (User.Phone.Value)); end loop; end Get_User; @@ -128,10 +130,10 @@ procedure Test is begin for I in Arg .. Arg_Count loop declare - Status : Swagger.UString_Vectors.Vector; + Status : Swagger.Nullable_UString_Vectors.Vector; P : constant String := Ada.Command_Line.Argument (I); begin - Status.Append (P); + Status.Append ((Is_Null => False, Value => Swagger.To_UString (P))); C.Find_Pets_By_Status (Status, Pets); for Pet of Pets loop Print_Pet (Pet); @@ -141,17 +143,17 @@ procedure Test is end List_Pet; procedure List_Inventory (C : in out Samples.Petstore.Clients.Client_Type) is - List : Swagger.Integer_Map; - Iter : Swagger.Integer_Maps.Cursor; + List : Swagger.Nullable_Integer_Map; + Iter : Swagger.Nullable_Integer_Maps.Cursor; begin C.Get_Inventory (List); Ada.Text_IO.Put_Line ("Inventory size " & Natural'Image (Natural (List.Length))); Iter := List.First; - while Swagger.Integer_Maps.Has_Element (Iter) loop - Put (Swagger.Integer_Maps.Key (Iter)); + while Swagger.Nullable_Integer_Maps.Has_Element (Iter) loop + Put (Swagger.Nullable_Integer_Maps.Key (Iter)); Set_Col (70); - Put_Line (Natural'Image (Swagger.Integer_Maps.Element (Iter))); - Swagger.Integer_Maps.Next (Iter); + Put_Line (Natural'Image (Swagger.Nullable_Integer_Maps.Element (Iter).Value)); + Swagger.Nullable_Integer_Maps.Next (Iter); end loop; end List_Inventory; @@ -174,11 +176,14 @@ procedure Test is Usage; return; end if; - Pet.Id := Swagger.Long'Value (Ada.Command_Line.Argument (Arg)); + Pet.Id := (Is_Null => False, Value => Swagger.Long'Value (Ada.Command_Line.Argument (Arg))); Pet.Name := Swagger.To_UString (Ada.Command_Line.Argument (Arg + 1)); - Pet.Status := Swagger.To_UString (Ada.Command_Line.Argument (Arg + 2)); - Pet.Category.Id := Swagger.Long'Value (Ada.Command_Line.Argument (Arg + 3)); - Pet.Category.Name := Swagger.To_UString (Ada.Command_Line.Argument (Arg + 4)); + Pet.Status := (Is_Null => False, + Value => Swagger.To_UString (Ada.Command_Line.Argument (Arg + 2))); + Pet.Category.Id := (Is_Null => False, + Value => Swagger.Long'Value (Ada.Command_Line.Argument (Arg + 3))); + Pet.Category.Name := (Is_Null => False, + Value => Swagger.To_UString (Ada.Command_Line.Argument (Arg + 4))); C.Add_Pet (Pet); end Add_Pet; @@ -201,7 +206,8 @@ procedure Test is begin Arg := Arg + 1; for I in Arg .. Arg_Count loop - C.Delete_Pet (Swagger.Long'Value (Ada.Command_Line.Argument (I)), Key); + C.Delete_Pet (Swagger.Long'Value (Ada.Command_Line.Argument (I)), + (Is_Null => False, Value => Key)); end loop; end Delete_Pet; diff --git a/samples/client/petstore/ada/src/samples-petstore.ads b/samples/client/petstore/ada/src/samples-petstore.ads index c5292a19abf..18194660470 100644 --- a/samples/client/petstore/ada/src/samples-petstore.ads +++ b/samples/client/petstore/ada/src/samples-petstore.ads @@ -1,2 +1,14 @@ +-- Swagger Petstore +-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. +-- ------------ EDIT NOTE ------------ +-- This file was generated with swagger-codegen. You can modify it to implement +-- the server. After you modify this file, you should add the following line +-- to the .swagger-codegen-ignore file: +-- +-- src/samples-petstore.ads +-- +-- Then, you can drop this edit note comment. +-- ------------ EDIT NOTE ------------ package Samples.Petstore is -end Samples.Petstore; \ No newline at end of file + +end Samples.Petstore; diff --git a/samples/client/petstore/ada/src/samples.ads b/samples/client/petstore/ada/src/samples.ads index af66cc10aa8..ff6bb421800 100644 --- a/samples/client/petstore/ada/src/samples.ads +++ b/samples/client/petstore/ada/src/samples.ads @@ -1,2 +1,14 @@ +-- Swagger Petstore +-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. +-- ------------ EDIT NOTE ------------ +-- This file was generated with swagger-codegen. You can modify it to implement +-- the server. After you modify this file, you should add the following line +-- to the .swagger-codegen-ignore file: +-- +-- src/samples-petstore.ads +-- +-- Then, you can drop this edit note comment. +-- ------------ EDIT NOTE ------------ package Samples is -end Samples; \ No newline at end of file + +end Samples; From f9105c8bdcba329e9b927dbdfa2dcb7b82eac36c Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 7 Jan 2018 18:47:24 +0800 Subject: [PATCH 12/13] deploy snapshot version 2.3.1 --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 49fca1cd8eb..82d84700400 100644 --- a/.travis.yml +++ b/.travis.yml @@ -87,10 +87,10 @@ script: #after_success: # push a snapshot version to maven repo - #- if [ $SONATYPE_USERNAME ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_BRANCH" = "master" ]; then - # mvn clean deploy --settings .travis/settings.xml; - # echo "Finished mvn clean deploy for $TRAVIS_BRANCH"; - # fi; + - if [ $SONATYPE_USERNAME ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_BRANCH" = "master" ]; then + mvn clean deploy --settings .travis/settings.xml; + echo "Finished mvn clean deploy for $TRAVIS_BRANCH"; + fi; env: - DOCKER_GENERATOR_IMAGE_NAME=swaggerapi/swagger-generator DOCKER_CODEGEN_CLI_IMAGE_NAME=swaggerapi/swagger-codegen-cli From 14e7158164006e4a6eb0d14002e4b96987957d73 Mon Sep 17 00:00:00 2001 From: Greg Marzouka Date: Sun, 7 Jan 2018 09:50:30 -0500 Subject: [PATCH 13/13] [Scala] Fix missing json4s import (#7271) * [Scala] Fix missing json4s import Closes #7270 * Update petstore sample --- .../src/main/resources/scala/api.mustache | 2 + .../scala/.swagger-codegen/VERSION | 2 +- .../petstore-security-test/scala/build.sbt | 28 +- .../petstore-security-test/scala/pom.xml | 474 +++++++++--------- .../scala/io/swagger/client/ApiInvoker.scala | 69 +-- .../scala/io/swagger/client/AsyncClient.scala | 4 +- .../scala/io/swagger/client/api/FakeApi.scala | 20 +- .../io/swagger/client/model/ModelReturn.scala | 2 +- .../petstore/scala/.swagger-codegen/VERSION | 2 +- samples/client/petstore/scala/build.sbt | 28 +- samples/client/petstore/scala/pom.xml | 474 +++++++++--------- .../scala/io/swagger/client/ApiInvoker.scala | 69 +-- .../scala/io/swagger/client/AsyncClient.scala | 4 +- .../scala/io/swagger/client/api/PetApi.scala | 56 ++- .../io/swagger/client/api/StoreApi.scala | 36 +- .../scala/io/swagger/client/api/UserApi.scala | 54 +- .../scala/io/swagger/client/model/Order.scala | 2 +- .../scala/io/swagger/client/model/Pet.scala | 2 +- .../scala/io/swagger/client/model/User.scala | 2 +- 19 files changed, 710 insertions(+), 620 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index e7fedfd4d4b..32b8ff5fa51 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -31,6 +31,8 @@ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} +import org.json4s._ + {{#operations}} class {{classname}}( val defBasePath: String = "{{{basePath}}}", diff --git a/samples/client/petstore-security-test/scala/.swagger-codegen/VERSION b/samples/client/petstore-security-test/scala/.swagger-codegen/VERSION index f9f7450d135..cc6612c36e0 100644 --- a/samples/client/petstore-security-test/scala/.swagger-codegen/VERSION +++ b/samples/client/petstore-security-test/scala/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +2.3.0 \ No newline at end of file diff --git a/samples/client/petstore-security-test/scala/build.sbt b/samples/client/petstore-security-test/scala/build.sbt index bececaf181b..c6b665a0c8a 100644 --- a/samples/client/petstore-security-test/scala/build.sbt +++ b/samples/client/petstore-security-test/scala/build.sbt @@ -1,22 +1,20 @@ -version := "1.0.0" - -name := "swagger-scala-client" - -organization := "io.swagger" - -scalaVersion := "2.11.8" +version := "1.0.0" +name := "swagger-scala-client" +organization := "io.swagger" +scalaVersion := "2.11.12" libraryDependencies ++= Seq( - "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.4.2", - "com.sun.jersey" % "jersey-core" % "1.19", - "com.sun.jersey" % "jersey-client" % "1.19", - "com.sun.jersey.contribs" % "jersey-multipart" % "1.19", + "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.2", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.2", + "com.sun.jersey" % "jersey-core" % "1.19.4", + "com.sun.jersey" % "jersey-client" % "1.19.4", + "com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4", "org.jfarcand" % "jersey-ahc-client" % "1.0.5", "io.swagger" % "swagger-core" % "1.5.8", - "joda-time" % "joda-time" % "2.2", - "org.joda" % "joda-convert" % "1.2", - "org.scalatest" %% "scalatest" % "2.2.4" % "test", - "junit" % "junit" % "4.8.1" % "test", + "joda-time" % "joda-time" % "2.9.9", + "org.joda" % "joda-convert" % "1.9.2", + "org.scalatest" %% "scalatest" % "3.0.4" % "test", + "junit" % "junit" % "4.12" % "test", "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" ) diff --git a/samples/client/petstore-security-test/scala/pom.xml b/samples/client/petstore-security-test/scala/pom.xml index 66cd2a4003a..2a1715f4f02 100644 --- a/samples/client/petstore-security-test/scala/pom.xml +++ b/samples/client/petstore-security-test/scala/pom.xml @@ -1,235 +1,255 @@ - 4.0.0 - io.swagger - swagger-scala-client - jar - swagger-scala-client - 1.0.0 - - 2.2.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + io.swagger + swagger-scala-client + jar + swagger-scala-client + 1.0.0 - - - maven-mongodb-plugin-repo - maven mongodb plugin repository - http://maven-mongodb-plugin.googlecode.com/svn/maven/repo - default - - + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - 1.9.1 - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - 1.7 - 1.7 - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - scala-compile-first - process-resources - - add-source - compile - - - - scala-test-compile - process-test-resources - - testCompile - - - - - - -Xms128m - -Xmx1500m - - - - - - - - - org.scala-tools - maven-scala-plugin - - ${scala-version} - - - - - - - com.fasterxml.jackson.module - jackson-module-scala_2.11 - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} - - - com.sun.jersey - jersey-client - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - org.jfarcand - jersey-ahc-client - ${jersey-async-version} - compile - - - org.scala-lang - scala-library - ${scala-version} - - - io.swagger - swagger-core - ${swagger-core-version} - - - org.scalatest - scalatest_2.11 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - - - joda-time - joda-time - ${joda-time-version} - - - org.joda - joda-convert - ${joda-version} - - - com.wordnik.swagger - swagger-async-httpclient_2.11 - ${swagger-async-httpclient-version} - - - - 2.11.12 - 1.2 - 2.2 - 1.19 - 1.5.16 - 1.0.5 - 1.0.0 - 2.8.9 + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + + 1.7 + 1.7 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + com.fasterxml.jackson.module + jackson-module-scala_2.11 + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} + compile + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.wordnik.swagger + swagger-async-httpclient_2.11 + ${swagger-async-httpclient-version} + + + + 2.11.12 + 1.9.2 + 2.9.9 + 1.19.4 + 1.5.16 + 1.0.5 + 1.0.0 + 2.9.2 - 4.8.1 - 3.1.5 - 2.2.4 - 0.3.5 + 4.12 + 3.1.5 + 3.0.4 + 0.3.5 - UTF-8 - + UTF-8 + diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala index 5d31e36a762..38916b55d44 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -38,7 +38,7 @@ import com.fasterxml.jackson.annotation._ import com.fasterxml.jackson.databind.annotation.JsonSerialize object ScalaJsonUtil { - def getJsonMapper = { + def getJsonMapper: ObjectMapper = { val mapper = new ObjectMapper() mapper.registerModule(new DefaultScalaModule()) mapper.registerModule(new JodaModule()) @@ -130,9 +130,8 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, val builder = client.resource(host + path + querystring).accept(contentType) headerParams.map(p => builder.header(p._1, p._2)) defaultHeaders.foreach(p => { - headerParams.contains(p._1) match { - case true => // override default with supplied header - case false => if (p._2 != null) builder.header(p._1, p._2) + if (!headerParams.contains(p._1) && p._2 != null) { + builder.header(p._1, p._2) } }) var formData: MultivaluedMapImpl = null @@ -142,7 +141,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } val response: ClientResponse = method match { - case "GET" => builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] + case "GET" => builder.get(classOf[ClientResponse]) case "POST" => if (formData != null && formData.size() > 0) { builder.post(classOf[ClientResponse], formData) @@ -181,46 +180,48 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, response.getStatusInfo.getStatusCode match { case 204 => "" case code: Int if Range(200, 299).contains(code) => - response.hasEntity match { - case true => response.getEntity(classOf[String]) - case false => "" + if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "" } case _ => - val entity = response.hasEntity match { - case true => response.getEntity(classOf[String]) - case false => "no data" + val entity = if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "no data" } throw new ApiException(response.getStatusInfo.getStatusCode, entity) } } def getClient(host: String): Client = { - hostMap.contains(host) match { - case true => hostMap(host) - case false => - val client = newClient(host) - // client.addFilter(new LoggingFilter()) - hostMap += host -> client - client - } + if (hostMap.contains(host)) { + hostMap(host) + } else { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } } - def newClient(host: String): Client = asyncHttpClient match { - case true => - import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig - import org.sonatype.spice.jersey.client.ahc.AhcHttpClient - import com.ning.http.client.Realm + def newClient(host: String): Client = if (asyncHttpClient) { + import com.ning.http.client.Realm + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig - val config: DefaultAhcConfig = new DefaultAhcConfig() - if (!authScheme.isEmpty) { - val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) - config - .getAsyncHttpClientConfigBuilder - .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) - .setUsePreemptiveAuth(authPreemptive).build) - } - AhcHttpClient.create(config) - case _ => Client.create() + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config + .getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } else { + Client.create() } } diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/AsyncClient.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/AsyncClient.scala index c518277f577..44b642c913c 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/AsyncClient.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/AsyncClient.scala @@ -7,8 +7,8 @@ import com.wordnik.swagger.client._ import java.io.Closeable class AsyncClient(config: SwaggerConfig) extends Closeable { - val locator = config.locator - val name = config.name + lazy val locator: ServiceLocator = config.locator + lazy val name: String = config.name private[this] val client = transportClient diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala index 05a73b29609..0aaed4e8e81 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala @@ -40,6 +40,8 @@ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} +import org.json4s._ + class FakeApi( val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r", defApiInvoker: ApiInvoker = ApiInvoker @@ -48,12 +50,12 @@ class FakeApi( implicit val formats = new org.json4s.DefaultFormats { override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") } - implicit val stringReader = ClientResponseReaders.StringReader - implicit val unitReader = ClientResponseReaders.UnitReader - implicit val jvalueReader = ClientResponseReaders.JValueReader - implicit val jsonReader = JsonFormatsReader - implicit val stringWriter = RequestWriters.StringWriter - implicit val jsonWriter = JsonFormatsWriter + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter var basePath: String = defBasePath var apiInvoker: ApiInvoker = defApiInvoker @@ -62,13 +64,14 @@ class FakeApi( apiInvoker.defaultHeaders += key -> value } - val config = SwaggerConfig.forUrl(new URI(defBasePath)) + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) val client = new RestClient(config) val helper = new FakeApiAsyncHelper(client, config) /** * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * + * * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @return void */ @@ -83,9 +86,10 @@ class FakeApi( /** * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r asynchronously * + * * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @return Future(void) - */ + */ def testCodeInject * ' " =end rn n rAsync(testCodeInjectEndRnNR: Option[String] = None) = { helper.testCodeInject * ' " =end rn n r(testCodeInjectEndRnNR) } diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala index b2ce925e121..61527518a18 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala @@ -14,7 +14,7 @@ package io.swagger.client.model case class ModelReturn ( - /* property description *_/ ' \" =end -- \\r\\n \\n \\r */ + // property description *_/ ' \" =end -- \\r\\n \\n \\r _return: Option[Integer] = None ) diff --git a/samples/client/petstore/scala/.swagger-codegen/VERSION b/samples/client/petstore/scala/.swagger-codegen/VERSION index f9f7450d135..cc6612c36e0 100644 --- a/samples/client/petstore/scala/.swagger-codegen/VERSION +++ b/samples/client/petstore/scala/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.0-SNAPSHOT \ No newline at end of file +2.3.0 \ No newline at end of file diff --git a/samples/client/petstore/scala/build.sbt b/samples/client/petstore/scala/build.sbt index bececaf181b..c6b665a0c8a 100644 --- a/samples/client/petstore/scala/build.sbt +++ b/samples/client/petstore/scala/build.sbt @@ -1,22 +1,20 @@ -version := "1.0.0" - -name := "swagger-scala-client" - -organization := "io.swagger" - -scalaVersion := "2.11.8" +version := "1.0.0" +name := "swagger-scala-client" +organization := "io.swagger" +scalaVersion := "2.11.12" libraryDependencies ++= Seq( - "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.4.2", - "com.sun.jersey" % "jersey-core" % "1.19", - "com.sun.jersey" % "jersey-client" % "1.19", - "com.sun.jersey.contribs" % "jersey-multipart" % "1.19", + "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.2", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.2", + "com.sun.jersey" % "jersey-core" % "1.19.4", + "com.sun.jersey" % "jersey-client" % "1.19.4", + "com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4", "org.jfarcand" % "jersey-ahc-client" % "1.0.5", "io.swagger" % "swagger-core" % "1.5.8", - "joda-time" % "joda-time" % "2.2", - "org.joda" % "joda-convert" % "1.2", - "org.scalatest" %% "scalatest" % "2.2.4" % "test", - "junit" % "junit" % "4.8.1" % "test", + "joda-time" % "joda-time" % "2.9.9", + "org.joda" % "joda-convert" % "1.9.2", + "org.scalatest" %% "scalatest" % "3.0.4" % "test", + "junit" % "junit" % "4.12" % "test", "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" ) diff --git a/samples/client/petstore/scala/pom.xml b/samples/client/petstore/scala/pom.xml index 66cd2a4003a..2a1715f4f02 100644 --- a/samples/client/petstore/scala/pom.xml +++ b/samples/client/petstore/scala/pom.xml @@ -1,235 +1,255 @@ - 4.0.0 - io.swagger - swagger-scala-client - jar - swagger-scala-client - 1.0.0 - - 2.2.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + io.swagger + swagger-scala-client + jar + swagger-scala-client + 1.0.0 - - - maven-mongodb-plugin-repo - maven mongodb plugin repository - http://maven-mongodb-plugin.googlecode.com/svn/maven/repo - default - - + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - 1.9.1 - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - 1.7 - 1.7 - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - scala-compile-first - process-resources - - add-source - compile - - - - scala-test-compile - process-test-resources - - testCompile - - - - - - -Xms128m - -Xmx1500m - - - - - - - - - org.scala-tools - maven-scala-plugin - - ${scala-version} - - - - - - - com.fasterxml.jackson.module - jackson-module-scala_2.11 - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} - - - com.sun.jersey - jersey-client - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - org.jfarcand - jersey-ahc-client - ${jersey-async-version} - compile - - - org.scala-lang - scala-library - ${scala-version} - - - io.swagger - swagger-core - ${swagger-core-version} - - - org.scalatest - scalatest_2.11 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - - - joda-time - joda-time - ${joda-time-version} - - - org.joda - joda-convert - ${joda-version} - - - com.wordnik.swagger - swagger-async-httpclient_2.11 - ${swagger-async-httpclient-version} - - - - 2.11.12 - 1.2 - 2.2 - 1.19 - 1.5.16 - 1.0.5 - 1.0.0 - 2.8.9 + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + + 1.7 + 1.7 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + com.fasterxml.jackson.module + jackson-module-scala_2.11 + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} + compile + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.wordnik.swagger + swagger-async-httpclient_2.11 + ${swagger-async-httpclient-version} + + + + 2.11.12 + 1.9.2 + 2.9.9 + 1.19.4 + 1.5.16 + 1.0.5 + 1.0.0 + 2.9.2 - 4.8.1 - 3.1.5 - 2.2.4 - 0.3.5 + 4.12 + 3.1.5 + 3.0.4 + 0.3.5 - UTF-8 - + UTF-8 + diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala index 75f0833d51f..26e7215ca31 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -38,7 +38,7 @@ import com.fasterxml.jackson.annotation._ import com.fasterxml.jackson.databind.annotation.JsonSerialize object ScalaJsonUtil { - def getJsonMapper = { + def getJsonMapper: ObjectMapper = { val mapper = new ObjectMapper() mapper.registerModule(new DefaultScalaModule()) mapper.registerModule(new JodaModule()) @@ -130,9 +130,8 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, val builder = client.resource(host + path + querystring).accept(contentType) headerParams.map(p => builder.header(p._1, p._2)) defaultHeaders.foreach(p => { - headerParams.contains(p._1) match { - case true => // override default with supplied header - case false => if (p._2 != null) builder.header(p._1, p._2) + if (!headerParams.contains(p._1) && p._2 != null) { + builder.header(p._1, p._2) } }) var formData: MultivaluedMapImpl = null @@ -142,7 +141,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } val response: ClientResponse = method match { - case "GET" => builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] + case "GET" => builder.get(classOf[ClientResponse]) case "POST" => if (formData != null && formData.size() > 0) { builder.post(classOf[ClientResponse], formData) @@ -181,46 +180,48 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, response.getStatusInfo.getStatusCode match { case 204 => "" case code: Int if Range(200, 299).contains(code) => - response.hasEntity match { - case true => response.getEntity(classOf[String]) - case false => "" + if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "" } case _ => - val entity = response.hasEntity match { - case true => response.getEntity(classOf[String]) - case false => "no data" + val entity = if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "no data" } throw new ApiException(response.getStatusInfo.getStatusCode, entity) } } def getClient(host: String): Client = { - hostMap.contains(host) match { - case true => hostMap(host) - case false => - val client = newClient(host) - // client.addFilter(new LoggingFilter()) - hostMap += host -> client - client - } + if (hostMap.contains(host)) { + hostMap(host) + } else { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } } - def newClient(host: String): Client = asyncHttpClient match { - case true => - import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig - import org.sonatype.spice.jersey.client.ahc.AhcHttpClient - import com.ning.http.client.Realm + def newClient(host: String): Client = if (asyncHttpClient) { + import com.ning.http.client.Realm + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig - val config: DefaultAhcConfig = new DefaultAhcConfig() - if (!authScheme.isEmpty) { - val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) - config - .getAsyncHttpClientConfigBuilder - .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) - .setUsePreemptiveAuth(authPreemptive).build) - } - AhcHttpClient.create(config) - case _ => Client.create() + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config + .getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } else { + Client.create() } } diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/AsyncClient.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/AsyncClient.scala index c518277f577..44b642c913c 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/AsyncClient.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/AsyncClient.scala @@ -7,8 +7,8 @@ import com.wordnik.swagger.client._ import java.io.Closeable class AsyncClient(config: SwaggerConfig) extends Closeable { - val locator = config.locator - val name = config.name + lazy val locator: ServiceLocator = config.locator + lazy val name: String = config.name private[this] val client = transportClient diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index bdada6d0e63..7ee97e2ae40 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -43,6 +43,8 @@ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} +import org.json4s._ + class PetApi( val defBasePath: String = "http://petstore.swagger.io/v2", defApiInvoker: ApiInvoker = ApiInvoker @@ -51,12 +53,12 @@ class PetApi( implicit val formats = new org.json4s.DefaultFormats { override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") } - implicit val stringReader = ClientResponseReaders.StringReader - implicit val unitReader = ClientResponseReaders.UnitReader - implicit val jvalueReader = ClientResponseReaders.JValueReader - implicit val jsonReader = JsonFormatsReader - implicit val stringWriter = RequestWriters.StringWriter - implicit val jsonWriter = JsonFormatsWriter + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter var basePath: String = defBasePath var apiInvoker: ApiInvoker = defApiInvoker @@ -65,13 +67,14 @@ class PetApi( apiInvoker.defaultHeaders += key -> value } - val config = SwaggerConfig.forUrl(new URI(defBasePath)) + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) val client = new RestClient(config) val helper = new PetApiAsyncHelper(client, config) /** * Add a new pet to the store * + * * @param body Pet object that needs to be added to the store * @return void */ @@ -86,9 +89,10 @@ class PetApi( /** * Add a new pet to the store asynchronously * + * * @param body Pet object that needs to be added to the store * @return Future(void) - */ + */ def addPetAsync(body: Pet) = { helper.addPet(body) } @@ -96,6 +100,7 @@ class PetApi( /** * Deletes a pet * + * * @param petId Pet id to delete * @param apiKey (optional) * @return void @@ -111,10 +116,11 @@ class PetApi( /** * Deletes a pet asynchronously * + * * @param petId Pet id to delete * @param apiKey (optional) * @return Future(void) - */ + */ def deletePetAsync(petId: Long, apiKey: Option[String] = None) = { helper.deletePet(petId, apiKey) } @@ -122,6 +128,7 @@ class PetApi( /** * Finds Pets by status * Multiple status values can be provided with comma separated strings + * * @param status Status values that need to be considered for filter * @return List[Pet] */ @@ -136,9 +143,10 @@ class PetApi( /** * Finds Pets by status asynchronously * Multiple status values can be provided with comma separated strings + * * @param status Status values that need to be considered for filter * @return Future(List[Pet]) - */ + */ def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = { helper.findPetsByStatus(status) } @@ -146,6 +154,7 @@ class PetApi( /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * * @param tags Tags to filter by * @return List[Pet] */ @@ -160,9 +169,10 @@ class PetApi( /** * Finds Pets by tags asynchronously * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * * @param tags Tags to filter by * @return Future(List[Pet]) - */ + */ def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = { helper.findPetsByTags(tags) } @@ -170,6 +180,7 @@ class PetApi( /** * Find pet by ID * Returns a single pet + * * @param petId ID of pet to return * @return Pet */ @@ -184,9 +195,10 @@ class PetApi( /** * Find pet by ID asynchronously * Returns a single pet + * * @param petId ID of pet to return * @return Future(Pet) - */ + */ def getPetByIdAsync(petId: Long): Future[Pet] = { helper.getPetById(petId) } @@ -194,6 +206,7 @@ class PetApi( /** * Update an existing pet * + * * @param body Pet object that needs to be added to the store * @return void */ @@ -208,9 +221,10 @@ class PetApi( /** * Update an existing pet asynchronously * + * * @param body Pet object that needs to be added to the store * @return Future(void) - */ + */ def updatePetAsync(body: Pet) = { helper.updatePet(body) } @@ -218,6 +232,7 @@ class PetApi( /** * Updates a pet in the store with form data * + * * @param petId ID of pet that needs to be updated * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) @@ -234,11 +249,12 @@ class PetApi( /** * Updates a pet in the store with form data asynchronously * + * * @param petId ID of pet that needs to be updated * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) * @return Future(void) - */ + */ def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = { helper.updatePetWithForm(petId, name, status) } @@ -246,6 +262,7 @@ class PetApi( /** * uploads an image * + * * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) @@ -262,11 +279,12 @@ class PetApi( /** * uploads an image asynchronously * + * * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) * @return Future(ApiResponse) - */ + */ def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = { helper.uploadFile(petId, additionalMetadata, file) } @@ -296,7 +314,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { // create path and map variables val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + replaceAll("\\{" + "petId" + "\\}", petId.toString)) // query params val queryParams = new mutable.HashMap[String, String] @@ -350,7 +368,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { // create path and map variables val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + replaceAll("\\{" + "petId" + "\\}", petId.toString)) // query params val queryParams = new mutable.HashMap[String, String] @@ -385,7 +403,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { // create path and map variables val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + replaceAll("\\{" + "petId" + "\\}", petId.toString)) // query params val queryParams = new mutable.HashMap[String, String] @@ -404,7 +422,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends )(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = { // create path and map variables val path = (addFmt("/pet/{petId}/uploadImage") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + replaceAll("\\{" + "petId" + "\\}", petId.toString)) // query params val queryParams = new mutable.HashMap[String, String] diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala index 87a3364ceb5..1d467b4c97b 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -41,6 +41,8 @@ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} +import org.json4s._ + class StoreApi( val defBasePath: String = "http://petstore.swagger.io/v2", defApiInvoker: ApiInvoker = ApiInvoker @@ -49,12 +51,12 @@ class StoreApi( implicit val formats = new org.json4s.DefaultFormats { override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") } - implicit val stringReader = ClientResponseReaders.StringReader - implicit val unitReader = ClientResponseReaders.UnitReader - implicit val jvalueReader = ClientResponseReaders.JValueReader - implicit val jsonReader = JsonFormatsReader - implicit val stringWriter = RequestWriters.StringWriter - implicit val jsonWriter = JsonFormatsWriter + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter var basePath: String = defBasePath var apiInvoker: ApiInvoker = defApiInvoker @@ -63,13 +65,14 @@ class StoreApi( apiInvoker.defaultHeaders += key -> value } - val config = SwaggerConfig.forUrl(new URI(defBasePath)) + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) val client = new RestClient(config) val helper = new StoreApiAsyncHelper(client, config) /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * * @param orderId ID of the order that needs to be deleted * @return void */ @@ -84,9 +87,10 @@ class StoreApi( /** * Delete purchase order by ID asynchronously * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * * @param orderId ID of the order that needs to be deleted * @return Future(void) - */ + */ def deleteOrderAsync(orderId: String) = { helper.deleteOrder(orderId) } @@ -94,6 +98,7 @@ class StoreApi( /** * Returns pet inventories by status * Returns a map of status codes to quantities + * * @return Map[String, Integer] */ def getInventory(): Option[Map[String, Integer]] = { @@ -107,8 +112,9 @@ class StoreApi( /** * Returns pet inventories by status asynchronously * Returns a map of status codes to quantities + * * @return Future(Map[String, Integer]) - */ + */ def getInventoryAsync(): Future[Map[String, Integer]] = { helper.getInventory() } @@ -116,6 +122,7 @@ class StoreApi( /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * * @param orderId ID of pet that needs to be fetched * @return Order */ @@ -130,9 +137,10 @@ class StoreApi( /** * Find purchase order by ID asynchronously * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * * @param orderId ID of pet that needs to be fetched * @return Future(Order) - */ + */ def getOrderByIdAsync(orderId: Long): Future[Order] = { helper.getOrderById(orderId) } @@ -140,6 +148,7 @@ class StoreApi( /** * Place an order for a pet * + * * @param body order placed for purchasing the pet * @return Order */ @@ -154,9 +163,10 @@ class StoreApi( /** * Place an order for a pet asynchronously * + * * @param body order placed for purchasing the pet * @return Future(Order) - */ + */ def placeOrderAsync(body: Order): Future[Order] = { helper.placeOrder(body) } @@ -168,7 +178,7 @@ class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extend def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { // create path and map variables val path = (addFmt("/store/order/{orderId}") - replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + replaceAll("\\{" + "orderId" + "\\}", orderId.toString)) // query params val queryParams = new mutable.HashMap[String, String] @@ -201,7 +211,7 @@ class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extend def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = { // create path and map variables val path = (addFmt("/store/order/{orderId}") - replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + replaceAll("\\{" + "orderId" + "\\}", orderId.toString)) // query params val queryParams = new mutable.HashMap[String, String] diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala index 21a510f9a4f..e223e9287b0 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -41,6 +41,8 @@ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} +import org.json4s._ + class UserApi( val defBasePath: String = "http://petstore.swagger.io/v2", defApiInvoker: ApiInvoker = ApiInvoker @@ -49,12 +51,12 @@ class UserApi( implicit val formats = new org.json4s.DefaultFormats { override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") } - implicit val stringReader = ClientResponseReaders.StringReader - implicit val unitReader = ClientResponseReaders.UnitReader - implicit val jvalueReader = ClientResponseReaders.JValueReader - implicit val jsonReader = JsonFormatsReader - implicit val stringWriter = RequestWriters.StringWriter - implicit val jsonWriter = JsonFormatsWriter + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter var basePath: String = defBasePath var apiInvoker: ApiInvoker = defApiInvoker @@ -63,13 +65,14 @@ class UserApi( apiInvoker.defaultHeaders += key -> value } - val config = SwaggerConfig.forUrl(new URI(defBasePath)) + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) val client = new RestClient(config) val helper = new UserApiAsyncHelper(client, config) /** * Create user * This can only be done by the logged in user. + * * @param body Created user object * @return void */ @@ -84,9 +87,10 @@ class UserApi( /** * Create user asynchronously * This can only be done by the logged in user. + * * @param body Created user object * @return Future(void) - */ + */ def createUserAsync(body: User) = { helper.createUser(body) } @@ -94,6 +98,7 @@ class UserApi( /** * Creates list of users with given input array * + * * @param body List of user object * @return void */ @@ -108,9 +113,10 @@ class UserApi( /** * Creates list of users with given input array asynchronously * + * * @param body List of user object * @return Future(void) - */ + */ def createUsersWithArrayInputAsync(body: List[User]) = { helper.createUsersWithArrayInput(body) } @@ -118,6 +124,7 @@ class UserApi( /** * Creates list of users with given input array * + * * @param body List of user object * @return void */ @@ -132,9 +139,10 @@ class UserApi( /** * Creates list of users with given input array asynchronously * + * * @param body List of user object * @return Future(void) - */ + */ def createUsersWithListInputAsync(body: List[User]) = { helper.createUsersWithListInput(body) } @@ -142,6 +150,7 @@ class UserApi( /** * Delete user * This can only be done by the logged in user. + * * @param username The name that needs to be deleted * @return void */ @@ -156,9 +165,10 @@ class UserApi( /** * Delete user asynchronously * This can only be done by the logged in user. + * * @param username The name that needs to be deleted * @return Future(void) - */ + */ def deleteUserAsync(username: String) = { helper.deleteUser(username) } @@ -166,6 +176,7 @@ class UserApi( /** * Get user by user name * + * * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ @@ -180,9 +191,10 @@ class UserApi( /** * Get user by user name asynchronously * + * * @param username The name that needs to be fetched. Use user1 for testing. * @return Future(User) - */ + */ def getUserByNameAsync(username: String): Future[User] = { helper.getUserByName(username) } @@ -190,6 +202,7 @@ class UserApi( /** * Logs user into the system * + * * @param username The user name for login * @param password The password for login in clear text * @return String @@ -205,10 +218,11 @@ class UserApi( /** * Logs user into the system asynchronously * + * * @param username The user name for login * @param password The password for login in clear text * @return Future(String) - */ + */ def loginUserAsync(username: String, password: String): Future[String] = { helper.loginUser(username, password) } @@ -216,6 +230,7 @@ class UserApi( /** * Logs out current logged in user session * + * * @return void */ def logoutUser() = { @@ -229,8 +244,9 @@ class UserApi( /** * Logs out current logged in user session asynchronously * + * * @return Future(void) - */ + */ def logoutUserAsync() = { helper.logoutUser() } @@ -238,6 +254,7 @@ class UserApi( /** * Updated user * This can only be done by the logged in user. + * * @param username name that need to be deleted * @param body Updated user object * @return void @@ -253,10 +270,11 @@ class UserApi( /** * Updated user asynchronously * This can only be done by the logged in user. + * * @param username name that need to be deleted * @param body Updated user object * @return Future(void) - */ + */ def updateUserAsync(username: String, body: User) = { helper.updateUser(username, body) } @@ -316,7 +334,7 @@ class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { // create path and map variables val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) + replaceAll("\\{" + "username" + "\\}", username.toString)) // query params val queryParams = new mutable.HashMap[String, String] @@ -334,7 +352,7 @@ class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { // create path and map variables val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) + replaceAll("\\{" + "username" + "\\}", username.toString)) // query params val queryParams = new mutable.HashMap[String, String] @@ -390,7 +408,7 @@ class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { // create path and map variables val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) + replaceAll("\\{" + "username" + "\\}", username.toString)) // query params val queryParams = new mutable.HashMap[String, String] diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala index fae3fddacb1..56670631540 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala @@ -19,7 +19,7 @@ case class Order ( petId: Option[Long] = None, quantity: Option[Integer] = None, shipDate: Option[Date] = None, - /* Order Status */ + // Order Status status: Option[String] = None, complete: Option[Boolean] = None ) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala index 88c868637e9..b1fdd85d799 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -19,7 +19,7 @@ case class Pet ( name: String, photoUrls: List[String], tags: Option[List[Tag]] = None, - /* pet status in the store */ + // pet status in the store status: Option[String] = None ) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala index 46183e94547..b327c74ae50 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala @@ -21,7 +21,7 @@ case class User ( email: Option[String] = None, password: Option[String] = None, phone: Option[String] = None, - /* User Status */ + // User Status userStatus: Option[Integer] = None )