Merge remote-tracking branch 'origin/master' into 2.3.0

This commit is contained in:
wing328
2017-06-09 15:24:53 +08:00
31 changed files with 267 additions and 146 deletions

View File

@@ -7,6 +7,9 @@ machine:
# Override /etc/hosts
hosts:
petstore.swagger.io: 127.0.0.1
environment:
DOCKER_GENERATOR_IMAGE_NAME: swaggerapi/swagger-generator
DOCKER_CODEGEN_CLI_IMAGE_NAME: swaggerapi/swagger-codegen-cli
dependencies:
cache_directories:
@@ -37,6 +40,6 @@ test:
- java -version
- mvn -q clean verify -Psamples
# docker: build generator image and push to Docker Hub
- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$CIRCLE_TAG" ]; then docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$CIRCLE_TAG; fi && if [ ! -z "$CIRCLE_TAG" ] || [ "$CIRCLE_BRANCH" = "master" ]; then docker push $DOCKER_GENERATOR_IMAGE_NAME; fi; fi
- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build --rm=false -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$CIRCLE_TAG" ]; then docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$CIRCLE_TAG; fi && if [ ! -z "$CIRCLE_TAG" ] || [ "$CIRCLE_BRANCH" = "master" ]; then docker push $DOCKER_GENERATOR_IMAGE_NAME; fi; fi
# docker: build cli image and push to Docker Hub
- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/swagger-codegen-cli && if [ ! -z "$CIRCLE_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$CIRCLE_TAG; fi && if [ ! -z "$CIRCLE_TAG" ] || [ "$CIRCLE_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME; fi; fi
- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build --rm=false -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/swagger-codegen-cli && if [ ! -z "$CIRCLE_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$CIRCLE_TAG; fi && if [ ! -z "$CIRCLE_TAG" ] || [ "$CIRCLE_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME; fi; fi

View File

@@ -1,7 +1,10 @@
package io.swagger.codegen.languages;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import io.swagger.codegen.*;
import io.swagger.codegen.examples.ExampleGenerator;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
@@ -11,6 +14,8 @@ import io.swagger.models.properties.*;
import java.util.*;
import java.io.File;
import static com.google.common.base.Strings.isNullOrEmpty;
public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String DECLSPEC = "declspec";
@@ -20,6 +25,9 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
protected String declspec = "";
protected String defaultInclude = "";
private final Set<String> parentModels = new HashSet<>();
private final Multimap<String, CodegenModel> childrenByParent = ArrayListMultimap.create();
/**
* Configures the type of generator.
*
@@ -236,6 +244,13 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
if (isFileProperty(property)) {
property.vendorExtensions.put("x-codegen-file", true);
}
if (!isNullOrEmpty(model.parent)) {
parentModels.add(model.parent);
if (!childrenByParent.containsEntry(model.parent, model)) {
childrenByParent.put(model.parent, model);
}
}
}
protected boolean isFileProperty(CodegenProperty property) {
@@ -397,4 +412,38 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public Map<String, Object> postProcessAllModels(final Map<String, Object> models) {
final Map<String, Object> processed = super.postProcessAllModels(models);
postProcessParentModels(models);
return processed;
}
private void postProcessParentModels(final Map<String, Object> models) {
for (final String parent : parentModels) {
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models);
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) {
processParentPropertiesInChildModel(parentModel, child);
}
}
}
/**
* Sets the child property's isInherited flag to true if it is an inherited property
*/
private void processParentPropertiesInChildModel(final CodegenModel parent, final CodegenModel child) {
final Map<String, CodegenProperty> childPropertiesByName = new HashMap<>(child.vars.size());
for (final CodegenProperty childProperty : child.vars) {
childPropertiesByName.put(childProperty.name, childProperty);
}
for (final CodegenProperty parentProperty : parent.vars) {
final CodegenProperty duplicatedByParent = childPropertiesByName.get(parentProperty.name);
if (duplicatedByParent != null) {
duplicatedByParent.isInherited = true;
}
}
}
}

View File

@@ -12,6 +12,7 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.models.Swagger;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
@@ -228,7 +229,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
private void postProcessParentModels(final Map<String, Object> models) {
log.debug("Processing parents: " + parentModels);
for (final String parent : parentModels) {
final CodegenModel parentModel = modelByName(parent, models);
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models);
parentModel.hasChildren = true;
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) {
@@ -237,27 +238,6 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
}
}
private CodegenModel modelByName(final String name, final Map<String, Object> models) {
final Object data = models.get(name);
if (data instanceof Map) {
final Map<?, ?> dataMap = (Map<?, ?>) data;
final Object dataModels = dataMap.get("models");
if (dataModels instanceof List) {
final List<?> dataModelsList = (List<?>) dataModels;
for (final Object entry : dataModelsList) {
if (entry instanceof Map) {
final Map<?, ?> entryMap = (Map<?, ?>) entry;
final Object model = entryMap.get("model");
if (model instanceof CodegenModel) {
return (CodegenModel) model;
}
}
}
}
}
return null;
}
private void processParentPropertiesInChildModel(final CodegenModel parent, final CodegenModel child) {
final Map<String, CodegenProperty> childPropertiesByName = new HashMap<>(child.vars.size());
for (final CodegenProperty property : child.vars) {

View File

@@ -10,6 +10,8 @@ import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Info;
import org.yaml.snakeyaml.error.Mark;
import io.swagger.codegen.utils.Markdown;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
@@ -153,6 +155,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
additionalProperties.put("jsProjectName", jsProjectName);
additionalProperties.put("jsModuleName", jsModuleName);
preparHtmlForGlobalDescription(swagger);
}
@Override
@@ -195,6 +199,21 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
return op;
}
/**
* Parse Markdown to HTML for the main "Description" attribute
*
* @param swagger The base object containing the global description through "Info" class
* @return Void
*/
private void preparHtmlForGlobalDescription(Swagger swagger) {
String currentDescription = swagger.getInfo().getDescription();
if (currentDescription != null && !currentDescription.isEmpty()) {
Markdown markInstance = new Markdown();
swagger.getInfo().setDescription( markInstance.toHtml(currentDescription) );
} else {
LOGGER.error("Swagger object description is empty [" + swagger.getInfo().getTitle() + "]");
}
}
private String sanitizePath(String p) {
//prefer replace a ', instead of a fuLL URL encode for readability

View File

@@ -39,11 +39,13 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
public static final String POD_DOCUMENTATION_URL = "podDocumentationURL";
public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace";
public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen";
public static final String LENIENT_TYPE_CAST = "lenientTypeCast";
protected static final String LIBRARY_PROMISE_KIT = "PromiseKit";
protected static final String LIBRARY_RX_SWIFT = "RxSwift";
protected static final String[] RESPONSE_LIBRARIES = {LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT};
protected String projectName = "SwaggerClient";
protected boolean unwrapRequired;
protected boolean lenientTypeCast = false;
protected boolean swiftUseApiNamespace;
protected String[] responseAs = new String[0];
protected String sourceFolder = "Classes" + File.separator + "Swaggers";
@@ -170,12 +172,14 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API"));
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated")
.defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(LENIENT_TYPE_CAST, "Accept and cast values for simple types (string->bool, string->int, int->string)")
.defaultValue(Boolean.FALSE.toString()));
}
@Override
public void processOpts() {
super.processOpts();
// default HIDE_GENERATION_TIMESTAMP to true
if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) {
additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString());
@@ -224,6 +228,8 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
}
setLenientTypeCast(convertPropertyToBooleanAndWriteBack(LENIENT_TYPE_CAST));
supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec"));
supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile"));
supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift"));
@@ -472,6 +478,10 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
this.unwrapRequired = unwrapRequired;
}
public void setLenientTypeCast(boolean lenientTypeCast) {
this.lenientTypeCast = lenientTypeCast;
}
public void setResponseAs(String[] responseAs) {
this.responseAs = responseAs;
}

