diff --git a/.travis.yml b/.travis.yml index a1b712149fdd..e12db734bf1a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -133,6 +133,8 @@ after_success: cd modules/openapi-generator-gradle-plugin; ./gradlew -Psigning.keyId="$SIGNING_KEY" -Psigning.password="$SIGNING_PASSPHRASE" -Psigning.secretKeyRingFile="${TRAVIS_BUILD_DIR}/sec.gpg" -PossrhUsername="${SONATYPE_USERNAME}" -PossrhPassword="${SONATYPE_PASSWORD}" uploadArchives --no-daemon; echo "Finished ./gradlew uploadArchives"; + ./gradlew publishPlugins; + echo "Finished ./gradlew publishPlugins (plugin portal)"; popd; elif ([[ "$TRAVIS_BRANCH" =~ ^[0-9]+\.[0-9]+\.x$ ]]) ; then mvn clean deploy --settings CI/settings.xml; @@ -141,6 +143,8 @@ after_success: cd modules/openapi-generator-gradle-plugin; ./gradlew -PossrhUsername="${SONATYPE_USERNAME}" -PossrhPassword="${SONATYPE_PASSWORD}" uploadArchives --no-daemon; echo "Finished ./gradlew uploadArchives"; + ./gradlew publishPlugins; + echo "Finished ./gradlew publishPlugins (plugin portal)"; popd; fi; fi; diff --git a/docs/customization.md b/docs/customization.md index c696f4a04423..bfecdecbd97b 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -217,9 +217,13 @@ and `config.json` contains the following as an example: "apiPackage" : "petstore" } ``` +You can use also `config.yml` with following equivalent example: +```yaml +apiPackage: "petstore" +``` Supported config options can be different per language. Running `config-help -g {lang}` will show available options. -**These options are applied via configuration file (e.g. config.json) or by passing them with `-D{optionName}={optionValue}`**. (If `-D{optionName}` does not work, please open a [ticket](https://github.com/openapitools/openapi-generator/issues/new) and we'll look into it) +**These options are applied via configuration file (e.g. config.json or config.yml) or by passing them with `-D{optionName}={optionValue}`**. (If `-D{optionName}` does not work, please open a [ticket](https://github.com/openapitools/openapi-generator/issues/new) and we'll look into it) ```sh java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar config-help -g java @@ -258,6 +262,15 @@ Your config file for Java can look like } ``` +Or if you preffer yaml format it can look like + +```yaml +groupId: "com.my.company" +artifactId: "MyClient" +artifactVersion: "1.2.0" +library: "feign" +``` + For all the unspecified options default values will be used. Another way to override default options is to extend the config class for the specific language. diff --git a/docs/generators/aspnetcore.md b/docs/generators/aspnetcore.md index 63c1d810c112..fdb73387f3f7 100644 --- a/docs/generators/aspnetcore.md +++ b/docs/generators/aspnetcore.md @@ -16,13 +16,14 @@ sidebar_label: aspnetcore |packageVersion|C# package version.| |1.0.0| |packageGuid|The GUID that will be associated with the C# project| |null| |sourceFolder|source folder for generated code| |src| -|aspnetCoreVersion|ASP.NET Core version: 2.1 (default), 2.0 (deprecated)| |2.1| +|compatibilityVersion|ASP.Net Core CompatibilityVersion| |Version_2_1| +|aspnetCoreVersion|ASP.NET Core version: 2.2 (default), 2.1, 2.0 (deprecated)| |2.2| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |useSwashbuckle|Uses the Swashbuckle.AspNetCore NuGet package for documentation.| |true| -|classModifier|Class modifiers such as abstract or partial| || -|operationModifier|Operation modifiers such as virtual or abstract.| |virtual| +|classModifier|Class Modifier can be empty, abstract| || +|operationModifier|Operation Modifier can be virtual, abstract or partial| |virtual| +|buildTarget|Target to build an application or library| |program| |generateBody|Generates method body.| |true| -|buildTarget|Target the build for a program or library.| |program| diff --git a/docs/usage.md b/docs/usage.md index 284ba9e9f344..abd221e5c3ae 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -480,7 +480,7 @@ NOTE: `import-mappings` is assigned a key-value pair in this example, but multip #### Configuration File -Rather than passing generator options in a CSV of `--additional-properties`, you may also provide the settings via JSON file. +Rather than passing generator options in a CSV of `--additional-properties`, you may also provide the settings via JSON file or YAML file. For example, one of our typescript samples has the following configuration file: @@ -500,3 +500,21 @@ These settings can be passed via `-c filename`. Here, we've saved the above as ` openapi-generator generate -i petstore.yaml -g typescript-fetch -o out \ -c config.json ``` + +Same configuration file can be passed into YAML format having following equivalent content: + +```yaml +npmName: "@swagger/typescript-fetch-petstore" +npmVersion: "1.0.0" +npmRepository: "https://skimdb.npmjs.com/registry" +snapshot: false +supportsES6: true +``` + +The settings are passed exactly the same as for `config.json`. The most important part is the file extension. Supported values are `yml` or `yaml`. +The name of the file should be `config.yml` or `config.yaml` (in our example it will be `config.yaml`. + +```bash +openapi-generator generate -i petstore.yaml -g typescript-fetch -o out \ + -c config.yaml +``` diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java index 8f1082039453..f68e93ce29fb 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java @@ -17,10 +17,23 @@ package org.openapitools.codegen.cmd; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsvList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applySystemPropertiesKvpList; +import static org.openapitools.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvpList; + import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.spi.FilterAttachable; import io.airlift.airline.Command; import io.airlift.airline.Option; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; import org.openapitools.codegen.ClientOptInput; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.DefaultGenerator; @@ -29,14 +42,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; - /** * User: lanwen Date: 24.03.15 Time: 20:22 */ @@ -82,8 +87,9 @@ public class Generate implements Runnable { @Option( name = {"-c", "--config"}, title = "configuration file", - description = "Path to json configuration file. " - + "File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} " + description = "Path to configuration file configuration file. It can be json or yaml." + + "If file is json, the content should have the format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...}." + + "If file is yaml, the content should have the format optionKey: optionValue" + "Supported options can be different for each language. Run config-help -g {generator name} command for language specific config options.") private String configFile; diff --git a/modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/GenerateTest.java b/modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/GenerateTest.java index dea73a301efd..2738eebfac9d 100644 --- a/modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/GenerateTest.java +++ b/modules/openapi-generator-cli/src/test/java/org/openapitools/codegen/cmd/GenerateTest.java @@ -218,7 +218,7 @@ public void testSystemProperties() throws Exception { @Test - public void testConfig() throws Exception { + public void testConfigJson() throws Exception { setupAndRunTest("-i", "src/test/resources/swagger.yaml", "-g", "java", "-o", "src/main/java", true, "config.json", "-c", "config.json"); @@ -237,6 +237,26 @@ public void testConfig() throws Exception { }; } + @Test + public void testConfigYaml() throws Exception { + + setupAndRunTest("-i", "src/test/resources/swagger.yaml", "-g", "java", "-o", "src/main/java", true, + "config.yaml", "-c", "config.yaml"); + + new FullVerifications() { + { + } + }; + + setupAndRunTest("-i", "src/test/resources/swagger.yaml", "-g", "java", "-o", "src/main/java", true, + "config.yaml", "--config", "config.yaml"); + + new FullVerifications() { + { + } + }; + } + @Test public void testSkipOverwrite() throws Exception { diff --git a/modules/openapi-generator-gradle-plugin/build.gradle b/modules/openapi-generator-gradle-plugin/build.gradle index 42be781a4de7..346deef7c4b6 100644 --- a/modules/openapi-generator-gradle-plugin/build.gradle +++ b/modules/openapi-generator-gradle-plugin/build.gradle @@ -11,10 +11,14 @@ buildscript { maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { + url "https://plugins.gradle.org/m2/" + } } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "gradle.plugin.org.gradle.kotlin:gradle-kotlin-dsl-plugins:1.0-rc-3" + classpath "com.gradle.publish:plugin-publish-plugin:0.10.1" } } @@ -29,6 +33,7 @@ specifications as part of your build. Other tasks are available as command line """ ext.isReleaseVersion = !version.endsWith("SNAPSHOT") +apply plugin: 'com.gradle.plugin-publish' apply plugin: 'java-gradle-plugin' apply plugin: 'maven' apply plugin: 'signing' @@ -39,6 +44,7 @@ sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { + jcenter() mavenCentral() mavenLocal() maven { @@ -90,6 +96,23 @@ gradlePlugin { } } +pluginBundle { + // These settings are set for the whole plugin bundle + website = 'https://openapi-generator.tech/' + vcsUrl = 'https://github.com/OpenAPITools/openapi-generator' + description = 'OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)' + + plugins { + // first plugin + openApiGenerator { + id = 'org.openapi.generator' + displayName = 'OpenAPI Generator Gradle Plugin' + tags = ['openapi-3.0', 'openapi-2.0', 'openapi', 'swagger', 'codegen', 'sdk'] + version = "$openApiGeneratorVersion" + } + } +} + // signing will require three keys to be defined: signing.keyId, signing.password, and signing.secretKeyRingFile. // These can be passed to the gradle command: // ./gradlew -Psigning.keyId=yourid diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java index 0854b2e8593c..45241c9e6377 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CliOption.java @@ -28,6 +28,7 @@ public class CliOption { private String description; private String type; private String defaultValue; + private String optValue; private Map enumValues; public CliOption(String opt, String description) { @@ -73,6 +74,17 @@ public CliOption defaultValue(String defaultValue) { return this; } + public String getOptValue() { + return this.optValue; + } + public void setOptValue(String optValue) { + if (this.enumValues!=null && this.enumValues.containsKey(optValue)) { + this.optValue = optValue; + } else { + this.optValue = null; + } + } + public CliOption addEnum(String value, String description) { if (this.enumValues == null) { this.enumValues = new LinkedHashMap(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index a1bdb827ea50..64aa97b280f3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -17,41 +17,66 @@ package org.openapitools.codegen.config; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.parser.OpenAPIParser; import io.swagger.v3.core.util.Json; +import io.swagger.v3.core.util.Yaml; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.parser.core.models.AuthorizationValue; import io.swagger.v3.parser.core.models.ParseOptions; import io.swagger.v3.parser.core.models.SwaggerParseResult; +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.Validate; -import org.openapitools.codegen.*; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.ClientOpts; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenConfigLoader; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.SpecValidationException; import org.openapitools.codegen.auth.AuthParser; -import org.openapitools.codegen.languages.*; +import org.openapitools.codegen.languages.CSharpNancyFXServerCodegen; +import org.openapitools.codegen.languages.CppQt5ClientCodegen; +import org.openapitools.codegen.languages.CppRestSdkClientCodegen; +import org.openapitools.codegen.languages.CppTizenClientCodegen; +import org.openapitools.codegen.languages.JavaJerseyServerCodegen; +import org.openapitools.codegen.languages.PhpLumenServerCodegen; +import org.openapitools.codegen.languages.PhpSlimServerCodegen; +import org.openapitools.codegen.languages.PhpZendExpressivePathHandlerServerCodegen; +import org.openapitools.codegen.languages.RubySinatraServerCodegen; +import org.openapitools.codegen.languages.ScalaAkkaClientCodegen; +import org.openapitools.codegen.languages.ScalaHttpClientCodegen; +import org.openapitools.codegen.languages.SwiftClientCodegen; import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.nio.file.Paths; -import java.util.*; - -import static org.apache.commons.lang3.StringUtils.isNotEmpty; - /** - * A class that contains all codegen configuration properties a user would want to manipulate. - * An instance could be created by deserializing a JSON file or being populated from CLI or Maven plugin parameters. - * It also has a convenience method for creating a ClientOptInput class which is THE object DefaultGenerator.java needs - * to generate code. + * A class that contains all codegen configuration properties a user would want to manipulate. An + * instance could be created by deserializing a JSON file or being populated from CLI or Maven + * plugin parameters. It also has a convenience method for creating a ClientOptInput class which is + * THE object DefaultGenerator.java needs to generate code. */ public class CodegenConfigurator implements Serializable { public static final Logger LOGGER = LoggerFactory.getLogger(CodegenConfigurator.class); - private static Map nameMigrationMap = new HashMap<>(); + private static Map nameMigrationMap = new HashMap<>(); + static { nameMigrationMap.put("akka-scala", new ScalaAkkaClientCodegen().getName()); nameMigrationMap.put("scala", new ScalaHttpClientCodegen().getName()); @@ -94,14 +119,15 @@ public class CodegenConfigurator implements Serializable { private Map additionalProperties = new HashMap(); private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); - private Map reservedWordMappings = new HashMap(); + private Map reservedWordMappings = new HashMap(); - private String gitUserId="GIT_USER_ID"; - private String gitRepoId="GIT_REPO_ID"; - private String releaseNote="Minor update"; + private String gitUserId = "GIT_USER_ID"; + private String gitRepoId = "GIT_REPO_ID"; + private String releaseNote = "Minor update"; private String httpUserAgent; - private final Map dynamicProperties = new HashMap(); //the map that holds the JsonAnySetter/JsonAnyGetter values + private final Map dynamicProperties = new HashMap(); + //the map that holds the JsonAnySetter/JsonAnyGetter values public CodegenConfigurator() { this.validateSpec = true; @@ -109,18 +135,21 @@ public CodegenConfigurator() { } // TODO: When setLang is removed, please remove nameMigrationMap and its usage(s). + /** - * Set the "language". This has drifted away from language-only to include framework and hyphenated generator types as well as language. + * Set the "language". This has drifted away from language-only to include framework and + * hyphenated generator types as well as language. *

- * NOTE: This will eventually become language only again. It is deprecated in its current state. + * NOTE: This will eventually become language only again. It is deprecated in its current + * state. *

* - * @deprecated Please use {@link #setGeneratorName(String)}, as generators are no longer identified only by language. We may reuse language in the future. * @param lang The generator name. Previously, language name only. * @return The fluent instance of {@link CodegenConfigurator} + * @deprecated Please use {@link #setGeneratorName(String)}, as generators are no longer + * identified only by language. We may reuse language in the future. */ - @Deprecated - public CodegenConfigurator setLang(String lang) { + @Deprecated public CodegenConfigurator setLang(String lang) { this.setGeneratorName(lang); return this; } @@ -128,8 +157,8 @@ public CodegenConfigurator setLang(String lang) { /** * Sets the name of the target generator. * - * The generator's name is used to uniquely identify the generator as a mechanism to lookup the desired implementation - * at runtime. + * The generator's name is used to uniquely identify the generator as a mechanism to lookup the + * desired implementation at runtime. * * @param generatorName The name of the generator. * @return The fluent instance of {@link CodegenConfigurator} @@ -137,7 +166,9 @@ public CodegenConfigurator setLang(String lang) { public CodegenConfigurator setGeneratorName(final String generatorName) { if (nameMigrationMap.containsKey(generatorName)) { String newValue = nameMigrationMap.get(generatorName); - LOGGER.warn(String.format(Locale.ROOT, "The name '%s' is a deprecated. Please update to the new name of '%s'.", generatorName, newValue)); + LOGGER.warn(String.format(Locale.ROOT, + "The name '%s' is a deprecated. Please update to the new name of '%s'.", + generatorName, newValue)); this.generatorName = newValue; } else { this.generatorName = generatorName; @@ -255,17 +286,18 @@ public CodegenConfigurator setSkipOverwrite(boolean skipOverwrite) { /** - * Gets the "language". This has drifted away from language-only to include framework and hyphenated generator types as well as language. + * Gets the "language". This has drifted away from language-only to include framework and + * hyphenated generator types as well as language. *

- * NOTE: This will eventually become language only again. It is deprecated in its current state. + * NOTE: This will eventually become language only again. It is deprecated in its current + * state. *

* - * @deprecated Please use {@link #getGeneratorName()}, as generators are no longer identified only by language. We may reuse language in the future. - * * @return A string which defines the generator. + * @deprecated Please use {@link #getGeneratorName()}, as generators are no longer identified + * only by language. We may reuse language in the future. */ - @Deprecated - public String getLang() { + @Deprecated public String getLang() { return getGeneratorName(); } @@ -282,7 +314,8 @@ public CodegenConfigurator setTemplateDir(String templateDir) { // check to see if the folder exists if (!(f.exists() && f.isDirectory())) { - throw new IllegalArgumentException("Template directory " + templateDir + " does not exist."); + throw new IllegalArgumentException( + "Template directory " + templateDir + " does not exist."); } this.templateDir = f.getAbsolutePath(); @@ -417,7 +450,8 @@ public Set getLanguageSpecificPrimitives() { return languageSpecificPrimitives; } - public CodegenConfigurator setLanguageSpecificPrimitives(Set languageSpecificPrimitives) { + public CodegenConfigurator setLanguageSpecificPrimitives( + Set languageSpecificPrimitives) { this.languageSpecificPrimitives = languageSpecificPrimitives; return this; } @@ -468,11 +502,11 @@ public String getHttpUserAgent() { } public CodegenConfigurator setHttpUserAgent(String httpUserAgent) { - this.httpUserAgent= httpUserAgent; + this.httpUserAgent = httpUserAgent; return this; } - public Map getReservedWordsMappings() { + public Map getReservedWordsMappings() { return reservedWordMappings; } @@ -524,7 +558,8 @@ public ClientOptInput toClientOptInput() { checkAndSetAdditionalProperty(groupId, CodegenConstants.GROUP_ID); checkAndSetAdditionalProperty(artifactId, CodegenConstants.ARTIFACT_ID); checkAndSetAdditionalProperty(artifactVersion, CodegenConstants.ARTIFACT_VERSION); - checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR); + checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), + CodegenConstants.TEMPLATE_DIR); checkAndSetAdditionalProperty(modelNamePrefix, CodegenConstants.MODEL_NAME_PREFIX); checkAndSetAdditionalProperty(modelNameSuffix, CodegenConstants.MODEL_NAME_SUFFIX); checkAndSetAdditionalProperty(gitUserId, CodegenConstants.GIT_USER_ID); @@ -540,13 +575,13 @@ public ClientOptInput toClientOptInput() { config.additionalProperties().putAll(additionalProperties); - ClientOptInput input = new ClientOptInput() - .config(config); + ClientOptInput input = new ClientOptInput().config(config); final List authorizationValues = AuthParser.parse(auth); ParseOptions options = new ParseOptions(); options.setResolve(true); - SwaggerParseResult result = new OpenAPIParser().readLocation(inputSpec, authorizationValues, options); + SwaggerParseResult result = + new OpenAPIParser().readLocation(inputSpec, authorizationValues, options); Set validationMessages = new HashSet<>(result.getMessages()); OpenAPI specification = result.getOpenAPI(); @@ -556,12 +591,15 @@ public ClientOptInput toClientOptInput() { Set warnings = new HashSet<>(); if (specification != null) { List unusedModels = ModelUtils.getUnusedSchemas(specification); - if (unusedModels != null) unusedModels.forEach(name -> warnings.add("Unused model: " + name)); + if (unusedModels != null) { + unusedModels.forEach(name -> warnings.add("Unused model: " + name)); + } } if (this.isValidateSpec()) { StringBuilder sb = new StringBuilder(); - sb.append("There were issues with the specification. The option can be disabled via validateSpec (Maven/Gradle) or --skip-validate-spec (CLI)."); + sb.append( + "There were issues with the specification. The option can be disabled via validateSpec (Maven/Gradle) or --skip-validate-spec (CLI)."); sb.append(System.lineSeparator()); SpecValidationException ex = new SpecValidationException(sb.toString()); ex.setErrors(validationMessages); @@ -569,38 +607,34 @@ public ClientOptInput toClientOptInput() { throw ex; } else { StringBuilder sb = new StringBuilder(); - sb.append("There were issues with the specification, but validation has been explicitly disabled."); + sb.append( + "There were issues with the specification, but validation has been explicitly disabled."); sb.append(System.lineSeparator()); sb.append("Errors: ").append(System.lineSeparator()); - validationMessages.forEach(msg -> - sb.append("\t-").append(msg).append(System.lineSeparator()) - ); + validationMessages.forEach( + msg -> sb.append("\t-").append(msg).append(System.lineSeparator())); if (!warnings.isEmpty()) { sb.append("Warnings: ").append(System.lineSeparator()); - warnings.forEach(msg -> - sb.append("\t-").append(msg).append(System.lineSeparator()) - ); + warnings.forEach( + msg -> sb.append("\t-").append(msg).append(System.lineSeparator())); } LOGGER.warn(sb.toString()); } } - input.opts(new ClientOpts()) - .openAPI(specification); + input.opts(new ClientOpts()).openAPI(specification); return input; } - @JsonAnySetter - public CodegenConfigurator addDynamicProperty(String name, Object value) { + @JsonAnySetter public CodegenConfigurator addDynamicProperty(String name, Object value) { dynamicProperties.put(name, value); return this; } - @JsonAnyGetter - public Map getDynamicProperties() { + @JsonAnyGetter public Map getDynamicProperties() { return dynamicProperties; } @@ -609,8 +643,7 @@ private void handleDynamicProperties(CodegenConfig codegenConfig) { String opt = langCliOption.getOpt(); if (dynamicProperties.containsKey(opt)) { codegenConfig.additionalProperties().put(opt, dynamicProperties.get(opt)); - } - else if(systemProperties.containsKey(opt)) { + } else if (systemProperties.containsKey(opt)) { codegenConfig.additionalProperties().put(opt, systemProperties.get(opt)); } } @@ -620,11 +653,11 @@ private void setVerboseFlags() { if (!verbose) { return; } - LOGGER.info("\nVERBOSE MODE: ON. Additional debug options are injected" + - "\n - [debugOpenAPI] prints the OpenAPI specification as interpreted by the codegen" + - "\n - [debugModels] prints models passed to the template engine" + - "\n - [debugOperations] prints operations passed to the template engine" + - "\n - [debugSupportingFiles] prints additional data passed to the template engine"); + LOGGER.info("\nVERBOSE MODE: ON. Additional debug options are injected" + + "\n - [debugOpenAPI] prints the OpenAPI specification as interpreted by the codegen" + + "\n - [debugModels] prints models passed to the template engine" + + "\n - [debugOperations] prints operations passed to the template engine" + + "\n - [debugSupportingFiles] prints additional data passed to the template engine"); GeneratorProperties.setProperty("debugOpenAPI", ""); GeneratorProperties.setProperty("debugModels", ""); @@ -651,7 +684,8 @@ private void checkAndSetAdditionalProperty(String property, String propertyKey) checkAndSetAdditionalProperty(property, property, propertyKey); } - private void checkAndSetAdditionalProperty(String property, String valueToSet, String propertyKey) { + private void checkAndSetAdditionalProperty(String property, String valueToSet, + String propertyKey) { if (isNotEmpty(property)) { additionalProperties.put(propertyKey, valueToSet); } @@ -660,13 +694,20 @@ private void checkAndSetAdditionalProperty(String property, String valueToSet, S public static CodegenConfigurator fromFile(String configFile) { if (isNotEmpty(configFile)) { + ObjectMapper mapper; + + if (FilenameUtils.isExtension(configFile, new String[] {"yml", "yaml"})) { + mapper = Yaml.mapper(); + } else { + mapper = Json.mapper(); + } + try { - return Json.mapper().readValue(new File(configFile), CodegenConfigurator.class); - } catch (IOException e) { - LOGGER.error("Unable to deserialize config file: " + configFile, e); + return mapper.readValue(new File(configFile), CodegenConfigurator.class); + } catch (IOException ex) { + LOGGER.error("Unable to deserialize config file: " + configFile, ex); } } return null; } - } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java index fe4bce79ae39..47080b75cfac 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java @@ -19,10 +19,7 @@ import com.samskivert.mustache.Mustache; import io.swagger.v3.oas.models.OpenAPI; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; import org.openapitools.codegen.utils.URLPathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,6 +44,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { public static final String PROJECT_SDK = "projectSdk"; public static final String SDK_WEB = "Microsoft.NET.Sdk.Web"; public static final String SDK_LIB = "Microsoft.NET.Sdk"; + public static final String COMPATIBILITY_VERSION = "compatibilityVersion"; private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; @@ -56,13 +54,13 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private boolean useSwashbuckle = true; protected int serverPort = 8080; protected String serverHost = "0.0.0.0"; - protected String aspnetCoreVersion= "2.1"; // default to 2.1 - // TODO Make next two enums toensure fixed list. - private String classModifier = ""; - private String operationModifier = "virtual"; + protected CliOption aspnetCoreVersion= new CliOption(ASPNET_CORE_VERSION,"ASP.NET Core version: 2.2 (default), 2.1, 2.0 (deprecated)");; // default to 2.1 + private CliOption classModifier = new CliOption(CLASS_MODIFIER,"Class Modifier can be empty, abstract"); + private CliOption operationModifier = new CliOption(OPERATION_MODIFIER, "Operation Modifier can be virtual, abstract or partial"); private boolean generateBody = true; - private String buildTarget = "program"; + private CliOption buildTarget = new CliOption("buildTarget", "Target to build an application or library"); private String projectSdk = SDK_WEB; + private String compatibilityVersion = "Version_2_1"; public AspNetCoreServerCodegen() { super(); @@ -119,9 +117,14 @@ public AspNetCoreServerCodegen() { CodegenConstants.SOURCE_FOLDER_DESC, sourceFolder); - addOption(ASPNET_CORE_VERSION, - "ASP.NET Core version: 2.1 (default), 2.0 (deprecated)", - aspnetCoreVersion); + addOption(COMPATIBILITY_VERSION, "ASP.Net Core CompatibilityVersion", compatibilityVersion); + + aspnetCoreVersion.addEnum("2.0", "ASP.NET COre V2.0"); + aspnetCoreVersion.addEnum("2.1", "ASP.NET COre V2.1"); + aspnetCoreVersion.addEnum("2.2", "ASP.NET COre V2.2"); + aspnetCoreVersion.setDefault("2.2"); + aspnetCoreVersion.setOptValue(aspnetCoreVersion.getDefault()); + addOption(aspnetCoreVersion.getOpt(),aspnetCoreVersion.getDescription(),aspnetCoreVersion.getOptValue()); // CLI Switches addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, @@ -144,22 +147,28 @@ public AspNetCoreServerCodegen() { "Uses the Swashbuckle.AspNetCore NuGet package for documentation.", useSwashbuckle); - addOption(CLASS_MODIFIER, - "Class modifiers such as abstract or partial", - classModifier); + classModifier.addEnum("", "Keep class default with no modifier"); + classModifier.addEnum("abstract", "Make class abstract"); + classModifier.setDefault(""); + classModifier.setOptValue(classModifier.getDefault()); + addOption(classModifier.getOpt(),classModifier.getDescription(),classModifier.getOptValue()); + + operationModifier.addEnum("virtual", "Keep method virtual "); + operationModifier.addEnum("abstract", "Make method abstract"); + operationModifier.setDefault("virtual"); + operationModifier.setOptValue(operationModifier.getDefault()); + addOption(operationModifier.getOpt(),operationModifier.getDescription(),operationModifier.getOptValue()); - addOption(OPERATION_MODIFIER, - "Operation modifiers such as virtual or abstract.", - operationModifier); + buildTarget.addEnum("program", "Generate code for standalone server"); + buildTarget.addEnum("library", "Generate code for a server abstract class lbrary"); + buildTarget.setDefault("program"); + buildTarget.setOptValue(buildTarget.getDefault()); + addOption(buildTarget.getOpt(),buildTarget.getDescription(),buildTarget.getOptValue()); addSwitch(GENERATE_BODY, "Generates method body.", generateBody); - addOption(BUILD_TARGET, - "Target the build for a program or library.", - buildTarget); - } @Override @@ -201,53 +210,15 @@ public void processOpts() { additionalProperties.put(USE_SWASHBUCKLE, useSwashbuckle); } - // determine the ASP.NET core version setting - if (additionalProperties.containsKey(ASPNET_CORE_VERSION)) { - setAspnetCoreVersion((String) additionalProperties.get(ASPNET_CORE_VERSION)); - } - - // CHeck for class modifier if not present set the default value. - if (additionalProperties.containsKey(CLASS_MODIFIER)) { - classModifier = additionalProperties.get(CLASS_MODIFIER).toString(); - } else { - additionalProperties.put(CLASS_MODIFIER, classModifier); - } - // TODO Validate modifier values - // If class modifierier is abstract then the methods need to be abstrat too. - if ("abstract".equals(classModifier)) { - operationModifier = classModifier; - additionalProperties.put(OPERATION_MODIFIER, operationModifier); - } + // CHeck for the modifiers etc. + // The order of the checks is important. + isLibrary = setBuildTarget(); + setClassModifier(); + setOperationModifier(); - if (additionalProperties.containsKey(OPERATION_MODIFIER)) { - operationModifier = additionalProperties.get(OPERATION_MODIFIER).toString(); - } else { - additionalProperties.put(OPERATION_MODIFIER, operationModifier); - } - - // TODO Validate modifier values - // If operation modifier is abstract then dont generate any body - if ("abstract".equals(operationModifier)) { - generateBody = false; - additionalProperties.put(GENERATE_BODY, generateBody); - } - if (additionalProperties.containsKey(GENERATE_BODY)) { - generateBody = convertPropertyToBooleanAndWriteBack(GENERATE_BODY); - } else { - additionalProperties.put(GENERATE_BODY, generateBody); - } // CHeck for class modifier if not present set the default value. - if (additionalProperties.containsKey(BUILD_TARGET)) { - buildTarget = additionalProperties.get(BUILD_TARGET).toString(); - } else { - additionalProperties.put(BUILD_TARGET, buildTarget); - } - if ("library".equals(buildTarget)) { - isLibrary = true; - projectSdk = SDK_LIB; - } additionalProperties.put(PROJECT_SDK, projectSdk); additionalProperties.put("dockerTag", packageName.toLowerCase(Locale.ROOT)); @@ -257,17 +228,8 @@ public void processOpts() { String packageFolder = sourceFolder + File.separator + packageName; - if ("2.0".equals(aspnetCoreVersion)) { - embeddedTemplateDir = templateDir = "aspnetcore/2.0"; - supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config")); - LOGGER.info("ASP.NET core version: 2.0"); - } else if ("2.1".equals(aspnetCoreVersion)) { - // default, do nothing - LOGGER.info("ASP.NET core version: 2.1"); - } else { - throw new IllegalArgumentException("aspnetCoreVersion must be '2.1', '2.0' but found " + aspnetCoreVersion); - } - + // determine the ASP.NET core version setting + setAspnetCoreVersion(packageFolder); supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); @@ -294,26 +256,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "openapi-original.mustache", packageFolder + File.separator + "wwwroot", "openapi-original.json")); } - supportingFiles.add(new SupportingFile("validateModel.mustache", packageFolder + File.separator + "Attributes", "ValidateModelStateAttribute.cs")); - supportingFiles.add(new SupportingFile("Project.csproj.mustache", packageFolder, packageName + ".csproj")); - if (!isLibrary) { - supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile")); - supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, "appsettings.json")); - - supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs")); - supportingFiles.add(new SupportingFile("Program.mustache", packageFolder, "Program.cs")); - supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", - packageFolder + File.separator + "Properties", "launchSettings.json")); - } else { - supportingFiles.add(new SupportingFile("Project.nuspec.mustache", packageFolder, packageName + ".nuspec")); - // wwwroot files. - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", packageFolder + File.separator + "wwwroot", "README.md")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", packageFolder + File.separator + "wwwroot", "index.html")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", packageFolder + File.separator + "wwwroot", "web.config")); - - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "openapi-original.mustache", - packageFolder + File.separator + "wwwroot", "openapi-original.json")); - } if (useSwashbuckle) { @@ -328,10 +270,6 @@ public void setPackageGuid(String packageGuid) { this.packageGuid = packageGuid; } - public void setAspnetCoreVersion(String aspnetCoreVersion) { - this.aspnetCoreVersion= aspnetCoreVersion; - } - @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Controllers"; @@ -375,4 +313,72 @@ public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { public String toRegularExpression(String pattern) { return escapeText(pattern); } + + private void setCliOption(CliOption cliOption) throws IllegalArgumentException { + if (additionalProperties.containsKey(cliOption.getOpt())) { + cliOption.setOptValue(additionalProperties.get(cliOption.getOpt()).toString()); + if (classModifier.getOptValue() == null) { + cliOption.setOptValue(cliOption.getDefault()); + throw new IllegalArgumentException(cliOption.getOpt() + ": Invalid value '" + additionalProperties.get(cliOption.getOpt()).toString() + "'" + + ". " + cliOption.getDescription()); + } + } else { + additionalProperties.put(cliOption.getOpt(), cliOption.getOptValue()); + } + } + + private void setClassModifier() { + // CHeck for class modifier if not present set the default value. + setCliOption(classModifier); + + // If class modifier is abstract then the methods need to be abstract too. + if ("abstract".equals(classModifier.getOptValue())) { + operationModifier.setOptValue(classModifier.getOptValue()); + additionalProperties.put(OPERATION_MODIFIER, operationModifier.getOptValue()); + LOGGER.warn("classModifier is " + classModifier.getOptValue() + " so forcing operatonModifier to "+ operationModifier.getOptValue()); + } else { + setCliOption(operationModifier); + } + } + + private void setOperationModifier() { + setCliOption(operationModifier); + + // If operation modifier is abstract then dont generate any body + if ("abstract".equals(operationModifier.getOptValue())) { + generateBody = false; + additionalProperties.put(GENERATE_BODY, generateBody); + LOGGER.warn("operationModifier is " + operationModifier.getOptValue() + " so forcing generateBody to "+ generateBody); + } else if (additionalProperties.containsKey(GENERATE_BODY)) { + generateBody = convertPropertyToBooleanAndWriteBack(GENERATE_BODY); + } else { + additionalProperties.put(GENERATE_BODY, generateBody); + } + } + + private boolean setBuildTarget() { + boolean isLibrary = false; + setCliOption(buildTarget); + if ("library".equals(buildTarget.getOptValue())) { + isLibrary = true; + projectSdk = SDK_LIB; + additionalProperties.put(CLASS_MODIFIER, "abstract"); + } + return isLibrary; + } + + private void setAspnetCoreVersion(String packageFolder) { + setCliOption(aspnetCoreVersion); + if ("2.0".equals(aspnetCoreVersion.getOptValue())) { + embeddedTemplateDir = templateDir = "aspnetcore/2.0"; + supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config")); + LOGGER.info("ASP.NET core version: 2.0"); + compatibilityVersion = null; + } else { + // default, do nothing + LOGGER.info("ASP.NET core version: " + aspnetCoreVersion.getOptValue()); + compatibilityVersion = "Version_" + aspnetCoreVersion.getOptValue().replace(".","_"); + } + additionalProperties.put(COMPATIBILITY_VERSION, compatibilityVersion); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java index 605c4e16e266..bf2852f71549 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java @@ -205,6 +205,9 @@ public void processOpts() { supportingFiles.add(new SupportingFile("cJSON.c.mustache", "external", "cJSON.c")); supportingFiles.add(new SupportingFile("cJSON.h.mustache", "external", "cJSON.h")); + // Object files in model folder + supportingFiles.add(new SupportingFile("object-body.mustache", "model", "object.c")); + supportingFiles.add(new SupportingFile("object-header.mustache", "model", "object.h")); } @Override @@ -333,6 +336,9 @@ public String toVarName(String name) { @Override public String toParamName(String name) { // should be the same as variable name + if (name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } name = name.replaceAll("-","_"); return name; } @@ -412,11 +418,15 @@ public String toApiName(String name) { @Override public String toEnumValue(String value, String datatype) { + value = value.replaceAll("-","_"); + if (isReservedWord(value)) { + value = escapeReservedWord(value); + } if ("Integer".equals(datatype) || "Float".equals(datatype)) { return value; } else { if (value.matches("\\d.*")) { // starts with number - return "N" + escapeText(value); + return escapeReservedWord(escapeText(value)); } else { return escapeText(value); } @@ -444,7 +454,7 @@ public String toEnumVarName(String name, String datatype) { enumName = enumName.replaceFirst("_$", ""); if (enumName.matches("\\d.*")) { // starts with number - return "N" + enumName; + return escapeReservedWord(enumName); } else { return enumName; } @@ -457,7 +467,7 @@ public String toEnumName(CodegenProperty property) { enumName = enumName.replaceFirst("_$", ""); if (enumName.matches("\\d.*")) { // starts with number - return "N" + enumName; + return escapeReservedWord(enumName); } else { return enumName; } @@ -502,7 +512,10 @@ public String toApiImport(String name) { @Override public String toModelImport(String name) { - return "#include \"" +"../model/" + name + ".h\""; + if (importMapping.containsKey(name)) { + return "#include \"" +"../model/" + importMapping.get(name) + ".h\""; + } else + return "#include \"" +"../model/" + name + ".h\""; } @Override @@ -595,6 +608,18 @@ public String escapeUnsafeCharacters(String input) { return input.replace("=end", "=_end").replace("=begin", "=_begin"); } + @Override + public CodegenProperty fromProperty(String name, Schema p) { + CodegenProperty cm = super.fromProperty(name,p); + Schema ref = ModelUtils.getReferencedSchema(openAPI, p); + if (ref != null) { + if (ref.getEnum() != null) { + cm.isEnum = true; + } + } + return cm; + } + @Override public void postProcessFile(File file, String fileType) { diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/README.md.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/README.md.mustache index c0fdb1883fbb..b656b40bb95d 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/README.md.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/README.md.mustache @@ -40,6 +40,7 @@ sudo make install ``` ## Compile the sample: +This will compile the generated code and create a library in build folder which has to be linked to the codes where API will be used. ```bash mkdir build cd build @@ -51,15 +52,17 @@ make sudo make install ``` ## How to use compiled library -Considering the test/source code which uses the API is written in main.c(respective api include is written and all objects necessary are defined) +Considering the test/source code which uses the API is written in main.c(respective api include is written and all objects necessary are defined and created) -To compile main.c use following command +To compile main.c(considering the file is present in build folder) use following command -L - locaiton of the library(not required if cmake with normal installation is performed) -l library name ```bash gcc main.c -L. -lpetstore -o main ``` +once compile, you can run it with ``` ./main ``` +Note: You dont need to specify includes for models and include folder seperately as they are path linked. You just have to import the api.h file in your code, the include linking will work. ## Author diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/object-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/object-body.mustache new file mode 100644 index 000000000000..d106693842f6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/C-libcurl/object-body.mustache @@ -0,0 +1,31 @@ +#include +#include +#include +#include "object.h" + +object_t *object_create() { + object_t *object = malloc(sizeof(object_t)); + + return object; +} + +void object_free(object_t *object) { + free (object); +} + +cJSON *object_convertToJSON(object_t *object) { + cJSON *item = cJSON_CreateObject(); + + return item; +fail: + cJSON_Delete(item); + return NULL; +} + +object_t *object_parseFromJSON(char *jsonString){ + object_t *object = NULL; + + return object; +end: + return NULL; +} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/object-header.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/object-header.mustache new file mode 100644 index 000000000000..6b1a77fc508a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/C-libcurl/object-header.mustache @@ -0,0 +1,26 @@ +/* + * object.h + */ + +#ifndef _object_H_ +#define _object_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" + + +typedef struct object_t { + void *temporary; +} object_t; + +object_t *object_create(); + +void object_free(object_t *object); + +object_t *object_parseFromJSON(char *jsonString); + +cJSON *object_convertToJSON(object_t *object); + +#endif /* _object_H_ */ diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 22efcd9e9367..3c4559359c37 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -190,7 +190,7 @@ public class ApiClient { * @param newHttpClient An instance of OkHttpClient * @return Api Client */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { + public ApiClient setHttpClient(OkHttpClient newHttpClient) { if(!httpClient.equals(newHttpClient)) { OkHttpClient.Builder builder = newHttpClient.newBuilder(); Iterator networkInterceptorIterator = httpClient.networkInterceptors().iterator(); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache index cf90c4ee1dbd..3705e654e09e 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -274,8 +274,7 @@ public class {{classname}} { {{/optionalParams}} /** * Build call for {{operationId}} - * @param _progressListener Progress listener - * @param _progressRequestListener Progress request listener + * @param _callback ApiCallback API callback * @return Call to execute * @throws ApiException If fail to serialize the request body object {{#isDeprecated}} diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Dockerfile.mustache index 391e85846b8d..aa3f404bdce6 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Dockerfile.mustache @@ -1,4 +1,4 @@ -FROM microsoft/dotnet:2.1-sdk AS build-env +FROM microsoft/dotnet:{{aspnetCoreVersion}}-sdk AS build-env WORKDIR /app ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 @@ -12,7 +12,7 @@ COPY . ./ RUN dotnet publish -c Release -o out # build runtime image -FROM microsoft/dotnet:2.1-aspnetcore-runtime +FROM microsoft/dotnet:{{aspnetCoreVersion}}-aspnetcore-runtime WORKDIR /app COPY --from=build-env /app/out . ENTRYPOINT ["dotnet", "{{packageName}}.dll"] diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Project.csproj.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Project.csproj.mustache index 0430f24a4a46..296a332ecd97 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Project.csproj.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Project.csproj.mustache @@ -2,7 +2,7 @@ {{packageName}} {{packageName}} - netcoreapp2.1 + netcoreapp{{aspnetCoreVersion}} true true {{packageName}} diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache index 7a488bfcf170..f7d0e084937a 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache @@ -43,7 +43,9 @@ namespace {{packageName}} // Add framework services. services .AddMvc() - .SetCompatibilityVersion (CompatibilityVersion.Version_2_1) + {{#compatibilityVersion}} + .SetCompatibilityVersion (CompatibilityVersion.{{compatibilityVersion}}) + {{/compatibilityVersion}} .AddJsonOptions(opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache index 57a4f545f4ba..381d16aabef2 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache @@ -28,7 +28,7 @@ namespace {{packageName}}.Controllers [ValidateModelState]{{#useSwashbuckle}} [SwaggerOperation("{{operationId}}")]{{#responses}}{{#dataType}} [SwaggerResponse(statusCode: {{code}}, type: typeof({{&dataType}}), description: "{{message}}")]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}} - public {{operationModifier}} IActionResult {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + public {{operationModifier}} IActionResult {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{^generateBody}};{{/generateBody}} {{#generateBody}} { {{#responses}} {{#dataType}} @@ -51,9 +51,6 @@ namespace {{packageName}}.Controllers throw new NotImplementedException();{{/returnType}} } {{/generateBody}} - {{^generateBody}} - ; - {{/generateBody}} {{/operation}} } {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index 1766ea72105e..83c7a21222c7 100644 --- a/modules/openapi-generator/src/main/resources/dart2/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache @@ -58,18 +58,18 @@ import 'package:{{pubName}}/api.dart'; {{#authMethods}} {{#isBasic}} // TODO Configure HTTP basic authorization: {{{name}}} -//{{pubName}}.api.Configuration.username = 'YOUR_USERNAME'; -//{{pubName}}.api.Configuration.password = 'YOUR_PASSWORD'; +//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' +//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} -//{{pubName}}.api.Configuration.apiKey{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//{{pubName}}.api.Configuration.apiKeyPrefix{'{{{keyParamName}}}'} = "Bearer"; +//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer'; {{/isApiKey}} {{#isOAuth}} // TODO Configure OAuth2 access token for authorization: {{{name}}} -//{{pubName}}.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN'; {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache index 2a6c411a788d..a6bb6324e14f 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -157,11 +157,9 @@ class ApiClient { }); } - void setAccessToken(String accessToken) { - _authentications.forEach((key, auth) { - if (auth is OAuth) { - auth.setAccessToken(accessToken); - } - }); + T getAuthentication(String name) { + var authentication = _authentications[name]; + + return authentication is T ? authentication : null; } } diff --git a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache index c7c10a817a15..773ee0d562e1 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -29,18 +29,18 @@ import 'package:{{pubName}}/api.dart'; {{#authMethods}} {{#isBasic}} // TODO Configure HTTP basic authorization: {{{name}}} -//{{pubName}}.api.Configuration.username = 'YOUR_USERNAME'; -//{{pubName}}.api.Configuration.password = 'YOUR_PASSWORD'; +//defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' +//defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} -//{{pubName}}.api.Configuration.apiKey{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('{{{name}}}').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//{{pubName}}.api.Configuration.apiKeyPrefix{'{{{keyParamName}}}'} = "Bearer"; +//defaultApiClient.getAuthentication('{{{name}}}').apiKeyPrefix = 'Bearer'; {{/isApiKey}} {{#isOAuth}} // TODO Configure OAuth2 access token for authorization: {{{name}}} -//{{pubName}}.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN'; {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache index 1e62a7902e4a..c5e53204dc01 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache @@ -4,18 +4,20 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKey; + String _apiKey; String apiKeyPrefix; + set apiKey(String key) => _apiKey = key; + ApiKeyAuth(this.location, this.paramName); @override void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $apiKey'; + value = '$apiKeyPrefix $_apiKey'; } else { - value = apiKey; + value = _apiKey; } if (location == 'query' && value != null) { diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache index 89b3926ed791..efbbcfb30353 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache @@ -2,13 +2,15 @@ part of {{pubName}}.api; class HttpBasicAuth implements Authentication { - String username; - String password; + String _username; + String _password; @override void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password); headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str)); } + set username(String username) => _username = username; + set password(String password) => _password = password; } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache index 07a25e5f6dc3..58695a8a3efc 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache @@ -1,18 +1,16 @@ part of {{pubName}}.api; class OAuth implements Authentication { - String accessToken; + String _accessToken; - OAuth({this.accessToken}); + OAuth({String accessToken}) : _accessToken = accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { - headerParams["Authorization"] = "Bearer " + accessToken; + if (_accessToken != null) { + headerParams["Authorization"] = "Bearer $_accessToken"; } } - void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } + set accessToken(String accessToken) => _accessToken = accessToken; } diff --git a/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache index 3c7b53f81496..d94614b34fc7 100644 --- a/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/APIHelper.mustache @@ -45,6 +45,12 @@ public struct APIHelper { }) } + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? Array { + return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + } + return source + } public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in diff --git a/modules/openapi-generator/src/main/resources/swift4/api.mustache b/modules/openapi-generator/src/main/resources/swift4/api.mustache index 3dbe29390e83..c6eeab2d97e6 100644 --- a/modules/openapi-generator/src/main/resources/swift4/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/api.mustache @@ -143,7 +143,7 @@ open class {{classname}} { */ open class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{{path}}}"{{#pathParams}} - let {{paramName}}PreEscape = "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})" + let {{paramName}}PreEscape = "\({{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}APIHelper.mapValueToPathItem({{paramName}}){{/isEnum}})" let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}} let URLString = {{projectName}}API.basePath + path diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/docs/PetApi.md b/samples/client/petstore/dart/flutter_petstore/swagger/docs/PetApi.md index 5780e7f38022..3ec1113828c6 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/docs/PetApi.md +++ b/samples/client/petstore/dart/flutter_petstore/swagger/docs/PetApi.md @@ -28,7 +28,7 @@ Add a new pet to the store ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -70,7 +70,7 @@ Deletes a pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | Pet id to delete @@ -116,7 +116,7 @@ Multiple status values can be provided with comma separated strings ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var status = []; // List | Status values that need to be considered for filter @@ -161,7 +161,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var tags = []; // List | Tags to filter by @@ -206,9 +206,9 @@ Returns a single pet ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to return @@ -251,7 +251,7 @@ Update an existing pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -293,7 +293,7 @@ Updates a pet in the store with form data ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet that needs to be updated @@ -339,7 +339,7 @@ uploads an image ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to update diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/docs/StoreApi.md b/samples/client/petstore/dart/flutter_petstore/swagger/docs/StoreApi.md index df76647f11ae..f3a5e0aba874 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/docs/StoreApi.md +++ b/samples/client/petstore/dart/flutter_petstore/swagger/docs/StoreApi.md @@ -68,9 +68,9 @@ Returns a map of status codes to quantities ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new StoreApi(); diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/pet_api.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/pet_api.dart index 2ded9e38bf9d..abe86a5698a1 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/pet_api.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/pet_api.dart @@ -50,7 +50,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -100,7 +100,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -150,9 +150,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -201,9 +201,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -251,9 +251,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Pet') as Pet; + return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; } else { return null; } @@ -301,7 +301,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -362,7 +362,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -422,9 +422,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'ApiResponse') as ApiResponse; + return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; } else { return null; } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/store_api.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/store_api.dart index 0d05ff39bc96..75d6ef034ce3 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/store_api.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/store_api.dart @@ -50,7 +50,7 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -96,9 +96,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return new Map.from(apiClient.deserialize(response.body, 'Map')); + return new Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); ; } else { return null; @@ -147,9 +147,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } @@ -197,9 +197,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/user_api.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/user_api.dart index 91d35801e438..a4be03b43195 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/user_api.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api/user_api.dart @@ -50,7 +50,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -99,7 +99,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -148,7 +148,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -197,7 +197,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -246,9 +246,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'User') as User; + return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; } else { return null; } @@ -301,9 +301,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'String') as String; + return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; } else { return null; } @@ -348,7 +348,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -400,7 +400,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_client.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_client.dart index bfc05fe6ee85..9aed2f92dc3d 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_client.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_client.dart @@ -105,7 +105,10 @@ class ApiClient { _updateParamsForAuth(authNames, queryParams, headerParams); - var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + var ps = queryParams + .where((p) => p.value != null) + .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); + String queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; @@ -150,11 +153,9 @@ class ApiClient { }); } - void setAccessToken(String accessToken) { - _authentications.forEach((key, auth) { - if (auth is OAuth) { - auth.setAccessToken(accessToken); - } - }); + T getAuthentication(String name) { + var authentication = _authentications[name]; + + return authentication is T ? authentication : null; } } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_helper.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_helper.dart index a516a68d2649..c57b111ca87d 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_helper.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/api_helper.dart @@ -42,3 +42,15 @@ String parameterToString(dynamic value) { return value.toString(); } } + +/// Returns the decoded body by utf-8 if application/json with the given headers. +/// Else, returns the decoded body by default algorithm of dart:http. +/// Because avoid to text garbling when header only contains "application/json" without "; charset=utf-8". +String _decodeBodyBytes(Response response) { + var contentType = response.headers['content-type']; + if (contentType != null && contentType.contains("application/json")) { + return utf8.decode(response.bodyBytes); + } else { + return response.body; + } +} diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/api_key_auth.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/api_key_auth.dart index 8caf6ab5ebae..8384f0516ce2 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/api_key_auth.dart @@ -4,18 +4,20 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKey; + String _apiKey; String apiKeyPrefix; + set apiKey(String key) => _apiKey = key; + ApiKeyAuth(this.location, this.paramName); @override void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $apiKey'; + value = '$apiKeyPrefix $_apiKey'; } else { - value = apiKey; + value = _apiKey; } if (location == 'query' && value != null) { diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/http_basic_auth.dart index 6342d8866892..da931fa2634c 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/http_basic_auth.dart @@ -2,13 +2,15 @@ part of openapi.api; class HttpBasicAuth implements Authentication { - String username; - String password; + String _username; + String _password; @override void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password); headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str)); } + set username(String username) => _username = username; + set password(String password) => _password = password; } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/oauth.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/oauth.dart index aa08e5cdb4d1..230471e44fc6 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/oauth.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/auth/oauth.dart @@ -1,18 +1,16 @@ part of openapi.api; class OAuth implements Authentication { - String accessToken; + String _accessToken; - OAuth({this.accessToken}); + OAuth({String accessToken}) : _accessToken = accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { - headerParams["Authorization"] = "Bearer " + accessToken; + if (_accessToken != null) { + headerParams["Authorization"] = "Bearer $_accessToken"; } } - void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } + set accessToken(String accessToken) => _accessToken = accessToken; } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/api_response.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/api_response.dart index 37c961b73207..99ffe708aeb4 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/api_response.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/api_response.dart @@ -19,17 +19,17 @@ class ApiResponse { if (json['code'] == null) { code = null; } else { - code = json['code']; + code = json['code']; } if (json['type'] == null) { type = null; } else { - type = json['type']; + type = json['type']; } if (json['message'] == null) { message = null; } else { - message = json['message']; + message = json['message']; } } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/category.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/category.dart index 862b2c5b3858..19386463ba2c 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/category.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/category.dart @@ -17,12 +17,12 @@ class Category { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/order.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/order.dart index 42dc28f0fa3e..e9dfcfeaa93a 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/order.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/order.dart @@ -26,17 +26,17 @@ class Order { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['petId'] == null) { petId = null; } else { - petId = json['petId']; + petId = json['petId']; } if (json['quantity'] == null) { quantity = null; } else { - quantity = json['quantity']; + quantity = json['quantity']; } if (json['shipDate'] == null) { shipDate = null; @@ -46,12 +46,12 @@ class Order { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } if (json['complete'] == null) { complete = null; } else { - complete = json['complete']; + complete = json['complete']; } } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/pet.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/pet.dart index f7747b01cf1d..73407dc7dd0d 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/pet.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/pet.dart @@ -26,7 +26,7 @@ class Pet { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['category'] == null) { category = null; @@ -36,12 +36,12 @@ class Pet { if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } if (json['photoUrls'] == null) { photoUrls = null; } else { - photoUrls = ((json['photoUrls'] ?? []) as List).map((item) => item as String).toList(); + photoUrls = (json['photoUrls'] as List).cast(); } if (json['tags'] == null) { tags = null; @@ -51,7 +51,7 @@ class Pet { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/tag.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/tag.dart index 964fa48e0e23..7bd96004c234 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/tag.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/tag.dart @@ -17,12 +17,12 @@ class Tag { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/user.dart b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/user.dart index 067ce8f5c818..0178b539448f 100644 --- a/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/user.dart +++ b/samples/client/petstore/dart/flutter_petstore/swagger/lib/model/user.dart @@ -29,42 +29,42 @@ class User { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['username'] == null) { username = null; } else { - username = json['username']; + username = json['username']; } if (json['firstName'] == null) { firstName = null; } else { - firstName = json['firstName']; + firstName = json['firstName']; } if (json['lastName'] == null) { lastName = null; } else { - lastName = json['lastName']; + lastName = json['lastName']; } if (json['email'] == null) { email = null; } else { - email = json['email']; + email = json['email']; } if (json['password'] == null) { password = null; } else { - password = json['password']; + password = json['password']; } if (json['phone'] == null) { phone = null; } else { - phone = json['phone']; + phone = json['phone']; } if (json['userStatus'] == null) { userStatus = null; } else { - userStatus = json['userStatus']; + userStatus = json['userStatus']; } } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/docs/PetApi.md b/samples/client/petstore/dart2/flutter_petstore/openapi/docs/PetApi.md index 5780e7f38022..3ec1113828c6 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/docs/PetApi.md +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/docs/PetApi.md @@ -28,7 +28,7 @@ Add a new pet to the store ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -70,7 +70,7 @@ Deletes a pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | Pet id to delete @@ -116,7 +116,7 @@ Multiple status values can be provided with comma separated strings ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var status = []; // List | Status values that need to be considered for filter @@ -161,7 +161,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var tags = []; // List | Tags to filter by @@ -206,9 +206,9 @@ Returns a single pet ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to return @@ -251,7 +251,7 @@ Update an existing pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -293,7 +293,7 @@ Updates a pet in the store with form data ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet that needs to be updated @@ -339,7 +339,7 @@ uploads an image ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to update diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/docs/StoreApi.md b/samples/client/petstore/dart2/flutter_petstore/openapi/docs/StoreApi.md index df76647f11ae..f3a5e0aba874 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/docs/StoreApi.md +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/docs/StoreApi.md @@ -68,9 +68,9 @@ Returns a map of status codes to quantities ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new StoreApi(); diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/pet_api.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/pet_api.dart index 2ded9e38bf9d..abe86a5698a1 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/pet_api.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/pet_api.dart @@ -50,7 +50,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -100,7 +100,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -150,9 +150,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -201,9 +201,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -251,9 +251,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Pet') as Pet; + return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; } else { return null; } @@ -301,7 +301,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -362,7 +362,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -422,9 +422,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'ApiResponse') as ApiResponse; + return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; } else { return null; } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/store_api.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/store_api.dart index 0d05ff39bc96..75d6ef034ce3 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/store_api.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/store_api.dart @@ -50,7 +50,7 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -96,9 +96,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return new Map.from(apiClient.deserialize(response.body, 'Map')); + return new Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); ; } else { return null; @@ -147,9 +147,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } @@ -197,9 +197,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/user_api.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/user_api.dart index 91d35801e438..a4be03b43195 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/user_api.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api/user_api.dart @@ -50,7 +50,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -99,7 +99,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -148,7 +148,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -197,7 +197,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -246,9 +246,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'User') as User; + return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; } else { return null; } @@ -301,9 +301,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'String') as String; + return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; } else { return null; } @@ -348,7 +348,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -400,7 +400,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_client.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_client.dart index bfc05fe6ee85..9aed2f92dc3d 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_client.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_client.dart @@ -105,7 +105,10 @@ class ApiClient { _updateParamsForAuth(authNames, queryParams, headerParams); - var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + var ps = queryParams + .where((p) => p.value != null) + .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); + String queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; @@ -150,11 +153,9 @@ class ApiClient { }); } - void setAccessToken(String accessToken) { - _authentications.forEach((key, auth) { - if (auth is OAuth) { - auth.setAccessToken(accessToken); - } - }); + T getAuthentication(String name) { + var authentication = _authentications[name]; + + return authentication is T ? authentication : null; } } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_helper.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_helper.dart index a516a68d2649..c57b111ca87d 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_helper.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/api_helper.dart @@ -42,3 +42,15 @@ String parameterToString(dynamic value) { return value.toString(); } } + +/// Returns the decoded body by utf-8 if application/json with the given headers. +/// Else, returns the decoded body by default algorithm of dart:http. +/// Because avoid to text garbling when header only contains "application/json" without "; charset=utf-8". +String _decodeBodyBytes(Response response) { + var contentType = response.headers['content-type']; + if (contentType != null && contentType.contains("application/json")) { + return utf8.decode(response.bodyBytes); + } else { + return response.body; + } +} diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/api_key_auth.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/api_key_auth.dart index 8caf6ab5ebae..8384f0516ce2 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/api_key_auth.dart @@ -4,18 +4,20 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKey; + String _apiKey; String apiKeyPrefix; + set apiKey(String key) => _apiKey = key; + ApiKeyAuth(this.location, this.paramName); @override void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $apiKey'; + value = '$apiKeyPrefix $_apiKey'; } else { - value = apiKey; + value = _apiKey; } if (location == 'query' && value != null) { diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/http_basic_auth.dart index 6342d8866892..da931fa2634c 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/http_basic_auth.dart @@ -2,13 +2,15 @@ part of openapi.api; class HttpBasicAuth implements Authentication { - String username; - String password; + String _username; + String _password; @override void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password); headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str)); } + set username(String username) => _username = username; + set password(String password) => _password = password; } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/oauth.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/oauth.dart index aa08e5cdb4d1..230471e44fc6 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/oauth.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/auth/oauth.dart @@ -1,18 +1,16 @@ part of openapi.api; class OAuth implements Authentication { - String accessToken; + String _accessToken; - OAuth({this.accessToken}); + OAuth({String accessToken}) : _accessToken = accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { - headerParams["Authorization"] = "Bearer " + accessToken; + if (_accessToken != null) { + headerParams["Authorization"] = "Bearer $_accessToken"; } } - void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } + set accessToken(String accessToken) => _accessToken = accessToken; } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/api_response.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/api_response.dart index 37c961b73207..99ffe708aeb4 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/api_response.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/api_response.dart @@ -19,17 +19,17 @@ class ApiResponse { if (json['code'] == null) { code = null; } else { - code = json['code']; + code = json['code']; } if (json['type'] == null) { type = null; } else { - type = json['type']; + type = json['type']; } if (json['message'] == null) { message = null; } else { - message = json['message']; + message = json['message']; } } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/category.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/category.dart index 862b2c5b3858..19386463ba2c 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/category.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/category.dart @@ -17,12 +17,12 @@ class Category { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/order.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/order.dart index 42dc28f0fa3e..e9dfcfeaa93a 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/order.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/order.dart @@ -26,17 +26,17 @@ class Order { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['petId'] == null) { petId = null; } else { - petId = json['petId']; + petId = json['petId']; } if (json['quantity'] == null) { quantity = null; } else { - quantity = json['quantity']; + quantity = json['quantity']; } if (json['shipDate'] == null) { shipDate = null; @@ -46,12 +46,12 @@ class Order { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } if (json['complete'] == null) { complete = null; } else { - complete = json['complete']; + complete = json['complete']; } } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/pet.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/pet.dart index f7747b01cf1d..73407dc7dd0d 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/pet.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/pet.dart @@ -26,7 +26,7 @@ class Pet { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['category'] == null) { category = null; @@ -36,12 +36,12 @@ class Pet { if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } if (json['photoUrls'] == null) { photoUrls = null; } else { - photoUrls = ((json['photoUrls'] ?? []) as List).map((item) => item as String).toList(); + photoUrls = (json['photoUrls'] as List).cast(); } if (json['tags'] == null) { tags = null; @@ -51,7 +51,7 @@ class Pet { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/tag.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/tag.dart index 964fa48e0e23..7bd96004c234 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/tag.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/tag.dart @@ -17,12 +17,12 @@ class Tag { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/user.dart b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/user.dart index 067ce8f5c818..0178b539448f 100644 --- a/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/user.dart +++ b/samples/client/petstore/dart2/flutter_petstore/openapi/lib/model/user.dart @@ -29,42 +29,42 @@ class User { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['username'] == null) { username = null; } else { - username = json['username']; + username = json['username']; } if (json['firstName'] == null) { firstName = null; } else { - firstName = json['firstName']; + firstName = json['firstName']; } if (json['lastName'] == null) { lastName = null; } else { - lastName = json['lastName']; + lastName = json['lastName']; } if (json['email'] == null) { email = null; } else { - email = json['email']; + email = json['email']; } if (json['password'] == null) { password = null; } else { - password = json['password']; + password = json['password']; } if (json['phone'] == null) { phone = null; } else { - phone = json['phone']; + phone = json['phone']; } if (json['userStatus'] == null) { userStatus = null; } else { - userStatus = json['userStatus']; + userStatus = json['userStatus']; } } diff --git a/samples/client/petstore/dart2/openapi-browser-client/docs/PetApi.md b/samples/client/petstore/dart2/openapi-browser-client/docs/PetApi.md index 5780e7f38022..3ec1113828c6 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/docs/PetApi.md +++ b/samples/client/petstore/dart2/openapi-browser-client/docs/PetApi.md @@ -28,7 +28,7 @@ Add a new pet to the store ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -70,7 +70,7 @@ Deletes a pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | Pet id to delete @@ -116,7 +116,7 @@ Multiple status values can be provided with comma separated strings ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var status = []; // List | Status values that need to be considered for filter @@ -161,7 +161,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var tags = []; // List | Tags to filter by @@ -206,9 +206,9 @@ Returns a single pet ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to return @@ -251,7 +251,7 @@ Update an existing pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -293,7 +293,7 @@ Updates a pet in the store with form data ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet that needs to be updated @@ -339,7 +339,7 @@ uploads an image ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to update diff --git a/samples/client/petstore/dart2/openapi-browser-client/docs/StoreApi.md b/samples/client/petstore/dart2/openapi-browser-client/docs/StoreApi.md index df76647f11ae..f3a5e0aba874 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/docs/StoreApi.md +++ b/samples/client/petstore/dart2/openapi-browser-client/docs/StoreApi.md @@ -68,9 +68,9 @@ Returns a map of status codes to quantities ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new StoreApi(); diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/api/pet_api.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/api/pet_api.dart index 2ded9e38bf9d..abe86a5698a1 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/api/pet_api.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/api/pet_api.dart @@ -50,7 +50,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -100,7 +100,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -150,9 +150,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -201,9 +201,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -251,9 +251,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Pet') as Pet; + return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; } else { return null; } @@ -301,7 +301,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -362,7 +362,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -422,9 +422,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'ApiResponse') as ApiResponse; + return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; } else { return null; } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/api/store_api.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/api/store_api.dart index 0d05ff39bc96..75d6ef034ce3 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/api/store_api.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/api/store_api.dart @@ -50,7 +50,7 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -96,9 +96,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return new Map.from(apiClient.deserialize(response.body, 'Map')); + return new Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); ; } else { return null; @@ -147,9 +147,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } @@ -197,9 +197,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/api/user_api.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/api/user_api.dart index 91d35801e438..a4be03b43195 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/api/user_api.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/api/user_api.dart @@ -50,7 +50,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -99,7 +99,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -148,7 +148,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -197,7 +197,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -246,9 +246,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'User') as User; + return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; } else { return null; } @@ -301,9 +301,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'String') as String; + return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; } else { return null; } @@ -348,7 +348,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -400,7 +400,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/api_client.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/api_client.dart index dcdbd3769d87..d5b111bf7fc7 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/api_client.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/api_client.dart @@ -105,7 +105,10 @@ class ApiClient { _updateParamsForAuth(authNames, queryParams, headerParams); - var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + var ps = queryParams + .where((p) => p.value != null) + .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); + String queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; @@ -150,11 +153,9 @@ class ApiClient { }); } - void setAccessToken(String accessToken) { - _authentications.forEach((key, auth) { - if (auth is OAuth) { - auth.setAccessToken(accessToken); - } - }); + T getAuthentication(String name) { + var authentication = _authentications[name]; + + return authentication is T ? authentication : null; } } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/api_helper.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/api_helper.dart index a516a68d2649..c57b111ca87d 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/api_helper.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/api_helper.dart @@ -42,3 +42,15 @@ String parameterToString(dynamic value) { return value.toString(); } } + +/// Returns the decoded body by utf-8 if application/json with the given headers. +/// Else, returns the decoded body by default algorithm of dart:http. +/// Because avoid to text garbling when header only contains "application/json" without "; charset=utf-8". +String _decodeBodyBytes(Response response) { + var contentType = response.headers['content-type']; + if (contentType != null && contentType.contains("application/json")) { + return utf8.decode(response.bodyBytes); + } else { + return response.body; + } +} diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/auth/api_key_auth.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/auth/api_key_auth.dart index 8caf6ab5ebae..8384f0516ce2 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/auth/api_key_auth.dart @@ -4,18 +4,20 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKey; + String _apiKey; String apiKeyPrefix; + set apiKey(String key) => _apiKey = key; + ApiKeyAuth(this.location, this.paramName); @override void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $apiKey'; + value = '$apiKeyPrefix $_apiKey'; } else { - value = apiKey; + value = _apiKey; } if (location == 'query' && value != null) { diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/auth/http_basic_auth.dart index 6342d8866892..da931fa2634c 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/auth/http_basic_auth.dart @@ -2,13 +2,15 @@ part of openapi.api; class HttpBasicAuth implements Authentication { - String username; - String password; + String _username; + String _password; @override void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password); headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str)); } + set username(String username) => _username = username; + set password(String password) => _password = password; } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/auth/oauth.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/auth/oauth.dart index aa08e5cdb4d1..230471e44fc6 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/auth/oauth.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/auth/oauth.dart @@ -1,18 +1,16 @@ part of openapi.api; class OAuth implements Authentication { - String accessToken; + String _accessToken; - OAuth({this.accessToken}); + OAuth({String accessToken}) : _accessToken = accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { - headerParams["Authorization"] = "Bearer " + accessToken; + if (_accessToken != null) { + headerParams["Authorization"] = "Bearer $_accessToken"; } } - void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } + set accessToken(String accessToken) => _accessToken = accessToken; } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/model/api_response.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/model/api_response.dart index 37c961b73207..99ffe708aeb4 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/model/api_response.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/model/api_response.dart @@ -19,17 +19,17 @@ class ApiResponse { if (json['code'] == null) { code = null; } else { - code = json['code']; + code = json['code']; } if (json['type'] == null) { type = null; } else { - type = json['type']; + type = json['type']; } if (json['message'] == null) { message = null; } else { - message = json['message']; + message = json['message']; } } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/model/category.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/model/category.dart index 862b2c5b3858..19386463ba2c 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/model/category.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/model/category.dart @@ -17,12 +17,12 @@ class Category { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/model/order.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/model/order.dart index 42dc28f0fa3e..e9dfcfeaa93a 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/model/order.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/model/order.dart @@ -26,17 +26,17 @@ class Order { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['petId'] == null) { petId = null; } else { - petId = json['petId']; + petId = json['petId']; } if (json['quantity'] == null) { quantity = null; } else { - quantity = json['quantity']; + quantity = json['quantity']; } if (json['shipDate'] == null) { shipDate = null; @@ -46,12 +46,12 @@ class Order { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } if (json['complete'] == null) { complete = null; } else { - complete = json['complete']; + complete = json['complete']; } } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/model/pet.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/model/pet.dart index f7747b01cf1d..73407dc7dd0d 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/model/pet.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/model/pet.dart @@ -26,7 +26,7 @@ class Pet { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['category'] == null) { category = null; @@ -36,12 +36,12 @@ class Pet { if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } if (json['photoUrls'] == null) { photoUrls = null; } else { - photoUrls = ((json['photoUrls'] ?? []) as List).map((item) => item as String).toList(); + photoUrls = (json['photoUrls'] as List).cast(); } if (json['tags'] == null) { tags = null; @@ -51,7 +51,7 @@ class Pet { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/model/tag.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/model/tag.dart index 964fa48e0e23..7bd96004c234 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/model/tag.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/model/tag.dart @@ -17,12 +17,12 @@ class Tag { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart2/openapi-browser-client/lib/model/user.dart b/samples/client/petstore/dart2/openapi-browser-client/lib/model/user.dart index 067ce8f5c818..0178b539448f 100644 --- a/samples/client/petstore/dart2/openapi-browser-client/lib/model/user.dart +++ b/samples/client/petstore/dart2/openapi-browser-client/lib/model/user.dart @@ -29,42 +29,42 @@ class User { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['username'] == null) { username = null; } else { - username = json['username']; + username = json['username']; } if (json['firstName'] == null) { firstName = null; } else { - firstName = json['firstName']; + firstName = json['firstName']; } if (json['lastName'] == null) { lastName = null; } else { - lastName = json['lastName']; + lastName = json['lastName']; } if (json['email'] == null) { email = null; } else { - email = json['email']; + email = json['email']; } if (json['password'] == null) { password = null; } else { - password = json['password']; + password = json['password']; } if (json['phone'] == null) { phone = null; } else { - phone = json['phone']; + phone = json['phone']; } if (json['userStatus'] == null) { userStatus = null; } else { - userStatus = json['userStatus']; + userStatus = json['userStatus']; } } diff --git a/samples/client/petstore/dart2/openapi/docs/PetApi.md b/samples/client/petstore/dart2/openapi/docs/PetApi.md index 5780e7f38022..3ec1113828c6 100644 --- a/samples/client/petstore/dart2/openapi/docs/PetApi.md +++ b/samples/client/petstore/dart2/openapi/docs/PetApi.md @@ -28,7 +28,7 @@ Add a new pet to the store ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -70,7 +70,7 @@ Deletes a pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | Pet id to delete @@ -116,7 +116,7 @@ Multiple status values can be provided with comma separated strings ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var status = []; // List | Status values that need to be considered for filter @@ -161,7 +161,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var tags = []; // List | Tags to filter by @@ -206,9 +206,9 @@ Returns a single pet ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to return @@ -251,7 +251,7 @@ Update an existing pet ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -293,7 +293,7 @@ Updates a pet in the store with form data ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet that needs to be updated @@ -339,7 +339,7 @@ uploads an image ```dart import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth -//openapi.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +//defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; var api_instance = new PetApi(); var petId = 789; // int | ID of pet to update diff --git a/samples/client/petstore/dart2/openapi/docs/StoreApi.md b/samples/client/petstore/dart2/openapi/docs/StoreApi.md index df76647f11ae..f3a5e0aba874 100644 --- a/samples/client/petstore/dart2/openapi/docs/StoreApi.md +++ b/samples/client/petstore/dart2/openapi/docs/StoreApi.md @@ -68,9 +68,9 @@ Returns a map of status codes to quantities ```dart import 'package:openapi/api.dart'; // TODO Configure API key authorization: api_key -//openapi.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +//defaultApiClient.getAuthentication('api_key').apiKey = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//openapi.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; +//defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; var api_instance = new StoreApi(); diff --git a/samples/client/petstore/dart2/openapi/lib/api/pet_api.dart b/samples/client/petstore/dart2/openapi/lib/api/pet_api.dart index 2ded9e38bf9d..abe86a5698a1 100644 --- a/samples/client/petstore/dart2/openapi/lib/api/pet_api.dart +++ b/samples/client/petstore/dart2/openapi/lib/api/pet_api.dart @@ -50,7 +50,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -100,7 +100,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -150,9 +150,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -201,9 +201,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return (apiClient.deserialize(response.body, 'List') as List).map((item) => item as Pet).toList(); + return (apiClient.deserialize(_decodeBodyBytes(response), 'List') as List).map((item) => item as Pet).toList(); } else { return null; } @@ -251,9 +251,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Pet') as Pet; + return apiClient.deserialize(_decodeBodyBytes(response), 'Pet') as Pet; } else { return null; } @@ -301,7 +301,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -362,7 +362,7 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -422,9 +422,9 @@ class PetApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'ApiResponse') as ApiResponse; + return apiClient.deserialize(_decodeBodyBytes(response), 'ApiResponse') as ApiResponse; } else { return null; } diff --git a/samples/client/petstore/dart2/openapi/lib/api/store_api.dart b/samples/client/petstore/dart2/openapi/lib/api/store_api.dart index 0d05ff39bc96..75d6ef034ce3 100644 --- a/samples/client/petstore/dart2/openapi/lib/api/store_api.dart +++ b/samples/client/petstore/dart2/openapi/lib/api/store_api.dart @@ -50,7 +50,7 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -96,9 +96,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return new Map.from(apiClient.deserialize(response.body, 'Map')); + return new Map.from(apiClient.deserialize(_decodeBodyBytes(response), 'Map')); ; } else { return null; @@ -147,9 +147,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } @@ -197,9 +197,9 @@ class StoreApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') as Order; + return apiClient.deserialize(_decodeBodyBytes(response), 'Order') as Order; } else { return null; } diff --git a/samples/client/petstore/dart2/openapi/lib/api/user_api.dart b/samples/client/petstore/dart2/openapi/lib/api/user_api.dart index 91d35801e438..a4be03b43195 100644 --- a/samples/client/petstore/dart2/openapi/lib/api/user_api.dart +++ b/samples/client/petstore/dart2/openapi/lib/api/user_api.dart @@ -50,7 +50,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -99,7 +99,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -148,7 +148,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -197,7 +197,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -246,9 +246,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'User') as User; + return apiClient.deserialize(_decodeBodyBytes(response), 'User') as User; } else { return null; } @@ -301,9 +301,9 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'String') as String; + return apiClient.deserialize(_decodeBodyBytes(response), 'String') as String; } else { return null; } @@ -348,7 +348,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; @@ -400,7 +400,7 @@ class UserApi { authNames); if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); + throw new ApiException(response.statusCode, _decodeBodyBytes(response)); } else if(response.body != null) { } else { return; diff --git a/samples/client/petstore/dart2/openapi/lib/api_client.dart b/samples/client/petstore/dart2/openapi/lib/api_client.dart index bfc05fe6ee85..9aed2f92dc3d 100644 --- a/samples/client/petstore/dart2/openapi/lib/api_client.dart +++ b/samples/client/petstore/dart2/openapi/lib/api_client.dart @@ -105,7 +105,10 @@ class ApiClient { _updateParamsForAuth(authNames, queryParams, headerParams); - var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + var ps = queryParams + .where((p) => p.value != null) + .map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}'); + String queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; @@ -150,11 +153,9 @@ class ApiClient { }); } - void setAccessToken(String accessToken) { - _authentications.forEach((key, auth) { - if (auth is OAuth) { - auth.setAccessToken(accessToken); - } - }); + T getAuthentication(String name) { + var authentication = _authentications[name]; + + return authentication is T ? authentication : null; } } diff --git a/samples/client/petstore/dart2/openapi/lib/api_helper.dart b/samples/client/petstore/dart2/openapi/lib/api_helper.dart index a516a68d2649..c57b111ca87d 100644 --- a/samples/client/petstore/dart2/openapi/lib/api_helper.dart +++ b/samples/client/petstore/dart2/openapi/lib/api_helper.dart @@ -42,3 +42,15 @@ String parameterToString(dynamic value) { return value.toString(); } } + +/// Returns the decoded body by utf-8 if application/json with the given headers. +/// Else, returns the decoded body by default algorithm of dart:http. +/// Because avoid to text garbling when header only contains "application/json" without "; charset=utf-8". +String _decodeBodyBytes(Response response) { + var contentType = response.headers['content-type']; + if (contentType != null && contentType.contains("application/json")) { + return utf8.decode(response.bodyBytes); + } else { + return response.body; + } +} diff --git a/samples/client/petstore/dart2/openapi/lib/auth/api_key_auth.dart b/samples/client/petstore/dart2/openapi/lib/auth/api_key_auth.dart index 8caf6ab5ebae..8384f0516ce2 100644 --- a/samples/client/petstore/dart2/openapi/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart2/openapi/lib/auth/api_key_auth.dart @@ -4,18 +4,20 @@ class ApiKeyAuth implements Authentication { final String location; final String paramName; - String apiKey; + String _apiKey; String apiKeyPrefix; + set apiKey(String key) => _apiKey = key; + ApiKeyAuth(this.location, this.paramName); @override void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $apiKey'; + value = '$apiKeyPrefix $_apiKey'; } else { - value = apiKey; + value = _apiKey; } if (location == 'query' && value != null) { diff --git a/samples/client/petstore/dart2/openapi/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart2/openapi/lib/auth/http_basic_auth.dart index 6342d8866892..da931fa2634c 100644 --- a/samples/client/petstore/dart2/openapi/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart2/openapi/lib/auth/http_basic_auth.dart @@ -2,13 +2,15 @@ part of openapi.api; class HttpBasicAuth implements Authentication { - String username; - String password; + String _username; + String _password; @override void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + String str = (_username == null ? "" : _username) + ":" + (_password == null ? "" : _password); headerParams["Authorization"] = "Basic " + base64.encode(utf8.encode(str)); } + set username(String username) => _username = username; + set password(String password) => _password = password; } diff --git a/samples/client/petstore/dart2/openapi/lib/auth/oauth.dart b/samples/client/petstore/dart2/openapi/lib/auth/oauth.dart index aa08e5cdb4d1..230471e44fc6 100644 --- a/samples/client/petstore/dart2/openapi/lib/auth/oauth.dart +++ b/samples/client/petstore/dart2/openapi/lib/auth/oauth.dart @@ -1,18 +1,16 @@ part of openapi.api; class OAuth implements Authentication { - String accessToken; + String _accessToken; - OAuth({this.accessToken}); + OAuth({String accessToken}) : _accessToken = accessToken; @override void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { - headerParams["Authorization"] = "Bearer " + accessToken; + if (_accessToken != null) { + headerParams["Authorization"] = "Bearer $_accessToken"; } } - void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } + set accessToken(String accessToken) => _accessToken = accessToken; } diff --git a/samples/client/petstore/dart2/openapi/lib/model/api_response.dart b/samples/client/petstore/dart2/openapi/lib/model/api_response.dart index 37c961b73207..99ffe708aeb4 100644 --- a/samples/client/petstore/dart2/openapi/lib/model/api_response.dart +++ b/samples/client/petstore/dart2/openapi/lib/model/api_response.dart @@ -19,17 +19,17 @@ class ApiResponse { if (json['code'] == null) { code = null; } else { - code = json['code']; + code = json['code']; } if (json['type'] == null) { type = null; } else { - type = json['type']; + type = json['type']; } if (json['message'] == null) { message = null; } else { - message = json['message']; + message = json['message']; } } diff --git a/samples/client/petstore/dart2/openapi/lib/model/category.dart b/samples/client/petstore/dart2/openapi/lib/model/category.dart index 862b2c5b3858..19386463ba2c 100644 --- a/samples/client/petstore/dart2/openapi/lib/model/category.dart +++ b/samples/client/petstore/dart2/openapi/lib/model/category.dart @@ -17,12 +17,12 @@ class Category { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart2/openapi/lib/model/order.dart b/samples/client/petstore/dart2/openapi/lib/model/order.dart index 42dc28f0fa3e..e9dfcfeaa93a 100644 --- a/samples/client/petstore/dart2/openapi/lib/model/order.dart +++ b/samples/client/petstore/dart2/openapi/lib/model/order.dart @@ -26,17 +26,17 @@ class Order { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['petId'] == null) { petId = null; } else { - petId = json['petId']; + petId = json['petId']; } if (json['quantity'] == null) { quantity = null; } else { - quantity = json['quantity']; + quantity = json['quantity']; } if (json['shipDate'] == null) { shipDate = null; @@ -46,12 +46,12 @@ class Order { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } if (json['complete'] == null) { complete = null; } else { - complete = json['complete']; + complete = json['complete']; } } diff --git a/samples/client/petstore/dart2/openapi/lib/model/pet.dart b/samples/client/petstore/dart2/openapi/lib/model/pet.dart index f7747b01cf1d..73407dc7dd0d 100644 --- a/samples/client/petstore/dart2/openapi/lib/model/pet.dart +++ b/samples/client/petstore/dart2/openapi/lib/model/pet.dart @@ -26,7 +26,7 @@ class Pet { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['category'] == null) { category = null; @@ -36,12 +36,12 @@ class Pet { if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } if (json['photoUrls'] == null) { photoUrls = null; } else { - photoUrls = ((json['photoUrls'] ?? []) as List).map((item) => item as String).toList(); + photoUrls = (json['photoUrls'] as List).cast(); } if (json['tags'] == null) { tags = null; @@ -51,7 +51,7 @@ class Pet { if (json['status'] == null) { status = null; } else { - status = json['status']; + status = json['status']; } } diff --git a/samples/client/petstore/dart2/openapi/lib/model/tag.dart b/samples/client/petstore/dart2/openapi/lib/model/tag.dart index 964fa48e0e23..7bd96004c234 100644 --- a/samples/client/petstore/dart2/openapi/lib/model/tag.dart +++ b/samples/client/petstore/dart2/openapi/lib/model/tag.dart @@ -17,12 +17,12 @@ class Tag { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['name'] == null) { name = null; } else { - name = json['name']; + name = json['name']; } } diff --git a/samples/client/petstore/dart2/openapi/lib/model/user.dart b/samples/client/petstore/dart2/openapi/lib/model/user.dart index 067ce8f5c818..0178b539448f 100644 --- a/samples/client/petstore/dart2/openapi/lib/model/user.dart +++ b/samples/client/petstore/dart2/openapi/lib/model/user.dart @@ -29,42 +29,42 @@ class User { if (json['id'] == null) { id = null; } else { - id = json['id']; + id = json['id']; } if (json['username'] == null) { username = null; } else { - username = json['username']; + username = json['username']; } if (json['firstName'] == null) { firstName = null; } else { - firstName = json['firstName']; + firstName = json['firstName']; } if (json['lastName'] == null) { lastName = null; } else { - lastName = json['lastName']; + lastName = json['lastName']; } if (json['email'] == null) { email = null; } else { - email = json['email']; + email = json['email']; } if (json['password'] == null) { password = null; } else { - password = json['password']; + password = json['password']; } if (json['phone'] == null) { phone = null; } else { - phone = json['phone']; + phone = json['phone']; } if (json['userStatus'] == null) { userStatus = null; } else { - userStatus = json['userStatus']; + userStatus = json['userStatus']; } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java index 6fe790dd668c..b00cb6aabb33 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java @@ -174,7 +174,7 @@ public OkHttpClient getHttpClient() { * @param newHttpClient An instance of OkHttpClient * @return Api Client */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { + public ApiClient setHttpClient(OkHttpClient newHttpClient) { if(!httpClient.equals(newHttpClient)) { OkHttpClient.Builder builder = newHttpClient.newBuilder(); Iterator networkInterceptorIterator = httpClient.networkInterceptors().iterator(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java index a1a5d500323f..d87dfd770802 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java @@ -1238,8 +1238,7 @@ public APItestGroupParametersRequest int64Group(Long int64Group) { /** * Build call for testGroupParameters - * @param _progressListener Progress listener - * @param _progressRequestListener Progress request listener + * @param _callback ApiCallback API callback * @return Call to execute * @throws ApiException If fail to serialize the request body object */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java index 6fe790dd668c..b00cb6aabb33 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -174,7 +174,7 @@ public OkHttpClient getHttpClient() { * @param newHttpClient An instance of OkHttpClient * @return Api Client */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { + public ApiClient setHttpClient(OkHttpClient newHttpClient) { if(!httpClient.equals(newHttpClient)) { OkHttpClient.Builder builder = newHttpClient.newBuilder(); Iterator networkInterceptorIterator = httpClient.networkInterceptors().iterator(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java index a1a5d500323f..d87dfd770802 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -1238,8 +1238,7 @@ public APItestGroupParametersRequest int64Group(Long int64Group) { /** * Build call for testGroupParameters - * @param _progressListener Progress listener - * @param _progressRequestListener Progress request listener + * @param _callback ApiCallback API callback * @return Call to execute * @throws ApiException If fail to serialize the request body object */ diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 3c7b53f81496..d94614b34fc7 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -45,6 +45,12 @@ public struct APIHelper { }) } + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? Array { + return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") + } + return source + } public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in