View File

@@ -0,0 +1,36 @@
package io.swagger.codegen.utils;
import io.swagger.codegen.CodegenModel;
import java.util.List;
import java.util.Map;
public class ModelUtils {
/**
* Searches for the model by name in the map of models and returns it
*
* @param name Name of the model
* @param models Map of models
* @return model
*/
public static CodegenModel getModelByName(final String name, final Map<String, Object> models) {
final Object data = models.get(name);
if (data instanceof Map) {
final Map<?, ?> dataMap = (Map<?, ?>) data;
final Object dataModels = dataMap.get("models");
if (dataModels instanceof List) {
final List<?> dataModelsList = (List<?>) dataModels;
for (final Object entry : dataModelsList) {
if (entry instanceof Map) {
final Map<?, ?> entryMap = (Map<?, ?>) entry;
final Object model = entryMap.get("model");
if (model instanceof CodegenModel) {
return (CodegenModel) model;
}
}
}
}
}
return null;
}
}

View File

@@ -23,8 +23,6 @@ public class ProgressRequestBody extends RequestBody {
private final ProgressRequestListener progressListener;
private BufferedSink bufferedSink;
public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
this.requestBody = requestBody;
this.progressListener = progressListener;
@@ -42,13 +40,9 @@ public class ProgressRequestBody extends RequestBody {
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink));
}
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {

View File

@@ -41,9 +41,6 @@ public class {{classname}}Controller extends Controller {
{{#wrapCalls}}@ApiAction{{/wrapCalls}}
public Result {{operationId}}({{#pathParams}}{{>pathParams}}{{#hasMore}},{{/hasMore}}{{/pathParams}}) {{^handleExceptions}}{{#bodyParams}}throws IOException{{/bodyParams}}{{/handleExceptions}}{{#handleExceptions}}throws Exception{{/handleExceptions}} {
{{#bodyParams}}
{{#collectionFormat}}
//TODO: Support this later
{{/collectionFormat}}
{{^collectionFormat}}
JsonNode node{{paramName}} = request().body().asJson();
{{{dataType}}} {{paramName}};
@@ -59,12 +56,12 @@ public class {{classname}}Controller extends Controller {
{{/bodyParams}}
{{#queryParams}}
{{#collectionFormat}}
//TODO: Support this later
//List<Pair> {{paramName}}Pair = SwaggerUtils.parameterToPairs("{{collectionFormat}}", "{{paramName}}", request().getQueryString("{{baseName}}"));
List<String> {{paramName}}List = SwaggerUtils.parametersToList("{{collectionFormat}}", "{{paramName}}", request().getQueryString("{{baseName}}"));
{{{dataType}}} {{paramName}} = new Array{{{dataType}}}();
//for (Pair pair : {{paramName}}Pair) {
// {{paramName}}.add({{>conversionBegin}}pair.getValue(){{>conversionEnd}});
//}
for (String curParam : {{paramName}}List) {
//noinspection UseBulkOperation
{{paramName}}.add({{>conversionBegin}}curParam{{>conversionEnd}});
}
{{/collectionFormat}}
{{^collectionFormat}}
String value{{paramName}} = request().getQueryString("{{paramName}}");
@@ -89,15 +86,15 @@ public class {{classname}}Controller extends Controller {
{{/notFile}}
{{#notFile}}
{{#collectionFormat}}
//TODO: Support this later
//List<Pair> {{paramName}}Pair = SwaggerUtils.parameterToPairs("{{collectionFormat}}", "{{paramName}}", ((String[]) request().body().asMultipartFormData().asFormUrlEncoded().get("{{baseName}}"))[0]);
List<String> {{paramName}}List = SwaggerUtils.parametersToList("{{collectionFormat}}", "{{paramName}}", (request().body().asMultipartFormData().asFormUrlEncoded().get("{{baseName}}"))[0]);
{{{dataType}}} {{paramName}} = new Array{{{dataType}}}();
//for (Pair pair : {{paramName}}Pair) {
// {{paramName}}.add({{>conversionBegin}}pair.getValue(){{>conversionEnd}});
//}
for (String curParam : {{paramName}}List) {
//noinspection UseBulkOperation
{{paramName}}.add({{>conversionBegin}}curParam{{>conversionEnd}});
}
{{/collectionFormat}}
{{^collectionFormat}}
String value{{paramName}} = ((String[]) request().body().asMultipartFormData().asFormUrlEncoded().get("{{baseName}}"))[0];
String value{{paramName}} = (request().body().asMultipartFormData().asFormUrlEncoded().get("{{baseName}}"))[0];
{{{dataType}}} {{paramName}};
{{^required}}
if (value{{paramName}} != null) {
@@ -112,12 +109,12 @@ public class {{classname}}Controller extends Controller {
{{/formParams}}
{{#headerParams}}
{{#collectionFormat}}
//TODO: Support this later
//List<Pair> {{paramName}}Pair = SwaggerUtils.parameterToPairs("{{collectionFormat}}", "{{paramName}}", request().getHeader("{{baseName}}"));
//{{{dataType}}} {{paramName}} = new Array{{{dataType}}}();
//for (Pair pair : {{paramName}}Pair) {
// {{paramName}}.add({{>conversionBegin}}pair.getValue(){{>conversionEnd}});
//}
List<String> {{paramName}}List = SwaggerUtils.parametersToList("{{collectionFormat}}", "{{paramName}}", request().getHeader("{{baseName}}"));
{{{dataType}}} {{paramName}} = new Array{{{dataType}}}();
for (String curParam : {{paramName}}List) {
//noinspection UseBulkOperation
{{paramName}}.add({{>conversionBegin}}curParam{{>conversionEnd}});
}
{{/collectionFormat}}
{{^collectionFormat}}
String value{{paramName}} = request().getHeader("{{baseName}}");

View File

@@ -7,10 +7,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
public class SwaggerUtils {
@@ -22,8 +19,8 @@ public class SwaggerUtils {
}
{{/handleExceptions}}
public static Map<String, String> parameterToPairs(String collectionFormat, String name, Object value){
Map<String, String> params = new HashMap<>();
public static List<String> parametersToList(String collectionFormat, String name, Object value){
List<String> params = new ArrayList<>();
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
@@ -32,7 +29,7 @@ public class SwaggerUtils {
if (value instanceof Collection) {
valueCollection = (Collection) value;
} else {
params.put(name, parameterToString(value));
params.add(parameterToString(value));
return params;
}
@@ -46,7 +43,7 @@ public class SwaggerUtils {
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.put(name, parameterToString(item));
params.add(parameterToString(item));
}
return params;
@@ -70,7 +67,7 @@ public class SwaggerUtils {
sb.append(parameterToString(item));
}
params.put(name, sb.substring(1));
params.add(sb.substring(1));
return params;
}

View File

@@ -160,10 +160,16 @@ export default class ApiClient {
*/
{{/emitJSDoc}}
isFileParam(param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' && typeof require === 'function' && require('fs') && param instanceof require('fs').ReadStream) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
let fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {

View File

@@ -168,13 +168,16 @@
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
{{/emitJSDoc}} exports.prototype.isFileParam = function(param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' &&
typeof require === 'function' &&
require('fs') &&
param instanceof require('fs').ReadStream) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
var fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;

View File

@@ -325,7 +325,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
{{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result[item.first] = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item.second);
{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result[item.first] = ModelBase::stringFromJson(item.second);
{{/vendorExtensions.x-codegen-response.items.isString}}{{^vendorExtensions.x-codegen-response.items.isString}}{{{vendorExtensions.x-codegen-response.items.datatype}}} itemObj({{{vendorExtensions.x-codegen-response.items.defaultValue}}});
itemObj->fromJson(item);
itemObj->fromJson(item.second);
result[item.first] = itemObj;
{{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}
}

View File

@@ -122,7 +122,7 @@ pplx::task<web::http::http_response> ApiClient::callApi(
web::json::value body_data = web::json::value::object();
for (auto& kvp : formParams)
{
body_data[U(kvp.first)] = ModelBase::toJson(kvp.second);
body_data[kvp.first] = ModelBase::toJson(kvp.second);
}
request.set_body(body_data);
}

View File

@@ -8,8 +8,10 @@
#ifndef {{classname}}_H_
#define {{classname}}_H_
{{^parent}}
{{{defaultInclude}}}
#include "ModelBase.h"
{{/parent}}
{{#imports}}{{{this}}}
{{/imports}}
@@ -22,7 +24,7 @@ namespace {{this}} {
/// {{description}}
/// </summary>
class {{declspec}} {{classname}}
: public ModelBase
: public {{#parent}}{{{parent}}}{{/parent}}{{^parent}}ModelBase{{/parent}}
{
public:
{{classname}}();
@@ -43,6 +45,7 @@ public:
/// {{classname}} members
{{#vars}}
{{^isInherited}}
/// <summary>
/// {{description}}
/// </summary>
@@ -52,12 +55,16 @@ public:
{{/isNotContainer}}{{^required}}bool {{baseName}}IsSet() const;
void unset{{name}}();
{{/required}}
{{/isInherited}}
{{/vars}}
protected:
{{#vars}}{{{datatype}}} m_{{name}};
{{#vars}}
{{^isInherited}}
{{{datatype}}} m_{{name}};
{{^required}}bool m_{{name}}IsSet;
{{/required}}
{{/isInherited}}
{{/vars}}
};

View File

@@ -9,11 +9,11 @@ namespace {{this}} {
{{classname}}::{{classname}}()
{
{{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}m_{{name}} = {{{defaultValue}}};
{{#vars}}{{^isInherited}}{{#isNotContainer}}{{#isPrimitiveType}}m_{{name}} = {{{defaultValue}}};
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isString}}m_{{name}} = {{{defaultValue}}};
{{/isString}}{{#isDateTime}}m_{{name}} = {{{defaultValue}}};
{{/isDateTime}}{{/isPrimitiveType}}{{/isNotContainer}}{{^required}}m_{{name}}IsSet = false;
{{/required}}{{/vars}}
{{/required}}{{/isInherited}}{{/vars}}
}
{{classname}}::~{{classname}}()
@@ -27,9 +27,10 @@ void {{classname}}::validate()
web::json::value {{classname}}::toJson() const
{
web::json::value val = web::json::value::object();
{{#parent}}web::json::value val = this->{{{parent}}}::toJson(); {{/parent}}
{{^parent}}web::json::value val = web::json::value::object();{{/parent}}
{{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet)
{{#vars}}{{^isInherited}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet)
{
val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
}
@@ -53,14 +54,16 @@ web::json::value {{classname}}::toJson() const
val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
}
{{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}}
{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/isInherited}}{{/vars}}
return val;
}
void {{classname}}::fromJson(web::json::value& val)
{
{{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}")))
{{#parent}}this->{{{parent}}}::fromJson(val); {{/parent}}
{{#vars}}{{^isInherited}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}")))
{
{{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")]));
}
@@ -111,7 +114,7 @@ void {{classname}}::fromJson(web::json::value& val)
{{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}});
new{{name}}->fromJson(val[U("{{baseName}}")]);
{{setter}}( new{{name}} );
{{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}}
{{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/isInherited}}{{/vars}}
}
void {{classname}}::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
@@ -222,7 +225,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart,
}
{{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}()
{{#vars}}{{^isInherited}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}()
{
return m_{{name}};
}
@@ -245,6 +248,7 @@ void {{classname}}::unset{{name}}()
m_{{name}}IsSet = false;
}
{{/required}}
{{/isInherited}}
{{/vars}}
{{#modelNamespaceDeclarations}}

View File

@@ -273,7 +273,7 @@ int32_t ModelBase::int32_tFromJson(web::json::value& val)
}
float ModelBase::floatFromJson(web::json::value& val)
{
return val.as_double();
return static_cast<float>(val.as_double());
}
utility::string_t ModelBase::stringFromJson(web::json::value& val)
{

View File

@@ -182,7 +182,7 @@
<div class="app-desc">Version: {{{version}}}</div>
{{/version}}
<hr>
<p class="marked">{{appDescription}}</p>
<div>{{{appDescription}}}</div>
</div>
</div>
<div id="sections">

View File

@@ -140,6 +140,20 @@ class Decoders {
if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T {
return .success(value)
}
{{#lenientTypeCast}}
if T.self is Int32.Type && source is String {
return (source as! NSString).intValue as! T
}
if T.self is Int64.Type && source is String {
return (source as! NSString).intValue as! T
}
if T.self is Bool.Type && source is String {
return (source as! NSString).boolValue as! T
}
if T.self is String.Type && source is NSNumber {
return String(describing: source) as! T
}
{{/lenientTypeCast}}
let key = "\(T.self)"
if let decoder = decoders[key], let value = decoder(source, instance) as? Decoded<T> {

View File

@@ -13,6 +13,7 @@ public class Swift3OptionsProvider implements OptionsProvider {
public static final String PROJECT_NAME_VALUE = "Swagger";
public static final String RESPONSE_AS_VALUE = "test";
public static final String UNWRAP_REQUIRED_VALUE = "true";
public static final String LENIENT_TYPE_CAST_VALUE = "false";
public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," +
" :tag => 'v1.0.0-SNAPSHOT' }";
public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT";
@@ -41,6 +42,7 @@ public class Swift3OptionsProvider implements OptionsProvider {
.put(Swift3Codegen.PROJECT_NAME, PROJECT_NAME_VALUE)
.put(Swift3Codegen.RESPONSE_AS, RESPONSE_AS_VALUE)
.put(Swift3Codegen.UNWRAP_REQUIRED, UNWRAP_REQUIRED_VALUE)
.put(Swift3Codegen.LENIENT_TYPE_CAST, LENIENT_TYPE_CAST_VALUE)
.put(Swift3Codegen.POD_SOURCE, POD_SOURCE_VALUE)
.put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE)
.put(Swift3Codegen.POD_AUTHORS, POD_AUTHORS_VALUE)

View File

@@ -33,6 +33,8 @@ public class Swift3OptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setUnwrapRequired(Boolean.valueOf(Swift3OptionsProvider.UNWRAP_REQUIRED_VALUE));
times = 1;
clientCodegen.setLenientTypeCast(Boolean.valueOf(Swift3OptionsProvider.LENIENT_TYPE_CAST_VALUE));
times = 1;
}};
}
}

View File

@@ -34,8 +34,6 @@ public class ProgressRequestBody extends RequestBody {
private final ProgressRequestListener progressListener;
private BufferedSink bufferedSink;
public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
this.requestBody = requestBody;
this.progressListener = progressListener;
@@ -53,13 +51,9 @@ public class ProgressRequestBody extends RequestBody {
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink));
}
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {

View File

@@ -0,0 +1 @@
2.2.3-SNAPSHOT

View File

@@ -134,7 +134,7 @@ pplx::task<web::http::http_response> ApiClient::callApi(
web::json::value body_data = web::json::value::object();
for (auto& kvp : formParams)
{
body_data[U(kvp.first)] = ModelBase::toJson(kvp.second);
body_data[kvp.first] = ModelBase::toJson(kvp.second);
}
request.set_body(body_data);
}

View File

@@ -285,7 +285,7 @@ int32_t ModelBase::int32_tFromJson(web::json::value& val)
}
float ModelBase::floatFromJson(web::json::value& val)
{
return val.as_double();
return static_cast<float>(val.as_double());
}
utility::string_t ModelBase::stringFromJson(web::json::value& val)
{

View File

@@ -34,8 +34,6 @@ public class ProgressRequestBody extends RequestBody {
private final ProgressRequestListener progressListener;
private BufferedSink bufferedSink;
public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
this.requestBody = requestBody;
this.progressListener = progressListener;
@@ -53,13 +51,9 @@ public class ProgressRequestBody extends RequestBody {
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink));
}
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {

View File

@@ -174,13 +174,16 @@
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
exports.prototype.isFileParam = function(param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' &&
typeof require === 'function' &&
require('fs') &&
param instanceof require('fs').ReadStream) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
var fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;

View File

@@ -174,13 +174,16 @@
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
exports.prototype.isFileParam = function(param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' &&
typeof require === 'function' &&
require('fs') &&
param instanceof require('fs').ReadStream) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
var fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;

View File

@@ -174,13 +174,16 @@
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
exports.prototype.isFileParam = function(param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' &&
typeof require === 'function' &&
require('fs') &&
param instanceof require('fs').ReadStream) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
var fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;

View File

@@ -174,13 +174,16 @@
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
exports.prototype.isFileParam = function(param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' &&
typeof require === 'function' &&
require('fs') &&
param instanceof require('fs').ReadStream) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
var fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;

View File

@@ -62,12 +62,12 @@ public class PetApiController extends Controller {
@ApiAction
public Result findPetsByStatus() throws Exception {
//TODO: Support this later
//List<Pair> statusPair = SwaggerUtils.parameterToPairs("csv", "status", request().getQueryString("status"));
List<String> statusList = SwaggerUtils.parametersToList("csv", "status", request().getQueryString("status"));
List<String> status = new ArrayList<String>();
//for (Pair pair : statusPair) {
// status.add(pair.getValue());
//}
for (String curParam : statusList) {
//noinspection UseBulkOperation
status.add(curParam);
}
List<Pet> obj = imp.findPetsByStatus(status);
JsonNode result = mapper.valueToTree(obj);
return ok(result);
@@ -76,12 +76,12 @@ public class PetApiController extends Controller {
@ApiAction
public Result findPetsByTags() throws Exception {
//TODO: Support this later
//List<Pair> tagsPair = SwaggerUtils.parameterToPairs("csv", "tags", request().getQueryString("tags"));
List<String> tagsList = SwaggerUtils.parametersToList("csv", "tags", request().getQueryString("tags"));
List<String> tags = new ArrayList<String>();
//for (Pair pair : tagsPair) {
// tags.add(pair.getValue());
//}
for (String curParam : tagsList) {
//noinspection UseBulkOperation
tags.add(curParam);
}
List<Pet> obj = imp.findPetsByTags(tags);
JsonNode result = mapper.valueToTree(obj);
return ok(result);
@@ -110,7 +110,7 @@ public class PetApiController extends Controller {
@ApiAction
public Result updatePetWithForm(Long petId) throws Exception {
String valuename = ((String[]) request().body().asMultipartFormData().asFormUrlEncoded().get("name"))[0];
String valuename = (request().body().asMultipartFormData().asFormUrlEncoded().get("name"))[0];
String name;
if (valuename != null) {
name = (String)valuename;
@@ -118,7 +118,7 @@ public class PetApiController extends Controller {
} else {
name = "";
}
String valuestatus = ((String[]) request().body().asMultipartFormData().asFormUrlEncoded().get("status"))[0];
String valuestatus = (request().body().asMultipartFormData().asFormUrlEncoded().get("status"))[0];
String status;
if (valuestatus != null) {
status = (String)valuestatus;
@@ -133,7 +133,7 @@ public class PetApiController extends Controller {
@ApiAction
public Result uploadFile(Long petId) throws Exception {
String valueadditionalMetadata = ((String[]) request().body().asMultipartFormData().asFormUrlEncoded().get("additionalMetadata"))[0];
String valueadditionalMetadata = (request().body().asMultipartFormData().asFormUrlEncoded().get("additionalMetadata"))[0];
String additionalMetadata;
if (valueadditionalMetadata != null) {
additionalMetadata = (String)valueadditionalMetadata;

View File

@@ -7,10 +7,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
public class SwaggerUtils {
@@ -20,8 +17,8 @@ public class SwaggerUtils {
public @interface ApiAction {
}
public static Map<String, String> parameterToPairs(String collectionFormat, String name, Object value){
Map<String, String> params = new HashMap<>();
public static List<String> parametersToList(String collectionFormat, String name, Object value){
List<String> params = new ArrayList<>();
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
@@ -30,7 +27,7 @@ public class SwaggerUtils {
if (value instanceof Collection) {
valueCollection = (Collection) value;
} else {
params.put(name, parameterToString(value));
params.add(parameterToString(value));
return params;
}
@@ -44,7 +41,7 @@ public class SwaggerUtils {
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.put(name, parameterToString(item));
params.add(parameterToString(item));
}
return params;
@@ -68,7 +65,7 @@ public class SwaggerUtils {
sb.append(parameterToString(item));
}
params.put(name, sb.substring(1));
params.add(sb.substring(1));
return params;
}