This commit is contained in:
Kristof Vrolijkx 2016-04-28 21:55:21 +02:00
commit a804738e8d
306 changed files with 7783 additions and 5239 deletions

View File

@ -54,4 +54,33 @@ public class ClientOpts {
sb.append("}"); sb.append("}");
return sb.toString(); return sb.toString();
} }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClientOpts that = (ClientOpts) o;
if (uri != null ? !uri.equals(that.uri) : that.uri != null)
return false;
if (target != null ? !target.equals(that.target) : that.target != null)
return false;
if (auth != null ? !auth.equals(that.auth) : that.auth != null)
return false;
if (properties != null ? !properties.equals(that.properties) : that.properties != null)
return false;
return outputDirectory != null ? outputDirectory.equals(that.outputDirectory) : that.outputDirectory == null;
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (target != null ? target.hashCode() : 0);
result = 31 * result + (auth != null ? auth.hashCode() : 0);
result = 31 * result + (properties != null ? properties.hashCode() : 0);
result = 31 * result + (outputDirectory != null ? outputDirectory.hashCode() : 0);
return result;
}
} }

View File

@ -1,7 +1,6 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.models.ExternalDocs; import io.swagger.models.ExternalDocs;
import java.util.*; import java.util.*;
public class CodegenModel { public class CodegenModel {
@ -18,6 +17,8 @@ public class CodegenModel {
public String discriminator; public String discriminator;
public String defaultValue; public String defaultValue;
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>(); public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
public List<CodegenProperty> requiredVars = new ArrayList<CodegenProperty>(); // a list of required properties
public List<CodegenProperty> optionalVars = new ArrayList<CodegenProperty>(); // a list of optional properties
public List<CodegenProperty> allVars; public List<CodegenProperty> allVars;
public List<String> allowableValues; public List<String> allowableValues;
@ -37,4 +38,113 @@ public class CodegenModel {
allVars = vars; allVars = vars;
allMandatory = mandatory; allMandatory = mandatory;
} }
@Override
public String toString() {
return String.format("%s(%s)", name, classname);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodegenModel that = (CodegenModel) o;
if (parent != null ? !parent.equals(that.parent) : that.parent != null)
return false;
if (parentSchema != null ? !parentSchema.equals(that.parentSchema) : that.parentSchema != null)
return false;
if (interfaces != null ? !interfaces.equals(that.interfaces) : that.interfaces != null)
return false;
if (parentModel != null ? !parentModel.equals(that.parentModel) : that.parentModel != null)
return false;
if (interfaceModels != null ? !interfaceModels.equals(that.interfaceModels) : that.interfaceModels != null)
return false;
if (name != null ? !name.equals(that.name) : that.name != null)
return false;
if (classname != null ? !classname.equals(that.classname) : that.classname != null)
return false;
if (description != null ? !description.equals(that.description) : that.description != null)
return false;
if (classVarName != null ? !classVarName.equals(that.classVarName) : that.classVarName != null)
return false;
if (modelJson != null ? !modelJson.equals(that.modelJson) : that.modelJson != null)
return false;
if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != null)
return false;
if (classFilename != null ? !classFilename.equals(that.classFilename) : that.classFilename != null)
return false;
if (unescapedDescription != null ? !unescapedDescription.equals(that.unescapedDescription) : that.unescapedDescription != null)
return false;
if (discriminator != null ? !discriminator.equals(that.discriminator) : that.discriminator != null)
return false;
if (defaultValue != null ? !defaultValue.equals(that.defaultValue) : that.defaultValue != null)
return false;
if (vars != null ? !vars.equals(that.vars) : that.vars != null)
return false;
if (requiredVars != null ? !requiredVars.equals(that.requiredVars) : that.requiredVars != null)
return false;
if (optionalVars != null ? !optionalVars.equals(that.optionalVars) : that.optionalVars != null)
return false;
if (allVars != null ? !allVars.equals(that.allVars) : that.allVars != null)
return false;
if (allowableValues != null ? !allowableValues.equals(that.allowableValues) : that.allowableValues != null)
return false;
if (mandatory != null ? !mandatory.equals(that.mandatory) : that.mandatory != null)
return false;
if (allMandatory != null ? !allMandatory.equals(that.allMandatory) : that.allMandatory != null)
return false;
if (imports != null ? !imports.equals(that.imports) : that.imports != null)
return false;
if (hasVars != null ? !hasVars.equals(that.hasVars) : that.hasVars != null)
return false;
if (emptyVars != null ? !emptyVars.equals(that.emptyVars) : that.emptyVars != null)
return false;
if (hasMoreModels != null ? !hasMoreModels.equals(that.hasMoreModels) : that.hasMoreModels != null)
return false;
if (hasEnums != null ? !hasEnums.equals(that.hasEnums) : that.hasEnums != null)
return false;
if (isEnum != null ? !isEnum.equals(that.isEnum) : that.isEnum != null)
return false;
if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null)
return false;
return vendorExtensions != null ? vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions == null;
}
@Override
public int hashCode() {
int result = parent != null ? parent.hashCode() : 0;
result = 31 * result + (parentSchema != null ? parentSchema.hashCode() : 0);
result = 31 * result + (interfaces != null ? interfaces.hashCode() : 0);
result = 31 * result + (parentModel != null ? parentModel.hashCode() : 0);
result = 31 * result + (interfaceModels != null ? interfaceModels.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (classname != null ? classname.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (classVarName != null ? classVarName.hashCode() : 0);
result = 31 * result + (modelJson != null ? modelJson.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (classFilename != null ? classFilename.hashCode() : 0);
result = 31 * result + (unescapedDescription != null ? unescapedDescription.hashCode() : 0);
result = 31 * result + (discriminator != null ? discriminator.hashCode() : 0);
result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0);
result = 31 * result + (vars != null ? vars.hashCode() : 0);
result = 31 * result + (requiredVars != null ? requiredVars.hashCode() : 0);
result = 31 * result + (optionalVars != null ? optionalVars.hashCode() : 0);
result = 31 * result + (allVars != null ? allVars.hashCode() : 0);
result = 31 * result + (allowableValues != null ? allowableValues.hashCode() : 0);
result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0);
result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0);
result = 31 * result + (imports != null ? imports.hashCode() : 0);
result = 31 * result + (hasVars != null ? hasVars.hashCode() : 0);
result = 31 * result + (emptyVars != null ? emptyVars.hashCode() : 0);
result = 31 * result + (hasMoreModels != null ? hasMoreModels.hashCode() : 0);
result = 31 * result + (hasEnums != null ? hasEnums.hashCode() : 0);
result = 31 * result + (isEnum != null ? isEnum.hashCode() : 0);
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
return result;
}
} }

View File

@ -88,4 +88,157 @@ public class CodegenOperation {
return nonempty(formParams); return nonempty(formParams);
} }
@Override
public String toString() {
return String.format("%s(%s)", baseName, path);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodegenOperation that = (CodegenOperation) o;
if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null)
return false;
if (hasAuthMethods != null ? !hasAuthMethods.equals(that.hasAuthMethods) : that.hasAuthMethods != null)
return false;
if (hasConsumes != null ? !hasConsumes.equals(that.hasConsumes) : that.hasConsumes != null)
return false;
if (hasProduces != null ? !hasProduces.equals(that.hasProduces) : that.hasProduces != null)
return false;
if (hasParams != null ? !hasParams.equals(that.hasParams) : that.hasParams != null)
return false;
if (hasOptionalParams != null ? !hasOptionalParams.equals(that.hasOptionalParams) : that.hasOptionalParams != null)
return false;
if (returnTypeIsPrimitive != null ? !returnTypeIsPrimitive.equals(that.returnTypeIsPrimitive) : that.returnTypeIsPrimitive != null)
return false;
if (returnSimpleType != null ? !returnSimpleType.equals(that.returnSimpleType) : that.returnSimpleType != null)
return false;
if (subresourceOperation != null ? !subresourceOperation.equals(that.subresourceOperation) : that.subresourceOperation != null)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
return false;
if (isMultipart != null ? !isMultipart.equals(that.isMultipart) : that.isMultipart != null)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
return false;
if (isResponseBinary != null ? !isResponseBinary.equals(that.isResponseBinary) : that.isResponseBinary != null)
return false;
if (hasReference != null ? !hasReference.equals(that.hasReference) : that.hasReference != null)
return false;
if (path != null ? !path.equals(that.path) : that.path != null)
return false;
if (operationId != null ? !operationId.equals(that.operationId) : that.operationId != null)
return false;
if (returnType != null ? !returnType.equals(that.returnType) : that.returnType != null)
return false;
if (httpMethod != null ? !httpMethod.equals(that.httpMethod) : that.httpMethod != null)
return false;
if (returnBaseType != null ? !returnBaseType.equals(that.returnBaseType) : that.returnBaseType != null)
return false;
if (returnContainer != null ? !returnContainer.equals(that.returnContainer) : that.returnContainer != null)
return false;
if (summary != null ? !summary.equals(that.summary) : that.summary != null)
return false;
if (unescapedNotes != null ? !unescapedNotes.equals(that.unescapedNotes) : that.unescapedNotes != null)
return false;
if (notes != null ? !notes.equals(that.notes) : that.notes != null)
return false;
if (baseName != null ? !baseName.equals(that.baseName) : that.baseName != null)
return false;
if (defaultResponse != null ? !defaultResponse.equals(that.defaultResponse) : that.defaultResponse != null)
return false;
if (discriminator != null ? !discriminator.equals(that.discriminator) : that.discriminator != null)
return false;
if (consumes != null ? !consumes.equals(that.consumes) : that.consumes != null)
return false;
if (produces != null ? !produces.equals(that.produces) : that.produces != null)
return false;
if (bodyParam != null ? !bodyParam.equals(that.bodyParam) : that.bodyParam != null)
return false;
if (allParams != null ? !allParams.equals(that.allParams) : that.allParams != null)
return false;
if (bodyParams != null ? !bodyParams.equals(that.bodyParams) : that.bodyParams != null)
return false;
if (pathParams != null ? !pathParams.equals(that.pathParams) : that.pathParams != null)
return false;
if (queryParams != null ? !queryParams.equals(that.queryParams) : that.queryParams != null)
return false;
if (headerParams != null ? !headerParams.equals(that.headerParams) : that.headerParams != null)
return false;
if (formParams != null ? !formParams.equals(that.formParams) : that.formParams != null)
return false;
if (authMethods != null ? !authMethods.equals(that.authMethods) : that.authMethods != null)
return false;
if (tags != null ? !tags.equals(that.tags) : that.tags != null)
return false;
if (responses != null ? !responses.equals(that.responses) : that.responses != null)
return false;
if (imports != null ? !imports.equals(that.imports) : that.imports != null)
return false;
if (examples != null ? !examples.equals(that.examples) : that.examples != null)
return false;
if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null)
return false;
if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null)
return false;
if (nickname != null ? !nickname.equals(that.nickname) : that.nickname != null)
return false;
return operationIdLowerCase != null ? operationIdLowerCase.equals(that.operationIdLowerCase) : that.operationIdLowerCase == null;
}
@Override
public int hashCode() {
int result = responseHeaders != null ? responseHeaders.hashCode() : 0;
result = 31 * result + (hasAuthMethods != null ? hasAuthMethods.hashCode() : 0);
result = 31 * result + (hasConsumes != null ? hasConsumes.hashCode() : 0);
result = 31 * result + (hasProduces != null ? hasProduces.hashCode() : 0);
result = 31 * result + (hasParams != null ? hasParams.hashCode() : 0);
result = 31 * result + (hasOptionalParams != null ? hasOptionalParams.hashCode() : 0);
result = 31 * result + (returnTypeIsPrimitive != null ? returnTypeIsPrimitive.hashCode() : 0);
result = 31 * result + (returnSimpleType != null ? returnSimpleType.hashCode() : 0);
result = 31 * result + (subresourceOperation != null ? subresourceOperation.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isMultipart != null ? isMultipart.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isResponseBinary != null ? isResponseBinary.hashCode() : 0);
result = 31 * result + (hasReference != null ? hasReference.hashCode() : 0);
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (operationId != null ? operationId.hashCode() : 0);
result = 31 * result + (returnType != null ? returnType.hashCode() : 0);
result = 31 * result + (httpMethod != null ? httpMethod.hashCode() : 0);
result = 31 * result + (returnBaseType != null ? returnBaseType.hashCode() : 0);
result = 31 * result + (returnContainer != null ? returnContainer.hashCode() : 0);
result = 31 * result + (summary != null ? summary.hashCode() : 0);
result = 31 * result + (unescapedNotes != null ? unescapedNotes.hashCode() : 0);
result = 31 * result + (notes != null ? notes.hashCode() : 0);
result = 31 * result + (baseName != null ? baseName.hashCode() : 0);
result = 31 * result + (defaultResponse != null ? defaultResponse.hashCode() : 0);
result = 31 * result + (discriminator != null ? discriminator.hashCode() : 0);
result = 31 * result + (consumes != null ? consumes.hashCode() : 0);
result = 31 * result + (produces != null ? produces.hashCode() : 0);
result = 31 * result + (bodyParam != null ? bodyParam.hashCode() : 0);
result = 31 * result + (allParams != null ? allParams.hashCode() : 0);
result = 31 * result + (bodyParams != null ? bodyParams.hashCode() : 0);
result = 31 * result + (pathParams != null ? pathParams.hashCode() : 0);
result = 31 * result + (queryParams != null ? queryParams.hashCode() : 0);
result = 31 * result + (headerParams != null ? headerParams.hashCode() : 0);
result = 31 * result + (formParams != null ? formParams.hashCode() : 0);
result = 31 * result + (authMethods != null ? authMethods.hashCode() : 0);
result = 31 * result + (tags != null ? tags.hashCode() : 0);
result = 31 * result + (responses != null ? responses.hashCode() : 0);
result = 31 * result + (imports != null ? imports.hashCode() : 0);
result = 31 * result + (examples != null ? examples.hashCode() : 0);
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + (nickname != null ? nickname.hashCode() : 0);
result = 31 * result + (operationIdLowerCase != null ? operationIdLowerCase.hashCode() : 0);
return result;
}
} }

View File

@ -20,6 +20,7 @@ public class CodegenParameter {
public Map<String, Object> allowableValues; public Map<String, Object> allowableValues;
public CodegenProperty items; public CodegenProperty items;
public Map<String, Object> vendorExtensions; public Map<String, Object> vendorExtensions;
public Boolean hasValidation;
/** /**
* Determines whether this parameter is mandatory. If the parameter is in "path", * Determines whether this parameter is mandatory. If the parameter is in "path",
@ -120,6 +121,7 @@ public class CodegenParameter {
output.items = this.items; output.items = this.items;
} }
output.vendorExtensions = this.vendorExtensions; output.vendorExtensions = this.vendorExtensions;
output.hasValidation = this.hasValidation;
output.isBinary = this.isBinary; output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray; output.isByteArray = this.isByteArray;
output.isString = this.isString; output.isString = this.isString;
@ -135,5 +137,185 @@ public class CodegenParameter {
return output; return output;
} }
@Override
public String toString() {
return String.format("%s(%s)", baseName, dataType);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodegenParameter that = (CodegenParameter) o;
if (isEnum != that.isEnum) return false;
if (isFormParam != null ? !isFormParam.equals(that.isFormParam) : that.isFormParam != null)
return false;
if (isQueryParam != null ? !isQueryParam.equals(that.isQueryParam) : that.isQueryParam != null)
return false;
if (isPathParam != null ? !isPathParam.equals(that.isPathParam) : that.isPathParam != null)
return false;
if (isHeaderParam != null ? !isHeaderParam.equals(that.isHeaderParam) : that.isHeaderParam != null)
return false;
if (isCookieParam != null ? !isCookieParam.equals(that.isCookieParam) : that.isCookieParam != null)
return false;
if (isBodyParam != null ? !isBodyParam.equals(that.isBodyParam) : that.isBodyParam != null)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
return false;
if (isContainer != null ? !isContainer.equals(that.isContainer) : that.isContainer != null)
return false;
if (secondaryParam != null ? !secondaryParam.equals(that.secondaryParam) : that.secondaryParam != null)
return false;
if (isCollectionFormatMulti != null ? !isCollectionFormatMulti.equals(that.isCollectionFormatMulti) : that.isCollectionFormatMulti != null)
return false;
if (isPrimitiveType != null ? !isPrimitiveType.equals(that.isPrimitiveType) : that.isPrimitiveType != null)
return false;
if (baseName != null ? !baseName.equals(that.baseName) : that.baseName != null)
return false;
if (paramName != null ? !paramName.equals(that.paramName) : that.paramName != null)
return false;
if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != null)
return false;
if (datatypeWithEnum != null ? !datatypeWithEnum.equals(that.datatypeWithEnum) : that.datatypeWithEnum != null)
return false;
if (collectionFormat != null ? !collectionFormat.equals(that.collectionFormat) : that.collectionFormat != null)
return false;
if (description != null ? !description.equals(that.description) : that.description != null)
return false;
if (unescapedDescription != null ? !unescapedDescription.equals(that.unescapedDescription) : that.unescapedDescription != null)
return false;
if (baseType != null ? !baseType.equals(that.baseType) : that.baseType != null)
return false;
if (defaultValue != null ? !defaultValue.equals(that.defaultValue) : that.defaultValue != null)
return false;
if (example != null ? !example.equals(that.example) : that.example != null)
return false;
if (jsonSchema != null ? !jsonSchema.equals(that.jsonSchema) : that.jsonSchema != null)
return false;
if (isString != null ? !isString.equals(that.isString) : that.isString != null)
return false;
if (isInteger != null ? !isInteger.equals(that.isInteger) : that.isInteger != null)
return false;
if (isLong != null ? !isLong.equals(that.isLong) : that.isLong != null)
return false;
if (isFloat != null ? !isFloat.equals(that.isFloat) : that.isFloat != null)
return false;
if (isDouble != null ? !isDouble.equals(that.isDouble) : that.isDouble != null)
return false;
if (isByteArray != null ? !isByteArray.equals(that.isByteArray) : that.isByteArray != null)
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
return false;
if (isBoolean != null ? !isBoolean.equals(that.isBoolean) : that.isBoolean != null)
return false;
if (isDate != null ? !isDate.equals(that.isDate) : that.isDate != null)
return false;
if (isDateTime != null ? !isDateTime.equals(that.isDateTime) : that.isDateTime != null)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
return false;
if (notFile != null ? !notFile.equals(that.notFile) : that.notFile != null)
return false;
if (_enum != null ? !_enum.equals(that._enum) : that._enum != null)
return false;
if (allowableValues != null ? !allowableValues.equals(that.allowableValues) : that.allowableValues != null)
return false;
if (items != null ? !items.equals(that.items) : that.items != null)
return false;
if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null)
return false;
if (hasValidation != null ? !hasValidation.equals(that.hasValidation) : that.hasValidation != null)
return false;
if (required != null ? !required.equals(that.required) : that.required != null)
return false;
if (maximum != null ? !maximum.equals(that.maximum) : that.maximum != null)
return false;
if (exclusiveMaximum != null ? !exclusiveMaximum.equals(that.exclusiveMaximum) : that.exclusiveMaximum != null)
return false;
if (minimum != null ? !minimum.equals(that.minimum) : that.minimum != null)
return false;
if (exclusiveMinimum != null ? !exclusiveMinimum.equals(that.exclusiveMinimum) : that.exclusiveMinimum != null)
return false;
if (maxLength != null ? !maxLength.equals(that.maxLength) : that.maxLength != null)
return false;
if (minLength != null ? !minLength.equals(that.minLength) : that.minLength != null)
return false;
if (pattern != null ? !pattern.equals(that.pattern) : that.pattern != null)
return false;
if (maxItems != null ? !maxItems.equals(that.maxItems) : that.maxItems != null)
return false;
if (minItems != null ? !minItems.equals(that.minItems) : that.minItems != null)
return false;
if (uniqueItems != null ? !uniqueItems.equals(that.uniqueItems) : that.uniqueItems != null)
return false;
return multipleOf != null ? multipleOf.equals(that.multipleOf) : that.multipleOf == null;
}
@Override
public int hashCode() {
int result = isFormParam != null ? isFormParam.hashCode() : 0;
result = 31 * result + (isQueryParam != null ? isQueryParam.hashCode() : 0);
result = 31 * result + (isPathParam != null ? isPathParam.hashCode() : 0);
result = 31 * result + (isHeaderParam != null ? isHeaderParam.hashCode() : 0);
result = 31 * result + (isCookieParam != null ? isCookieParam.hashCode() : 0);
result = 31 * result + (isBodyParam != null ? isBodyParam.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isContainer != null ? isContainer.hashCode() : 0);
result = 31 * result + (secondaryParam != null ? secondaryParam.hashCode() : 0);
result = 31 * result + (isCollectionFormatMulti != null ? isCollectionFormatMulti.hashCode() : 0);
result = 31 * result + (isPrimitiveType != null ? isPrimitiveType.hashCode() : 0);
result = 31 * result + (baseName != null ? baseName.hashCode() : 0);
result = 31 * result + (paramName != null ? paramName.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (datatypeWithEnum != null ? datatypeWithEnum.hashCode() : 0);
result = 31 * result + (collectionFormat != null ? collectionFormat.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (unescapedDescription != null ? unescapedDescription.hashCode() : 0);
result = 31 * result + (baseType != null ? baseType.hashCode() : 0);
result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0);
result = 31 * result + (example != null ? example.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
result = 31 * result + (isString != null ? isString.hashCode() : 0);
result = 31 * result + (isInteger != null ? isInteger.hashCode() : 0);
result = 31 * result + (isLong != null ? isLong.hashCode() : 0);
result = 31 * result + (isFloat != null ? isFloat.hashCode() : 0);
result = 31 * result + (isDouble != null ? isDouble.hashCode() : 0);
result = 31 * result + (isByteArray != null ? isByteArray.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (isBoolean != null ? isBoolean.hashCode() : 0);
result = 31 * result + (isDate != null ? isDate.hashCode() : 0);
result = 31 * result + (isDateTime != null ? isDateTime.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isFile != null ? isFile.hashCode() : 0);
result = 31 * result + (notFile != null ? notFile.hashCode() : 0);
result = 31 * result + (isEnum ? 1 : 0);
result = 31 * result + (_enum != null ? _enum.hashCode() : 0);
result = 31 * result + (allowableValues != null ? allowableValues.hashCode() : 0);
result = 31 * result + (items != null ? items.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + (hasValidation != null ? hasValidation.hashCode() : 0);
result = 31 * result + (required != null ? required.hashCode() : 0);
result = 31 * result + (maximum != null ? maximum.hashCode() : 0);
result = 31 * result + (exclusiveMaximum != null ? exclusiveMaximum.hashCode() : 0);
result = 31 * result + (minimum != null ? minimum.hashCode() : 0);
result = 31 * result + (exclusiveMinimum != null ? exclusiveMinimum.hashCode() : 0);
result = 31 * result + (maxLength != null ? maxLength.hashCode() : 0);
result = 31 * result + (minLength != null ? minLength.hashCode() : 0);
result = 31 * result + (pattern != null ? pattern.hashCode() : 0);
result = 31 * result + (maxItems != null ? maxItems.hashCode() : 0);
result = 31 * result + (minItems != null ? minItems.hashCode() : 0);
result = 31 * result + (uniqueItems != null ? uniqueItems.hashCode() : 0);
result = 31 * result + (multipleOf != null ? multipleOf.hashCode() : 0);
return result;
}
} }

View File

@ -42,6 +42,13 @@ public class CodegenProperty {
public Map<String, Object> allowableValues; public Map<String, Object> allowableValues;
public CodegenProperty items; public CodegenProperty items;
public Map<String, Object> vendorExtensions; public Map<String, Object> vendorExtensions;
public Boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template)
@Override
public String toString() {
return String.format("%s(%s)", baseName, datatype);
}
@Override @Override
public int hashCode() public int hashCode()
@ -85,6 +92,7 @@ public class CodegenProperty {
result = prime * result + ((setter == null) ? 0 : setter.hashCode()); result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode()); result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode()); result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
result = prime * result + ((hasValidation == null) ? 0 : hasValidation.hashCode());
result = prime * result + ((isString == null) ? 0 : isString.hashCode()); result = prime * result + ((isString == null) ? 0 : isString.hashCode());
result = prime * result + ((isInteger == null) ? 0 : isInteger.hashCode()); result = prime * result + ((isInteger == null) ? 0 : isInteger.hashCode());
result = prime * result + ((isLong == null) ? 0 : isLong.hashCode()); result = prime * result + ((isLong == null) ? 0 : isLong.hashCode());
@ -202,12 +210,19 @@ public class CodegenProperty {
if (this.allowableValues != other.allowableValues && (this.allowableValues == null || !this.allowableValues.equals(other.allowableValues))) { if (this.allowableValues != other.allowableValues && (this.allowableValues == null || !this.allowableValues.equals(other.allowableValues))) {
return false; return false;
} }
if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) { if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) {
return false; return false;
} }
if (this.hasValidation != other.hasValidation && (this.hasValidation == null || !this.hasValidation.equals(other.hasValidation))) {
return false;
}
if (this.isString != other.isString && (this.isString == null || !this.isString.equals(other.isString))) { if (this.isString != other.isString && (this.isString == null || !this.isString.equals(other.isString))) {
return false; return false;
} }
if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) { if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) {
return false; return false;
} }

View File

@ -22,4 +22,71 @@ public class CodegenResponse {
public boolean isWildcard() { public boolean isWildcard() {
return "0".equals(code) || "default".equals(code); return "0".equals(code) || "default".equals(code);
} }
@Override
public String toString() {
return String.format("%s(%s)", code, containerType);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodegenResponse that = (CodegenResponse) o;
if (headers != null ? !headers.equals(that.headers) : that.headers != null)
return false;
if (code != null ? !code.equals(that.code) : that.code != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
return false;
if (examples != null ? !examples.equals(that.examples) : that.examples != null)
return false;
if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != null)
return false;
if (baseType != null ? !baseType.equals(that.baseType) : that.baseType != null)
return false;
if (containerType != null ? !containerType.equals(that.containerType) : that.containerType != null)
return false;
if (isDefault != null ? !isDefault.equals(that.isDefault) : that.isDefault != null)
return false;
if (simpleType != null ? !simpleType.equals(that.simpleType) : that.simpleType != null)
return false;
if (primitiveType != null ? !primitiveType.equals(that.primitiveType) : that.primitiveType != null)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false;
return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null;
}
@Override
public int hashCode() {
int result = headers != null ? headers.hashCode() : 0;
result = 31 * result + (code != null ? code.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (examples != null ? examples.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (baseType != null ? baseType.hashCode() : 0);
result = 31 * result + (containerType != null ? containerType.hashCode() : 0);
result = 31 * result + (isDefault != null ? isDefault.hashCode() : 0);
result = 31 * result + (simpleType != null ? simpleType.hashCode() : 0);
result = 31 * result + (primitiveType != null ? primitiveType.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (schema != null ? schema.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
return result;
}
} }

View File

@ -13,4 +13,62 @@ public class CodegenSecurity {
// Oauth specific // Oauth specific
public String flow, authorizationUrl, tokenUrl; public String flow, authorizationUrl, tokenUrl;
public List<Map<String, Object>> scopes; public List<Map<String, Object>> scopes;
@Override
public String toString() {
return String.format("%s(%s)", name, type);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodegenSecurity that = (CodegenSecurity) o;
if (name != null ? !name.equals(that.name) : that.name != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
return false;
if (isBasic != null ? !isBasic.equals(that.isBasic) : that.isBasic != null)
return false;
if (isOAuth != null ? !isOAuth.equals(that.isOAuth) : that.isOAuth != null)
return false;
if (isApiKey != null ? !isApiKey.equals(that.isApiKey) : that.isApiKey != null)
return false;
if (keyParamName != null ? !keyParamName.equals(that.keyParamName) : that.keyParamName != null)
return false;
if (isKeyInQuery != null ? !isKeyInQuery.equals(that.isKeyInQuery) : that.isKeyInQuery != null)
return false;
if (isKeyInHeader != null ? !isKeyInHeader.equals(that.isKeyInHeader) : that.isKeyInHeader != null)
return false;
if (flow != null ? !flow.equals(that.flow) : that.flow != null)
return false;
if (authorizationUrl != null ? !authorizationUrl.equals(that.authorizationUrl) : that.authorizationUrl != null)
return false;
if (tokenUrl != null ? !tokenUrl.equals(that.tokenUrl) : that.tokenUrl != null)
return false;
return scopes != null ? scopes.equals(that.scopes) : that.scopes == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isBasic != null ? isBasic.hashCode() : 0);
result = 31 * result + (isOAuth != null ? isOAuth.hashCode() : 0);
result = 31 * result + (isApiKey != null ? isApiKey.hashCode() : 0);
result = 31 * result + (keyParamName != null ? keyParamName.hashCode() : 0);
result = 31 * result + (isKeyInQuery != null ? isKeyInQuery.hashCode() : 0);
result = 31 * result + (isKeyInHeader != null ? isKeyInHeader.hashCode() : 0);
result = 31 * result + (flow != null ? flow.hashCode() : 0);
result = 31 * result + (authorizationUrl != null ? authorizationUrl.hashCode() : 0);
result = 31 * result + (tokenUrl != null ? tokenUrl.hashCode() : 0);
result = 31 * result + (scopes != null ? scopes.hashCode() : 0);
return result;
}
} }

View File

@ -327,6 +327,16 @@ public class DefaultCodegen {
this.ensureUniqueParams = ensureUniqueParams; this.ensureUniqueParams = ensureUniqueParams;
} }
/**
* Return the regular expression/JSON schema pattern (http://json-schema.org/latest/json-schema-validation.html#anchor33)
*
* @param pattern the pattern (regular expression)
* @return properly-escaped pattern
*/
public String toRegularExpression(String pattern) {
return escapeText(pattern);
}
/** /**
* Return the file name of the Api Test * Return the file name of the Api Test
* *
@ -1094,6 +1104,10 @@ public class DefaultCodegen {
property.exclusiveMinimum = np.getExclusiveMinimum(); property.exclusiveMinimum = np.getExclusiveMinimum();
property.exclusiveMaximum = np.getExclusiveMaximum(); property.exclusiveMaximum = np.getExclusiveMaximum();
// check if any validation rule defined
if (property.minimum != null || property.maximum != null || property.exclusiveMinimum != null || property.exclusiveMaximum != null)
property.hasValidation = true;
// legacy support // legacy support
Map<String, Object> allowableValues = new HashMap<String, Object>(); Map<String, Object> allowableValues = new HashMap<String, Object>();
if (np.getMinimum() != null) { if (np.getMinimum() != null) {
@ -1111,7 +1125,12 @@ public class DefaultCodegen {
StringProperty sp = (StringProperty) p; StringProperty sp = (StringProperty) p;
property.maxLength = sp.getMaxLength(); property.maxLength = sp.getMaxLength();
property.minLength = sp.getMinLength(); property.minLength = sp.getMinLength();
property.pattern = sp.getPattern(); property.pattern = toRegularExpression(sp.getPattern());
// check if any validation rule defined
if (property.pattern != null || property.minLength != null || property.maxLength != null)
property.hasValidation = true;
property.isString = true; property.isString = true;
if (sp.getEnum() != null) { if (sp.getEnum() != null) {
List<String> _enum = sp.getEnum(); List<String> _enum = sp.getEnum();
@ -1802,9 +1821,6 @@ public class DefaultCodegen {
if (model.complexType != null) { if (model.complexType != null) {
imports.add(model.complexType); imports.add(model.complexType);
} }
p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength();
p.pattern = qp.getPattern();
p.maximum = qp.getMaximum(); p.maximum = qp.getMaximum();
p.exclusiveMaximum = qp.isExclusiveMaximum(); p.exclusiveMaximum = qp.isExclusiveMaximum();
@ -1812,11 +1828,20 @@ public class DefaultCodegen {
p.exclusiveMinimum = qp.isExclusiveMinimum(); p.exclusiveMinimum = qp.isExclusiveMinimum();
p.maxLength = qp.getMaxLength(); p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength(); p.minLength = qp.getMinLength();
p.pattern = qp.getPattern(); p.pattern = toRegularExpression(qp.getPattern());
p.maxItems = qp.getMaxItems(); p.maxItems = qp.getMaxItems();
p.minItems = qp.getMinItems(); p.minItems = qp.getMinItems();
p.uniqueItems = qp.isUniqueItems(); p.uniqueItems = qp.isUniqueItems();
p.multipleOf = qp.getMultipleOf(); p.multipleOf = qp.getMultipleOf();
if (p.maximum != null || p.exclusiveMaximum != null ||
p.minimum != null || p.exclusiveMinimum != null ||
p.maxLength != null || p.minLength != null ||
p.maxItems != null || p.minItems != null ||
p.pattern != null) {
p.hasValidation = true;
}
} else { } else {
if (!(param instanceof BodyParameter)) { if (!(param instanceof BodyParameter)) {
LOGGER.error("Cannot use Parameter " + param + " as Body Parameter"); LOGGER.error("Cannot use Parameter " + param + " as Body Parameter");
@ -1889,7 +1914,7 @@ public class DefaultCodegen {
// set the example value // set the example value
// if not specified in x-example, generate a default value // if not specified in x-example, generate a default value
if (p.vendorExtensions.containsKey("x-example")) { if (p.vendorExtensions.containsKey("x-example")) {
p.example = (String) p.vendorExtensions.get("x-example"); p.example = Objects.toString(p.vendorExtensions.get("x-example"));
} else if (Boolean.TRUE.equals(p.isString)) { } else if (Boolean.TRUE.equals(p.isString)) {
p.example = p.paramName + "_example"; p.example = p.paramName + "_example";
} else if (Boolean.TRUE.equals(p.isBoolean)) { } else if (Boolean.TRUE.equals(p.isBoolean)) {
@ -2307,6 +2332,12 @@ public class DefaultCodegen {
addImport(m, cp.baseType); addImport(m, cp.baseType);
addImport(m, cp.complexType); addImport(m, cp.complexType);
vars.add(cp); vars.add(cp);
if (Boolean.TRUE.equals(cp.required)) { // if required, add to the list "requiredVars"
m.requiredVars.add(cp);
} else { // else add to the list "optionalVars" for optional property
m.optionalVars.add(cp);
}
} }
} }
} }
@ -2319,18 +2350,28 @@ public class DefaultCodegen {
*/ */
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
public String removeNonNameElementToCamelCase(String name) { public String removeNonNameElementToCamelCase(String name) {
String nonNameElementPattern = "[-_:;#]"; return removeNonNameElementToCamelCase(name, "[-_:;#]");
name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function<String, String>() { // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. }
/**
* Remove characters that is not good to be included in method name from the input and camelize it
*
* @param name string to be camelize
* @param nonNameElementPattern a regex pattern of the characters that is not good to be included in name
* @return camelized string
*/
protected String removeNonNameElementToCamelCase(final String name, final String nonNameElementPattern) {
String result = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function<String, String>() {
@Nullable @Nullable
@Override @Override
public String apply(String input) { public String apply(String input) {
return StringUtils.capitalize(input); return StringUtils.capitalize(input);
} }
}), ""); }), "");
if (name.length() > 0) { if (result.length() > 0) {
name = name.substring(0, 1).toLowerCase() + name.substring(1); result = result.substring(0, 1).toLowerCase() + result.substring(1);
} }
return name; return result;
} }
/** /**

View File

@ -21,4 +21,27 @@ public class SupportingFile {
return builder.toString(); return builder.toString();
} }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SupportingFile that = (SupportingFile) o;
if (templateFile != null ? !templateFile.equals(that.templateFile) : that.templateFile != null)
return false;
if (folder != null ? !folder.equals(that.folder) : that.folder != null)
return false;
return destinationFilename != null ? destinationFilename.equals(that.destinationFilename) : that.destinationFilename == null;
}
@Override
public int hashCode() {
int result = templateFile != null ? templateFile.hashCode() : 0;
result = 31 * result + (folder != null ? folder.hashCode() : 0);
result = 31 * result + (destinationFilename != null ? destinationFilename.hashCode() : 0);
return result;
}
} }

View File

@ -25,6 +25,15 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
super(); super();
} }
@Override
public void processOpts() {
super.processOpts();
// clear model and api doc template as AbstractJavaJAXRSServerCodegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
}
// ================ // ================
// ABSTRACT METHODS // ABSTRACT METHODS
// ================ // ================

View File

@ -51,7 +51,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
"case", "defer", "go", "map", "struct", "case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch", "chan", "else", "goto", "package", "switch",
"const", "fallthrough", "if", "range", "type", "const", "fallthrough", "if", "range", "type",
"continue", "for", "import", "return", "var", "error") "continue", "for", "import", "return", "var", "error", "ApiResponse")
// Added "error" as it's used so frequently that it may as well be a keyword // Added "error" as it's used so frequently that it may as well be a keyword
); );
@ -104,6 +104,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
importMapping = new HashMap<String, String>(); importMapping = new HashMap<String, String>();
importMapping.put("time.Time", "time"); importMapping.put("time.Time", "time");
importMapping.put("*os.File", "os"); importMapping.put("*os.File", "os");
importMapping.put("os", "io/ioutil");
cliOptions.clear(); cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).")
@ -144,6 +145,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go")); supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.go")); supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.go"));
supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go"));
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
} }
@ -323,7 +325,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
return swaggerType; return swaggerType;
} }
return camelize(swaggerType, false); return toModelName(swaggerType);
} }
@Override @Override
@ -374,6 +376,23 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
iterator.remove(); iterator.remove();
} }
// recursivly add import for mapping one type to multipe imports
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
if (recursiveImports == null)
return objs;
ListIterator<Map<String, String>> listIterator = imports.listIterator();
while (listIterator.hasNext()) {
String _import = listIterator.next().get("import");
// if the import package happens to be found in the importMapping (key)
// add the corresponding import package to the list
if (importMapping.containsKey(_import)) {
Map<String, String> newImportMap= new HashMap<String, String>();
newImportMap.put("import", importMapping.get(_import));
listIterator.add(newImportMap);
}
}
return objs; return objs;
} }
@ -388,6 +407,24 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
if (_import.startsWith(prefix)) if (_import.startsWith(prefix))
iterator.remove(); iterator.remove();
} }
// recursivly add import for mapping one type to multipe imports
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
if (recursiveImports == null)
return objs;
ListIterator<Map<String, String>> listIterator = imports.listIterator();
while (listIterator.hasNext()) {
String _import = listIterator.next().get("import");
// if the import package happens to be found in the importMapping (key)
// add the corresponding import package to the list
if (importMapping.containsKey(_import)) {
Map<String, String> newImportMap= new HashMap<String, String>();
newImportMap.put("import", importMapping.get(_import));
listIterator.add(newImportMap);
}
}
return objs; return objs;
} }

View File

@ -0,0 +1,93 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import java.io.File;
import java.util.*;
public class GroovyClientCodegen extends JavaClientCodegen {
public static final String CONFIG_PACKAGE = "configPackage";
protected String title = "Petstore Server";
protected String configPackage = "";
protected String templateFileName = "api.mustache";
public GroovyClientCodegen() {
super();
sourceFolder = projectFolder + File.separator + "groovy";
outputFolder = "generated-code/groovy";
modelTemplateFiles.put("model.mustache", ".groovy");
apiTemplateFiles.put(templateFileName, ".groovy");
embeddedTemplateDir = templateDir = "Groovy";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("title", title);
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
additionalProperties.put(CONFIG_PACKAGE, configPackage);
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
supportedLibraries.clear();
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "groovy";
}
@Override
public String getHelp() {
return "Generates a Groovy API client (beta).";
}
@Override
public void processOpts() {
super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
// TODO readme to be added later
//supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("ApiUtils.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiUtils.groovy"));
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
}

View File

@ -110,7 +110,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta4). Enable the RxJava adapter using '-DuseRxJava=true'."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.1). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.2)");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY); library.setDefault(DEFAULT_LIBRARY);

View File

@ -70,6 +70,11 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
supportingFiles.clear(); supportingFiles.clear();
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));

View File

@ -20,6 +20,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
apiTemplateFiles.put("apiService.mustache", ".java"); apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
apiPackage = "io.swagger.api"; apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model"; modelPackage = "io.swagger.model";
@ -72,6 +73,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) { if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
} }

View File

@ -84,6 +84,11 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
// clear model and api doc template as AbstractJavaJAXRSServerCodegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
} }

View File

@ -314,4 +314,10 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
} }
return super.postProcessSupportingFileData(objs); return super.postProcessSupportingFileData(objs);
} }
@Override
public String removeNonNameElementToCamelCase(String name) {
return removeNonNameElementToCamelCase(name, "[-:;#]");
}
} }

View File

@ -58,10 +58,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("DateTime", "datetime"); typeMapping.put("DateTime", "datetime");
typeMapping.put("object", "object"); typeMapping.put("object", "object");
typeMapping.put("file", "file"); typeMapping.put("file", "file");
//TODO binary should be mapped to byte array // TODO binary should be mapped to byte array
// mapped to String as a workaround // mapped to String as a workaround
typeMapping.put("binary", "str"); typeMapping.put("binary", "str");
typeMapping.put("ByteArray", "str"); typeMapping.put("ByteArray", "str");
// map uuid to string for the time being
typeMapping.put("UUID", "str");
// from https://docs.python.org/release/2.5.4/ref/keywords.html // from https://docs.python.org/release/2.5.4/ref/keywords.html
setReservedWordsLowerCase( setReservedWordsLowerCase(

View File

@ -111,7 +111,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
super.typeMapping = new HashMap<String, String>(); super.typeMapping = new HashMap<String, String>();
typeMapping.put("Date", "QDate"); typeMapping.put("date", "QDate");
typeMapping.put("DateTime", "QDateTime"); typeMapping.put("DateTime", "QDateTime");
typeMapping.put("string", "QString"); typeMapping.put("string", "QString");
typeMapping.put("integer", "qint32"); typeMapping.put("integer", "qint32");

View File

@ -59,6 +59,11 @@ public class SpringMVCServerCodegen extends JavaClientCodegen {
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(CONFIG_PACKAGE)) { if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE)); this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
} }

View File

@ -1,14 +1,9 @@
package {{package}}; package {{package}};
import groovyx.net.http.* import groovyx.net.http.*
import static groovyx.net.http.ContentType.* import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.* import static groovyx.net.http.Method.*
import {{invokerPackage}}.ApiUtils import {{invokerPackage}}.ApiUtils
//-------------
{{#imports}}import {{import}} {{#imports}}import {{import}}
{{/imports}} {{/imports}}
@ -21,36 +16,37 @@ class {{classname}} {
String basePath = "{{basePath}}" String basePath = "{{basePath}}"
String versionPath = "/api/v1" String versionPath = "/api/v1"
{{#operation}}
def {{operationId}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "{{path}}"
{{#operation}} // query params
def {{nickname}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) { def queryParams = [:]
// create path and map variables def headerParams = [:]
String resourcePath = "{{path}}"
{{#allParams}}
{{#required}}
// verify required params are set
if ({{paramName}} == null) {
throw new RuntimeException("missing required params {{paramName}}")
}
{{/required}}
{{/allParams}}
// query params {{#queryParams}}if (!"null".equals(String.valueOf({{paramName}})))
def queryParams = [:] queryParams.put("{{paramName}}", String.valueOf({{paramName}}))
def headerParams = [:] {{/queryParams}}
{{#allParams}} {{#headerParams}}
// verify required params are set headerParams.put("{{paramName}}", {{paramName}})
if({{/allParams}}{{#required}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/required}}{{#allParams}}) { {{/headerParams}}
throw new RuntimeException("missing required params")
}
{{/allParams}}
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}}))) invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
queryParams.put("{{paramName}}", String.valueOf({{paramName}}))
{{/queryParams}}
{{#headerParams}}headerParams.put("{{paramName}}", {{paramName}})
{{/headerParams}}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"{{httpMethod}}", "{{returnContainer}}", "{{httpMethod}}", "{{returnContainer}}",
{{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}}) {{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}})
} }
{{/operation}} {{/operation}}
} }
{{/operations}} {{/operations}}

View File

@ -17,15 +17,26 @@ buildscript {
} }
repositories { repositories {
mavenCentral() mavenCentral()
mavenLocal() mavenLocal()
mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone']) mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone'])
maven { url "http://$artifactory:8080/artifactory/repo" } maven { url "http://$artifactory:8080/artifactory/repo" }
}
ext {
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
} }
dependencies { dependencies {
groovy "org.codehaus.groovy:groovy-all:2.0.5" compile 'org.codehaus.groovy:groovy-all:2.4.6'
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6' compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
} }
task wrapper(type: Wrapper) { gradleVersion = '1.6' } task wrapper(type: Wrapper) { gradleVersion = '1.6' }

View File

@ -94,10 +94,10 @@ if(hasProperty('target') && target == 'android') {
} }
ext { ext {
swagger_annotations_version = "1.5.0" swagger_annotations_version = "1.5.8"
jackson_version = "2.4.2" jackson_version = "2.7.0"
jersey_version = "1.18" jersey_version = "1.19.1"
jodatime_version = "2.3" jodatime_version = "2.9.3"
junit_version = "4.12" junit_version = "4.12"
} }

View File

@ -94,11 +94,12 @@ if(hasProperty('target') && target == 'android') {
} }
ext { ext {
swagger_annotations_version = "1.5.0" swagger_annotations_version = "1.5.8"
jackson_version = "2.6.3" jackson_version = "2.7.0"
feign_version = "8.1.1" feign_version = "8.16.0"
jodatime_version = "2.5" jodatime_version = "2.9.3"
junit_version = "4.12" junit_version = "4.12"
oltu_version = "1.0.1"
} }
dependencies { dependencies {
@ -111,6 +112,7 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile "joda-time:joda-time:$jodatime_version" compile "joda-time:joda-time:$jodatime_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "com.brsanthu:migbase64:2.2" compile "com.brsanthu:migbase64:2.2"
testCompile "junit:junit:$junit_version" testCompile "junit:junit:$junit_version"
} }

View File

@ -100,8 +100,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>1.7</source>
<target>1.6</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
@ -180,11 +180,11 @@
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<feign-version>8.1.1</feign-version> <feign-version>8.16.0</feign-version>
<jackson-version>2.6.3</jackson-version> <jackson-version>2.7.0</jackson-version>
<jodatime-version>2.5</jodatime-version> <jodatime-version>2.9.3</jodatime-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<oltu-version>1.0.0</oltu-version> <oltu-version>1.0.1</oltu-version>
</properties> </properties>
</project> </project>

View File

@ -94,10 +94,10 @@ if(hasProperty('target') && target == 'android') {
} }
ext { ext {
swagger_annotations_version = "1.5.0" swagger_annotations_version = "1.5.8"
jackson_version = "2.4.2" jackson_version = "2.7.0"
jersey_version = "2.22" jersey_version = "2.22.2"
jodatime_version = "2.3" jodatime_version = "2.9.3"
junit_version = "4.12" junit_version = "4.12"
} }

View File

@ -100,8 +100,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>1.7</source>
<target>1.6</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
<!-- For testing build.gradle --> <!-- For testing build.gradle -->
@ -195,9 +195,9 @@
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<jersey-version>2.22</jersey-version> <jersey-version>2.22.2</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.7.0</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.9.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
</properties> </properties>

View File

@ -94,9 +94,9 @@ if(hasProperty('target') && target == 'android') {
} }
dependencies { dependencies {
compile 'io.swagger:swagger-annotations:1.5.0' compile 'io.swagger:swagger-annotations:1.5.8'
compile 'com.squareup.okhttp:okhttp:2.7.2' compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:logging-interceptor:2.7.2' compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
compile 'com.google.code.gson:gson:2.3.1' compile 'com.google.code.gson:gson:2.6.2'
testCompile 'junit:junit:4.12' testCompile 'junit:junit:4.12'
} }

View File

@ -9,10 +9,10 @@ lazy val root = (project in file(".")).
publishArtifact in (Compile, packageDoc) := false, publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal, resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq( libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.0", "io.swagger" % "swagger-annotations" % "1.5.8",
"com.squareup.okhttp" % "okhttp" % "2.7.2", "com.squareup.okhttp" % "okhttp" % "2.7.5",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.2", "com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
"com.google.code.gson" % "gson" % "2.3.1", "com.google.code.gson" % "gson" % "2.6.2",
"junit" % "junit" % "4.8.1" % "test" "junit" % "junit" % "4.12.0" % "test"
) )
) )

View File

@ -100,8 +100,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>1.7</source>
<target>1.6</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
<!-- For testing build.gradle --> <!-- For testing build.gradle -->
@ -160,8 +160,8 @@
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<okhttp-version>2.7.2</okhttp-version> <okhttp-version>2.7.5</okhttp-version>
<gson-version>2.3.1</gson-version> <gson-version>2.6.2</gson-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
</properties> </properties>

View File

@ -94,10 +94,10 @@ if(hasProperty('target') && target == 'android') {
} }
ext { ext {
okhttp_version = "2.3.0" okhttp_version = "2.7.5"
oltu_version = "1.0.0" oltu_version = "1.0.1"
retrofit_version = "1.9.0" retrofit_version = "1.9.0"
swagger_annotations_version = "1.5.0" swagger_annotations_version = "1.5.8"
junit_version = "4.12" junit_version = "4.12"
} }

View File

@ -100,8 +100,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>1.7</source>
<target>1.6</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
@ -139,8 +139,8 @@
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>1.9.0</retrofit-version> <retrofit-version>1.9.0</retrofit-version>
<okhttp-version>2.4.0</okhttp-version> <okhttp-version>2.7.5</okhttp-version>
<oltu-version>1.0.0</oltu-version> <oltu-version>1.0.1</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
</properties> </properties>

View File

@ -94,13 +94,12 @@ if(hasProperty('target') && target == 'android') {
} }
ext { ext {
oltu_version = "1.0.0" oltu_version = "1.0.1"
retrofit_version = "2.0.0-beta4" retrofit_version = "2.0.2"
gson_version = "2.4" swagger_annotations_version = "1.5.8"
swagger_annotations_version = "1.5.0"
junit_version = "4.12" junit_version = "4.12"
{{#useRxJava}} {{#useRxJava}}
rx_java_version = "1.0.16" rx_java_version = "1.1.3"
{{/useRxJava}} {{/useRxJava}}
{{^useRxJava}}{{/useRxJava}} {{^useRxJava}}{{/useRxJava}}
} }

View File

@ -100,8 +100,7 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source> <source>1.7</source>
1.7</source>
<target>1.7</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
@ -113,6 +112,11 @@
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-core-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit-version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.squareup.retrofit2</groupId> <groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId> <artifactId>retrofit</artifactId>
@ -123,11 +127,6 @@
<artifactId>converter-scalars</artifactId> <artifactId>converter-scalars</artifactId>
<version>${retrofit-version}</version> <version>${retrofit-version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit-version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.oltu.oauth2</groupId> <groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId> <artifactId>org.apache.oltu.oauth2.client</artifactId>
@ -154,9 +153,10 @@
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>2.0.0-beta4</retrofit-version>{{#useRxJava}} <retrofit-version>2.0.2</retrofit-version>
<rxjava-version>1.0.16</rxjava-version>{{/useRxJava}} {{#useRxJava}}<rxjava-version>1.1.3</rxjava-version>{{/useRxJava}}
<oltu-version>1.0.0</oltu-version> <okhttp-version>3.2.0</okhttp-version>
<oltu-version>1.0.1</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
</properties> </properties>

View File

@ -97,8 +97,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>1.7</source>
<target>1.6</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
@ -172,9 +172,9 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.8</swagger-annotations-version> <swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>1.18</jersey-version> <jersey-version>1.19.1</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.7.0</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.9.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
</properties> </properties>

View File

@ -47,8 +47,8 @@ goog.require('{{import}}');
/** @private {!angular.$http} */ /** @private {!angular.$http} */
this.http_ = $http; this.http_ = $http;
/** @private {!Object} */ /** @package {!Object} */
this.httpParamSerializer_ = $injector.get('$httpParamSerializer'); this.httpParamSerializer = $injector.get('$httpParamSerializer');
} }
{{package}}.{{classname}}.$inject = ['$http', '$httpParamSerializer', '$injector']; {{package}}.{{classname}}.$inject = ['$http', '$httpParamSerializer', '$injector'];
{{#operation}} {{#operation}}
@ -69,7 +69,7 @@ goog.require('{{import}}');
var queryParameters = {}; var queryParameters = {};
/** @type {!Object} */ /** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders); var headerParams = angular.extend({}, this.defaultHeaders_);
{{#hasFormParams}} {{#hasFormParams}}
/** @type {!Object} */ /** @type {!Object} */
var formParams = {}; var formParams = {};
@ -108,7 +108,7 @@ goog.require('{{import}}');
json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}}, json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}},
{{#bodyParam}}data: {{^required}}opt_{{/required}}{{paramName}}, {{#bodyParam}}data: {{^required}}opt_{{/required}}{{paramName}},
{{/bodyParam}} {{/bodyParam}}
{{#hasFormParams}}data: this.httpParamSerializer_(formParams), {{#hasFormParams}}data: this.httpParamSerializer(formParams),
{{/hasFormParams}} {{/hasFormParams}}
params: queryParameters, params: queryParameters,
headers: headerParams headers: headerParams
@ -118,7 +118,7 @@ goog.require('{{import}}');
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
} }
return this.http_(httpRequestParams); return (/** @type {?} */ (this.http_))(httpRequestParams);
} }
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}

View File

@ -6,6 +6,7 @@ io.swagger.codegen.languages.DartClientCodegen
io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.FlashClientCodegen
io.swagger.codegen.languages.FlaskConnexionCodegen io.swagger.codegen.languages.FlaskConnexionCodegen
io.swagger.codegen.languages.GoClientCodegen io.swagger.codegen.languages.GoClientCodegen
io.swagger.codegen.languages.GroovyClientCodegen
io.swagger.codegen.languages.JavaClientCodegen io.swagger.codegen.languages.JavaClientCodegen
io.swagger.codegen.languages.JavaJerseyServerCodegen io.swagger.codegen.languages.JavaJerseyServerCodegen
io.swagger.codegen.languages.JavaCXFServerCodegen io.swagger.codegen.languages.JavaCXFServerCodegen

View File

@ -6,7 +6,6 @@ import (
"fmt" "fmt"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/dghubble/sling"
{{#imports}} "{{import}}" {{#imports}} "{{import}}"
{{/imports}} {{/imports}}
) )
@ -38,130 +37,115 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}}{
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/ */
func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) { func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}APIResponse, error) {
{{#allParams}}
{{#required}}
// verify the required parameter '{{paramName}}' is set
if &{{paramName}} == nil {
return {{#returnType}}*new({{{returnType}}}), {{/returnType}}errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")
}
{{/required}}
{{/allParams}}
_sling := sling.New().{{httpMethod}}(a.Configuration.BasePath)
{{#authMethods}}// authentication ({{name}}) required var httpMethod = "{{httpMethod}}"
{{#isApiKey}}{{#isKeyInHeader}} // create path and map variables
// set key with prefix in header path := a.Configuration.BasePath + "{{path}}"
_sling.Set("{{keyParamName}}", a.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")) {{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1)
{{/isKeyInHeader}}{{#isKeyInQuery}}
// set key with prefix in querystring
{{#hasKeyParamName}} type KeyQueryParams struct {
{{keyParamName}} string `url:"{{keyParamName}},omitempty"`
}
_sling = _sling.QueryStruct(&KeyQueryParams{ {{keyParamName}}: a.Configuration.GetApiKeyWithPrefix("{{keyParamName}}") })
{{/hasKeyParamName}}
{{/isKeyInQuery}}{{/isApiKey}}
{{#isBasic}}
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
_sling.Set("Authorization", "Basic " + a.Configuration.GetBasicAuthEncodedString())
}
{{/isBasic}}
{{#isOAuth}}
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
}
{{/isOAuth}}
{{/authMethods}}
// create path and map variables
path := "{{basePathWithoutHost}}{{path}}"
{{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1)
{{/pathParams}} {{/pathParams}}
_sling = _sling.Path(path) {{#allParams}}
{{#required}}
// verify the required parameter '{{paramName}}' is set
if &{{paramName}} == nil {
return {{#returnType}}*new({{{returnType}}}), {{/returnType}}*NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")
}
{{/required}}
{{/allParams}}
// add default headers if any headerParams := make(map[string]string)
for key := range a.Configuration.DefaultHeader { queryParams := make(map[string]string)
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key]) formParams := make(map[string]string)
} var postBody interface{}
var fileName string
var fileBytes []byte
{{#hasQueryParams}} type QueryParams struct { {{#authMethods}}// authentication ({{name}}) required
{{#queryParams}}{{vendorExtensions.x-exportParamName}} {{dataType}} `url:"{{baseName}},omitempty"` {{#isApiKey}}{{#isKeyInHeader}}
{{/queryParams}} // set key with prefix in header
} headerParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}")
_sling = _sling.QueryStruct(&QueryParams{ {{#queryParams}}{{vendorExtensions.x-exportParamName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/queryParams}} }) {{/isKeyInHeader}}{{#isKeyInQuery}}
{{/hasQueryParams}} // set key with prefix in querystring
{{#hasKeyParamName}}
queryParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}")
{{/hasKeyParamName}}
{{/isKeyInQuery}}{{/isApiKey}}
{{#isBasic}}
// http basic authentication required
if a.Configuration.Username != "" || a.Configuration.Password != ""{
headerParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
{{/isBasic}}
{{#isOAuth}}
// oauth required
if a.Configuration.AccessToken != ""{
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
{{/isOAuth}}
{{/authMethods}}
// to determine the Content-Type header // add default headers if any
localVarHttpContentTypes := []string { for key := range a.Configuration.DefaultHeader {
{{#consumes}} headerParams[key] = a.Configuration.DefaultHeader[key]
"{{mediaType}}",
{{/consumes}}
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType)
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
{{#produces}}
"{{mediaType}}",
{{/produces}}
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
}
{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}"
_sling = _sling.Set("{{baseName}}", {{paramName}})
{{/headerParams}}{{/hasHeaderParams}}
{{#hasFormParams}} type FormParams struct {
{{#formParams}} {{vendorExtensions.x-exportParamName}} {{dataType}} `url:"{{baseName}},omitempty"`
{{/formParams}}
}
_sling = _sling.BodyForm(&FormParams{ {{#formParams}}{{vendorExtensions.x-exportParamName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/formParams}} })
{{/hasFormParams}}
{{#hasBodyParam}}{{#bodyParams}}// body params
_sling = _sling.BodyJSON({{paramName}})
{{/bodyParams}}{{/hasBodyParam}}
{{#returnType}} var successPayload = new({{returnType}}){{/returnType}}
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive({{#returnType}}successPayload{{/returnType}}{{^returnType}}nil{{/returnType}}, &failurePayload)
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
} }
return {{#returnType}}*successPayload, {{/returnType}}err {{#hasQueryParams}}
{{#queryParams}}
queryParams["{{paramName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}})
{{/queryParams}}
{{/hasQueryParams}}
// to determine the Content-Type header
localVarHttpContentTypes := []string {
{{#consumes}}
"{{mediaType}}",
{{/consumes}}
}
//set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
headerParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
{{#produces}}
"{{mediaType}}",
{{/produces}}
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
headerParams["Accept"] = localVarHttpHeaderAccept
}
{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}"
headerParams["{{baseName}}"] = {{paramName}}
{{/headerParams}}{{/hasHeaderParams}}
{{#hasFormParams}}
{{#formParams}}
{{#isFile}}fbs, _ := ioutil.ReadAll(file)
fileBytes = fbs
fileName = file.Name()
{{/isFile}}
{{^isFile}}formParams["{{paramName}}"] = {{paramName}}
{{/isFile}}
{{/formParams}}
{{/hasFormParams}}{{#hasBodyParam}}{{#bodyParams}} // body params
postBody = &{{paramName}}
{{/bodyParams}}{{/hasBodyParam}}
{{#returnType}} var successPayload = new({{returnType}}){{/returnType}}
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
if err != nil {
return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err
}
{{#returnType}}
err = json.Unmarshal(httpResponse.Body(), &successPayload)
{{/returnType}}
return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err
} }
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}

View File

@ -2,13 +2,18 @@ package {{packageName}}
import ( import (
"strings" "strings"
"github.com/go-resty/resty"
"fmt"
"reflect"
"bytes"
"path/filepath"
) )
type ApiClient struct { type APIClient struct {
} }
func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string { func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
if (len(contentTypes) == 0){ if (len(contentTypes) == 0){
return "" return ""
} }
@ -19,7 +24,7 @@ func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
return contentTypes[0] // use the first content type specified in 'consumes' return contentTypes[0] // use the first content type specified in 'consumes'
} }
func (c *ApiClient) SelectHeaderAccept(accepts []string) string { func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if (len(accepts) == 0){ if (len(accepts) == 0){
return "" return ""
} }
@ -39,3 +44,80 @@ func contains(source []string, containvalue string) bool {
} }
return false return false
} }
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams map[string]string,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
//set debug flag
configuration := NewConfiguration()
resty.SetDebug(configuration.GetDebug())
request := prepareRequest(postBody, headerParams, queryParams, formParams,fileName,fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}) string {
if reflect.TypeOf(obj).String() == "[]string" {
return strings.Join(obj.([]string), ",")
} else {
return obj.(string)
}
}
func prepareRequest(postBody interface{},
headerParams map[string]string,
queryParams map[string]string,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := resty.R()
request.SetBody(postBody)
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}

View File

@ -0,0 +1,24 @@
package {{packageName}}
import (
"net/http"
)
type APIResponse struct {
*http.Response
Message string `json:"message,omitempty"`
}
func NewAPIResponse(r *http.Response) *APIResponse {
response := &APIResponse{Response: r}
return response
}
func NewAPIResponseWithError(errorMessage string) *APIResponse {
response := &APIResponse{Message: errorMessage}
return response
}

View File

@ -7,9 +7,9 @@ import (
type Configuration struct { type Configuration struct {
UserName string `json:"userName,omitempty"` UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"` Password string `json:"password,omitempty"`
ApiKeyPrefix map[string] string `json:"apiKeyPrefix,omitempty"` APIKeyPrefix map[string] string `json:"APIKeyPrefix,omitempty"`
ApiKey map[string] string `json:"apiKey,omitempty"` APIKey map[string] string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"` debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"` DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"` OAuthToken string `json:"oAuthToken,omitempty"`
Timeout int `json:"timeout,omitempty"` Timeout int `json:"timeout,omitempty"`
@ -19,17 +19,17 @@ type Configuration struct {
AccessToken string `json:"accessToken,omitempty"` AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"` UserAgent string `json:"userAgent,omitempty"`
ApiClient ApiClient `json:"apiClient,omitempty"` APIClient APIClient `json:"APIClient,omitempty"`
} }
func NewConfiguration() *Configuration { func NewConfiguration() *Configuration {
return &Configuration{ return &Configuration{
BasePath: "{{basePath}}", BasePath: "{{basePath}}",
UserName: "", UserName: "",
Debug: false, debug: false,
DefaultHeader: make(map[string]string), DefaultHeader: make(map[string]string),
ApiKey: make(map[string]string), APIKey: make(map[string]string),
ApiKeyPrefix: make(map[string]string), APIKeyPrefix: make(map[string]string),
UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/go{{/httpUserAgent}}", UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/go{{/httpUserAgent}}",
} }
} }
@ -42,10 +42,18 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value c.DefaultHeader[key] = value
} }
func (c *Configuration) GetApiKeyWithPrefix(apiKeyIdentifier string) string { func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.ApiKeyPrefix[apiKeyIdentifier] != ""{ if c.APIKeyPrefix[APIKeyIdentifier] != ""{
return c.ApiKeyPrefix[apiKeyIdentifier] + " " + c.ApiKey[apiKeyIdentifier] return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
} }
return c.ApiKey[apiKeyIdentifier] return c.APIKey[APIKeyIdentifier]
}
func (c *Configuration) SetDebug(enable bool){
c.debug = enable
}
func (c *Configuration) GetDebug() bool {
return c.debug
} }

View File

@ -2,6 +2,10 @@
NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
NSString *const {{classPrefix}}DeserializationErrorDomainKey = @"{{classPrefix}}DeserializationErrorDomainKey";
NSInteger const {{classPrefix}}TypeMismatchErrorCode = 143553;
static long requestId = 0; static long requestId = 0;
static bool offlineState = false; static bool offlineState = false;
static NSMutableSet * queuedRequests = nil; static NSMutableSet * queuedRequests = nil;
@ -288,13 +292,7 @@ static void (^reachabilityChangeBlock)(int);
#pragma mark - Deserialize methods #pragma mark - Deserialize methods
- (id) deserialize:(id) data class:(NSString *) class { - (id) deserialize:(id) data class:(NSString *) class error:(NSError **) error {
NSRegularExpression *regexp = nil;
NSTextCheckingResult *match = nil;
NSMutableArray *resultArray = nil;
NSMutableDictionary *resultDict = nil;
NSString *innerType = nil;
// return nil if data is nil or class is nil // return nil if data is nil or class is nil
if (!data || !class) { if (!data || !class) {
return nil; return nil;
@ -310,6 +308,12 @@ static void (^reachabilityChangeBlock)(int);
return data; return data;
} }
NSRegularExpression *regexp = nil;
NSTextCheckingResult *match = nil;
NSMutableArray *resultArray = nil;
NSMutableDictionary *resultDict = nil;
NSString *innerType = nil;
// list of models // list of models
NSString *arrayOfModelsPat = @"NSArray<(.+)>"; NSString *arrayOfModelsPat = @"NSArray<(.+)>";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat
@ -321,14 +325,25 @@ static void (^reachabilityChangeBlock)(int);
range:NSMakeRange(0, [class length])]; range:NSMakeRange(0, [class length])];
if (match) { if (match) {
if(![data isKindOfClass: [NSArray class]]) {
if(error) {
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : NSLocalizedString(@"Received response is not an array", nil)};
*error = [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}TypeMismatchErrorCode userInfo:userInfo];
}
return nil;
}
NSArray *dataArray = data; NSArray *dataArray = data;
innerType = [class substringWithRange:[match rangeAtIndex:1]]; innerType = [class substringWithRange:[match rangeAtIndex:1]];
resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:innerType]]; id arrObj = [self deserialize:obj class:innerType error:error];
if(arrObj) {
[resultArray addObject:arrObj];
} else {
* stop = YES;
} }
]; }];
return resultArray; return resultArray;
} }
@ -348,7 +363,12 @@ static void (^reachabilityChangeBlock)(int);
resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:innerType]]; id arrObj = [self deserialize:obj class:innerType error:error];
if(arrObj) {
[resultArray addObject:arrObj];
} else {
* stop = YES;
}
}]; }];
return resultArray; return resultArray;
@ -369,7 +389,12 @@ static void (^reachabilityChangeBlock)(int);
resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]];
[data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; id dicObj = [self deserialize:obj class:valueType error:error];
if(dicObj) {
[resultDict setValue:dicObj forKey:key];
} else {
* stop = YES;
}
}]; }];
return resultDict; return resultDict;
@ -407,7 +432,7 @@ static void (^reachabilityChangeBlock)(int);
// model // model
Class ModelClass = NSClassFromString(class); Class ModelClass = NSClassFromString(class);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [[ModelClass alloc] initWithDictionary:data error:nil]; return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
} }
return nil; return nil;
@ -635,7 +660,12 @@ static void (^reachabilityChangeBlock)(int);
} }
else { else {
[self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) {
completionBlock([self deserialize:data class:responseType], error); NSError * serializationError;
id response = [self deserialize:data class:responseType error:&serializationError];
if(!response && !error){
error = serializationError;
}
completionBlock(response, error);
}]; }];
} }
return requestId; return requestId;

View File

@ -25,6 +25,16 @@
*/ */
extern NSString *const {{classPrefix}}ResponseObjectErrorKey; extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
/**
* A key for deserialization ErrorDomain
*/
extern NSString *const {{classPrefix}}DeserializationErrorDomainKey;
/**
* Code for deserialization type mismatch error
*/
extern NSInteger const {{classPrefix}}TypeMismatchErrorCode;
/** /**
* Log debug message macro * Log debug message macro
*/ */
@ -171,8 +181,9 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
* *
* @param data The data will be deserialized. * @param data The data will be deserialized.
* @param class The type of objective-c object. * @param class The type of objective-c object.
* @param error The error
*/ */
- (id) deserialize:(id) data class:(NSString *) class; - (id) deserialize:(id) data class:(NSString *) class error:(NSError**)error;
/** /**
* Logs request and response * Logs request and response

View File

@ -31,6 +31,7 @@ Then either install the gem locally:
```shell ```shell
gem install ./{{{gemName}}}-{{{gemVersion}}}.gem gem install ./{{{gemName}}}-{{{gemVersion}}}.gem
``` ```
(for development, run `gem install --dev ./{{{gemName}}}-{{{gemVersion}}}.gem` to install the development dependencies)
or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/).

View File

@ -33,19 +33,59 @@ module {{moduleName}}
{{/required}}{{/allParams}} # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Fixnum, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers {{/required}}{{/allParams}} # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Fixnum, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers
def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
if @api_client.config.debugging if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: {{classname}}#{{operationId}} ..." @api_client.config.logger.debug "Calling API: {{classname}}.{{operationId}} ..."
end end
{{#allParams}}{{#required}} {{#allParams}}
{{#required}}
# verify the required parameter '{{paramName}}' is set # verify the required parameter '{{paramName}}' is set
fail "Missing the required parameter '{{paramName}}' when calling {{operationId}}" if {{{paramName}}}.nil?{{#isEnum}} fail ArgumentError, "Missing the required parameter '{{paramName}}' when calling {{classname}}.{{operationId}}" if {{{paramName}}}.nil?
{{#isEnum}}
# verify enum value
unless [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?({{{paramName}}}) unless [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?({{{paramName}}})
fail "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}" fail ArgumentError, "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"
end{{/isEnum}}
{{/required}}{{^required}}{{#isEnum}}
if opts[:'{{{paramName}}}'] && ![{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(opts[:'{{{paramName}}}'])
fail 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
end end
{{/isEnum}}{{/required}}{{/allParams}} {{/isEnum}}
{{/required}}
{{^required}}
{{#isEnum}}
if opts[:'{{{paramName}}}'] && ![{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(opts[:'{{{paramName}}}'])
fail ArgumentError, 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
end
{{/isEnum}}
{{/required}}
{{#hasValidation}}
{{#minLength}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length > {{{maxLength}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.'
end
{{/minLength}}
{{#maxLength}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length < {{{minLength}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.'
end
{{/maxLength}}
{{#maximum}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} > {{{maximum}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{{maximum}}}.'
end
{{/maximum}}
{{#minimum}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} < {{{minimum}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than or equal to {{{minimum}}}.'
end
{{/minimum}}
{{#pattern}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} !~ Regexp.new({{{pattern}}})
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'
end
{{/pattern}}
{{/hasValidation}}
{{/allParams}}
# resource path # resource path
local_var_path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} local_var_path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}

View File

@ -38,26 +38,183 @@ module {{moduleName}}{{#models}}{{#model}}{{#description}}
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
{{#vars}} {{#vars}}
if attributes[:'{{{baseName}}}'] if attributes.has_key?(:'{{{baseName}}}')
{{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) {{#isContainer}}
if (value = attributes[:'{{{baseName}}}']).is_a?(Array)
self.{{{name}}} = value self.{{{name}}} = value
end{{/isContainer}}{{^isContainer}}self.{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}{{#defaultValue}} end
{{/isContainer}}
{{^isContainer}}
self.{{{name}}} = attributes[:'{{{baseName}}}']
{{/isContainer}}
{{#defaultValue}}
else else
self.{{{name}}} = {{{defaultValue}}}{{/defaultValue}} self.{{{name}}} = {{{defaultValue}}}
{{/defaultValue}}
end end
{{/vars}} {{/vars}}
end end
{{#vars}}{{#isEnum}}
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
{{#isEnum}}
allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]
if @{{{name}}} && !allowed_values.include?({{{name}}})
invalid_properties.push("invalid value for '{{{name}}}', must be one of #{allowed_values}.")
end
{{/isEnum}}
{{#hasValidation}}
if @{{{name}}}.nil?
fail ArgumentError, "{{{name}}} cannot be nil"
end
{{#minLength}}
if @{{{name}}}.to_s.length > {{{maxLength}}}
invalid_properties.push("invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}.")
end
{{/minLength}}
{{#maxLength}}
if @{{{name}}}.to_s.length < {{{minLength}}}
invalid_properties.push("invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}.")
end
{{/maxLength}}
{{#maximum}}
if @{{{name}}} > {{{maximum}}}
invalid_properties.push("invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}.")
end
{{/maximum}}
{{#minimum}}
if @{{{name}}} < {{{minimum}}}
invalid_properties.push("invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}.")
end
{{/minimum}}
{{#pattern}}
if @{{{name}}} !~ Regexp.new({{{pattern}}})
invalid_properties.push("invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}.")
end
{{/pattern}}
{{/hasValidation}}
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
{{#vars}}
{{#required}}
if @{{{name}}}.nil?
return false
end
{{/required}}
{{#isEnum}}
allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]
if @{{{name}}} && !allowed_values.include?(@{{{name}}})
return false
end
{{/isEnum}}
{{#hasValidation}}
{{#minLength}}
if @{{{name}}}.to_s.length > {{{maxLength}}}
return false
end
{{/minLength}}
{{#maxLength}}
if @{{{name}}}.to_s.length < {{{minLength}}}
return false
end
{{/maxLength}}
{{#maximum}}
if @{{{name}}} > {{{maximum}}}
return false
end
{{/maximum}}
{{#minimum}}
if @{{{name}}} < {{{minimum}}}
return false
end
{{/minimum}}
{{#pattern}}
if @{{{name}}} !~ Regexp.new({{{pattern}}})
return false
end
{{/pattern}}
{{/hasValidation}}
{{/vars}}
end
{{#vars}}
{{#isEnum}}
# Custom attribute writer method checking allowed values (enum). # Custom attribute writer method checking allowed values (enum).
# @param [Object] {{{name}}} Object to be assigned # @param [Object] {{{name}}} Object to be assigned
def {{{name}}}=({{{name}}}) def {{{name}}}=({{{name}}})
allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]
if {{{name}}} && !allowed_values.include?({{{name}}}) if {{{name}}} && !allowed_values.include?({{{name}}})
fail "invalid value for '{{{name}}}', must be one of #{allowed_values}" fail ArgumentError, "invalid value for '{{{name}}}', must be one of #{allowed_values}."
end end
@{{{name}}} = {{{name}}} @{{{name}}} = {{{name}}}
end end
{{/isEnum}}{{/vars}}
{{/isEnum}}
{{^isEnum}}
{{#hasValidation}}
# Custom attribute writer method with validation
# @param [Object] {{{name}}} Value to be assigned
def {{{name}}}=({{{name}}})
if {{{name}}}.nil?
fail ArgumentError, "{{{name}}} cannot be nil"
end
{{#minLength}}
if {{{name}}}.to_s.length > {{{maxLength}}}
fail ArgumentError, "invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}."
end
{{/minLength}}
{{#maxLength}}
if {{{name}}}.to_s.length < {{{minLength}}}
fail ArgumentError, "invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}."
end
{{/maxLength}}
{{#maximum}}
if {{{name}}} > {{{maximum}}}
fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}."
end
{{/maximum}}
{{#minimum}}
if {{{name}}} < {{{minimum}}}
fail ArgumentError, "invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}."
end
{{/minimum}}
{{#pattern}}
if @{{{name}}} !~ Regexp.new({{{pattern}}})
fail ArgumentError, "invalid value for '{{{name}}}', must conform to the pattern {{{pattern}}}."
end
{{/pattern}}
@{{{name}}} = {{{name}}}
end
{{/hasValidation}}
{{/isEnum}}
{{/vars}}
# Checks equality by comparing each attribute. # Checks equality by comparing each attribute.
# @param [Object] Object to be compared # @param [Object] Object to be compared
def ==(o) def ==(o)

View File

@ -137,9 +137,22 @@ class Decoders {
// Decoder for {{{classname}}} // Decoder for {{{classname}}}
Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in
let sourceDictionary = source as! [NSObject:AnyObject] let sourceDictionary = source as! [NSObject:AnyObject]
{{#unwrapRequired}}
let instance = {{classname}}({{#requiredVars}}{{^-first}}, {{/-first}}{{#isEnum}}{{name}}: {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? "")! {{/isEnum}}{{^isEnum}}{{name}}: Decoders.decode(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]!){{/isEnum}}{{/requiredVars}})
{{#optionalVars}}
{{#isEnum}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? "")
{{/isEnum}}
{{^isEnum}}
instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"])
{{/isEnum}}
{{/optionalVars}}
{{/unwrapRequired}}
{{^unwrapRequired}}
let instance = {{classname}}(){{#vars}}{{#isEnum}} let instance = {{classname}}(){{#vars}}{{#isEnum}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? ""){{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}} instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? "") {{/isEnum}}{{^isEnum}}
instance.{{name}} = Decoders.decode{{^unwrapRequired}}Optional{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}Optional{{/required}}{{/unwrapRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}}){{/isEnum}}{{/vars}} instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]){{/isEnum}}{{/vars}}
{{/unwrapRequired}}
return instance return instance
}{{/model}} }{{/model}}
{{/models}} {{/models}}

View File

@ -76,9 +76,9 @@ public class {{classname}}: APIBase {
{{#bodyParam}} {{#bodyParam}}
let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}}
let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}}
"{{baseName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}}
"{{baseName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
]{{/hasMore}}{{/queryParams}} ]{{/hasMore}}{{/queryParams}}
let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}}

View File

@ -21,15 +21,24 @@ public class {{classname}}: JSONEncodable {
{{#vars}} {{#vars}}
{{#isEnum}} {{#isEnum}}
{{#description}}/** {{description}} */ {{#description}}/** {{description}} */
{{/description}}public var {{name}}: {{{datatypeWithEnum}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{/description}}public var {{name}}: {{{datatypeWithEnum}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}
{{/isEnum}} {{/isEnum}}
{{^isEnum}} {{^isEnum}}
{{#description}}/** {{description}} */ {{#description}}/** {{description}} */
{{/description}}public var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{/description}}public var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}
{{/isEnum}} {{/isEnum}}
{{/vars}} {{/vars}}
{{^unwrapRequired}}
public init() {} public init() {}
{{/unwrapRequired}}
{{#unwrapRequired}}
public init({{#requiredVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}!{{/isEnum}}{{^isEnum}}{{datatype}}!{{/isEnum}}{{/requiredVars}}) {
{{#requiredVars}}
self.{{name}} = {{name}}
{{/requiredVars}}
}
{{/unwrapRequired}}
// MARK: JSONEncodable // MARK: JSONEncodable
func encodeToJSON() -> AnyObject { func encodeToJSON() -> AnyObject {

View File

@ -559,6 +559,97 @@ paths:
description: Invalid username supplied description: Invalid username supplied
'404': '404':
description: User not found description: User not found
/fake:
post:
tags:
- fake
summary: Fake endpoint for testing various parameters
description: Fake endpoint for testing various parameters
operationId: testEndpointParameters
produces:
- application/xml
- application/json
parameters:
- name: integer
type: integer
maximum: 100
minimum: 10
in: formData
description: None
- name: int32
type: integer
format: int32
maximum: 200
minimum: 20
in: formData
description: None
- name: int64
type: integer
format: int64
in: formData
description: None
- name: number
type: number
maximum: 543.2
minimum: 32.1
in: formData
description: None
required: true
- name: float
type: number
format: float
maximum: 987.6
in: formData
description: None
- name: double
type: number
in: formData
format: double
maximum: 123.4
minimum: 67.8
required: true
description: None
- name: string
type: string
pattern: /[a-z]/i
in: formData
description: None
required: true
- name: byte
type: string
format: byte
in: formData
description: None
required: true
- name: binary
type: string
format: binary
in: formData
description: None
- name: date
type: string
format: date
in: formData
description: None
- name: dateTime
type: string
format: date-time
in: formData
description: None
- name: password
type: string
format: password
maxLength: 64
minLength: 10
in: formData
description: None
responses:
'400':
description: Invalid username supplied
'404':
description: User not found
securityDefinitions: securityDefinitions:
petstore_auth: petstore_auth:
type: oauth2 type: oauth2
@ -755,25 +846,39 @@ definitions:
type: object type: object
required: required:
- number - number
- byte
- date
- password
properties: properties:
integer: integer:
type: integer type: integer
maximum: 100
minimum: 10
int32: int32:
type: integer type: integer
format: int32 format: int32
maximum: 200
minimum: 20
int64: int64:
type: integer type: integer
format: int64 format: int64
number: number:
maximum: 543.2
minimum: 32.1
type: number type: number
float: float:
type: number type: number
format: float format: float
maximum: 987.6
minimum: 54.3
double: double:
type: number type: number
format: double format: double
maximum: 123.4
minimum: 67.8
string: string:
type: string type: string
pattern: /[a-z]/i
byte: byte:
type: string type: string
format: byte format: byte
@ -786,9 +891,14 @@ definitions:
dateTime: dateTime:
type: string type: string
format: date-time format: date-time
uuid:
type: string
format: uuid
password: password:
type: string type: string
format: password format: password
maxLength: 64
minLength: 10
externalDocs: externalDocs:
description: Find out more about Swagger description: Find out more about Swagger
url: 'http://swagger.io' url: 'http://swagger.io'

View File

@ -7,7 +7,7 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge
- API version: 1.0.0 - API version: 1.0.0
- Package version: 1.0.0 - Package version: 1.0.0
- Build date: 2016-04-17T16:17:52.285+08:00 - Build date: 2016-04-23T17:00:49.475-07:00
- Build package: class io.swagger.codegen.languages.GoClientCodegen - Build package: class io.swagger.codegen.languages.GoClientCodegen
## Installation ## Installation
@ -46,8 +46,8 @@ Class | Method | HTTP request | Description
## Documentation For Models ## Documentation For Models
- [ApiResponse](docs/ApiResponse.md)
- [Category](docs/Category.md) - [Category](docs/Category.md)
- [ModelApiResponse](docs/ModelApiResponse.md)
- [Order](docs/Order.md) - [Order](docs/Order.md)
- [Pet](docs/Pet.md) - [Pet](docs/Pet.md)
- [Tag](docs/Tag.md) - [Tag](docs/Tag.md)
@ -57,12 +57,6 @@ Class | Method | HTTP request | Description
## Documentation For Authorization ## Documentation For Authorization
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## petstore_auth ## petstore_auth
- **Type**: OAuth - **Type**: OAuth
@ -72,6 +66,12 @@ Class | Method | HTTP request | Description
- **write:pets**: modify pets in your account - **write:pets**: modify pets in your account
- **read:pets**: read your pets - **read:pets**: read your pets
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## Author ## Author

View File

@ -2,13 +2,18 @@ package swagger
import ( import (
"strings" "strings"
"github.com/go-resty/resty"
"fmt"
"reflect"
"bytes"
"path/filepath"
) )
type ApiClient struct { type APIClient struct {
} }
func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string { func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
if (len(contentTypes) == 0){ if (len(contentTypes) == 0){
return "" return ""
} }
@ -19,7 +24,7 @@ func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
return contentTypes[0] // use the first content type specified in 'consumes' return contentTypes[0] // use the first content type specified in 'consumes'
} }
func (c *ApiClient) SelectHeaderAccept(accepts []string) string { func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if (len(accepts) == 0){ if (len(accepts) == 0){
return "" return ""
} }
@ -39,3 +44,80 @@ func contains(source []string, containvalue string) bool {
} }
return false return false
} }
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams map[string]string,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
//set debug flag
configuration := NewConfiguration()
resty.SetDebug(configuration.GetDebug())
request := prepareRequest(postBody, headerParams, queryParams, formParams,fileName,fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}) string {
if reflect.TypeOf(obj).String() == "[]string" {
return strings.Join(obj.([]string), ",")
} else {
return obj.(string)
}
}
func prepareRequest(postBody interface{},
headerParams map[string]string,
queryParams map[string]string,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := resty.R()
request.SetBody(postBody)
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}

View File

@ -1,14 +1,24 @@
package swagger package swagger
import ( import (
"net/http"
) )
type ApiResponse struct { type APIResponse struct {
*http.Response
Code int32 `json:"code,omitempty"` Message string `json:"message,omitempty"`
}
Type_ string `json:"type,omitempty"`
func NewAPIResponse(r *http.Response) *APIResponse {
Message string `json:"message,omitempty"` response := &APIResponse{Response: r}
return response
}
func NewAPIResponseWithError(errorMessage string) *APIResponse {
response := &APIResponse{Message: errorMessage}
return response
} }

View File

@ -7,9 +7,9 @@ import (
type Configuration struct { type Configuration struct {
UserName string `json:"userName,omitempty"` UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"` Password string `json:"password,omitempty"`
ApiKeyPrefix map[string] string `json:"apiKeyPrefix,omitempty"` APIKeyPrefix map[string] string `json:"APIKeyPrefix,omitempty"`
ApiKey map[string] string `json:"apiKey,omitempty"` APIKey map[string] string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"` debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"` DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"` OAuthToken string `json:"oAuthToken,omitempty"`
Timeout int `json:"timeout,omitempty"` Timeout int `json:"timeout,omitempty"`
@ -19,17 +19,17 @@ type Configuration struct {
AccessToken string `json:"accessToken,omitempty"` AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"` UserAgent string `json:"userAgent,omitempty"`
ApiClient ApiClient `json:"apiClient,omitempty"` APIClient APIClient `json:"APIClient,omitempty"`
} }
func NewConfiguration() *Configuration { func NewConfiguration() *Configuration {
return &Configuration{ return &Configuration{
BasePath: "http://petstore.swagger.io/v2", BasePath: "http://petstore.swagger.io/v2",
UserName: "", UserName: "",
Debug: false, debug: false,
DefaultHeader: make(map[string]string), DefaultHeader: make(map[string]string),
ApiKey: make(map[string]string), APIKey: make(map[string]string),
ApiKeyPrefix: make(map[string]string), APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go", UserAgent: "Swagger-Codegen/1.0.0/go",
} }
} }
@ -42,10 +42,18 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value c.DefaultHeader[key] = value
} }
func (c *Configuration) GetApiKeyWithPrefix(apiKeyIdentifier string) string { func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.ApiKeyPrefix[apiKeyIdentifier] != ""{ if c.APIKeyPrefix[APIKeyIdentifier] != ""{
return c.ApiKeyPrefix[apiKeyIdentifier] + " " + c.ApiKey[apiKeyIdentifier] return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
} }
return c.ApiKey[apiKeyIdentifier] return c.APIKey[APIKeyIdentifier]
}
func (c *Configuration) SetDebug(enable bool){
c.debug = enable
}
func (c *Configuration) GetDebug() bool {
return c.debug
} }

View File

@ -0,0 +1,12 @@
# ModelApiResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Code** | **int32** | | [optional] [default to null]
**Type_** | **string** | | [optional] [default to null]
**Message** | **string** | | [optional] [default to null]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -36,7 +36,7 @@ void (empty response body)
[petstore_auth](../README.md#petstore_auth) [petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: application/json, application/xml - **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -66,7 +66,7 @@ void (empty response body)
[petstore_auth](../README.md#petstore_auth) [petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -95,7 +95,7 @@ Name | Type | Description | Notes
[petstore_auth](../README.md#petstore_auth) [petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -124,7 +124,7 @@ Name | Type | Description | Notes
[petstore_auth](../README.md#petstore_auth) [petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -153,7 +153,7 @@ Name | Type | Description | Notes
[api_key](../README.md#api_key) [api_key](../README.md#api_key)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -182,7 +182,7 @@ void (empty response body)
[petstore_auth](../README.md#petstore_auth) [petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: application/json, application/xml - **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -213,7 +213,7 @@ void (empty response body)
[petstore_auth](../README.md#petstore_auth) [petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded - **Content-Type**: application/x-www-form-urlencoded
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -221,7 +221,7 @@ void (empty response body)
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **UploadFile** # **UploadFile**
> ApiResponse UploadFile($petId, $additionalMetadata, $file) > ModelApiResponse UploadFile($petId, $additionalMetadata, $file)
uploads an image uploads an image
@ -238,13 +238,13 @@ Name | Type | Description | Notes
### Return type ### Return type
[**ApiResponse**](ApiResponse.md) [**ModelApiResponse**](ApiResponse.md)
### Authorization ### Authorization
[petstore_auth](../README.md#petstore_auth) [petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: multipart/form-data - **Content-Type**: multipart/form-data
- **Accept**: application/json - **Accept**: application/json

View File

@ -32,7 +32,7 @@ void (empty response body)
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -58,7 +58,7 @@ This endpoint does not need any parameter.
[api_key](../README.md#api_key) [api_key](../README.md#api_key)
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/json - **Accept**: application/json
@ -87,7 +87,7 @@ Name | Type | Description | Notes
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -116,7 +116,7 @@ Name | Type | Description | Notes
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json

View File

@ -36,7 +36,7 @@ void (empty response body)
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -65,7 +65,7 @@ void (empty response body)
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -94,7 +94,7 @@ void (empty response body)
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -123,7 +123,7 @@ void (empty response body)
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -152,7 +152,7 @@ Name | Type | Description | Notes
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -182,7 +182,7 @@ Name | Type | Description | Notes
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -208,7 +208,7 @@ void (empty response body)
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json
@ -238,7 +238,7 @@ void (empty response body)
No authorization required No authorization required
### HTTP reuqest headers ### HTTP request headers
- **Content-Type**: Not defined - **Content-Type**: Not defined
- **Accept**: application/xml, application/json - **Accept**: application/xml, application/json

View File

@ -0,0 +1,14 @@
package swagger
import (
)
type ModelApiResponse struct {
Code int32 `json:"code,omitempty"`
Type_ string `json:"type,omitempty"`
Message string `json:"message,omitempty"`
}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/dghubble/sling"
) )
type StoreApi struct { type StoreApi struct {
@ -34,159 +33,123 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi{
* @param orderId ID of the order that needs to be deleted * @param orderId ID of the order that needs to be deleted
* @return void * @return void
*/ */
func (a StoreApi) DeleteOrder (orderId string) (error) { func (a StoreApi) DeleteOrder (orderId string) (APIResponse, error) {
// verify the required parameter 'orderId' is set
if &orderId == nil {
return errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder")
}
_sling := sling.New().Delete(a.Configuration.BasePath)
var httpMethod = "Delete"
// create path and map variables
path := a.Configuration.BasePath + "/store/order/{orderId}"
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
// create path and map variables // verify the required parameter 'orderId' is set
path := "/v2/store/order/{orderId}" if &orderId == nil {
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1) return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder")
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
}
// to determine the Content-Type header
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType)
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
"application/xml",
"application/json",
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
}
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive(nil, &failurePayload)
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
} }
return err headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
headerParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
headerParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
"application/xml",
"application/json",
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
headerParams["Accept"] = localVarHttpHeaderAccept
}
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return *NewAPIResponse(httpResponse.RawResponse), err
} }
/** /**
* Returns pet inventories by status * Returns pet inventories by status
* Returns a map of status codes to quantities * Returns a map of status codes to quantities
* @return map[string]int32 * @return map[string]int32
*/ */
func (a StoreApi) GetInventory () (map[string]int32, error) { func (a StoreApi) GetInventory () (map[string]int32, APIResponse, error) {
_sling := sling.New().Get(a.Configuration.BasePath)
// authentication (api_key) required var httpMethod = "Get"
// create path and map variables
// set key with prefix in header path := a.Configuration.BasePath + "/store/inventory"
_sling.Set("api_key", a.Configuration.GetApiKeyWithPrefix("api_key"))
// create path and map variables headerParams := make(map[string]string)
path := "/v2/store/inventory" queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
_sling = _sling.Path(path) // authentication (api_key) required
// add default headers if any // set key with prefix in header
for key := range a.Configuration.DefaultHeader { headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key")
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
}
// to determine the Content-Type header // add default headers if any
localVarHttpContentTypes := []string { for key := range a.Configuration.DefaultHeader {
} headerParams[key] = a.Configuration.DefaultHeader[key]
//set Content-Type header }
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType)
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string { // to determine the Content-Type header
"application/json", localVarHttpContentTypes := []string {
} }
//set Accept header //set Content-Type header
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts) localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpHeaderAccept != "" { if localVarHttpContentType != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept) headerParams["Content-Type"] = localVarHttpContentType
} }
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
"application/json",
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
headerParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(map[string]int32) var successPayload = new(map[string]int32)
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive(successPayload, &failurePayload) if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
} }
return *successPayload, err err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
} }
/** /**
* Find purchase order by ID * Find purchase order by ID
@ -194,80 +157,63 @@ func (a StoreApi) GetInventory () (map[string]int32, error) {
* @param orderId ID of pet that needs to be fetched * @param orderId ID of pet that needs to be fetched
* @return Order * @return Order
*/ */
func (a StoreApi) GetOrderById (orderId int64) (Order, error) { func (a StoreApi) GetOrderById (orderId int64) (Order, APIResponse, error) {
// verify the required parameter 'orderId' is set
if &orderId == nil { var httpMethod = "Get"
return *new(Order), errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById") // create path and map variables
} path := a.Configuration.BasePath + "/store/order/{orderId}"
_sling := sling.New().Get(a.Configuration.BasePath) path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
// verify the required parameter 'orderId' is set
if &orderId == nil {
return *new(Order), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById")
}
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// create path and map variables // add default headers if any
path := "/v2/store/order/{orderId}" for key := range a.Configuration.DefaultHeader {
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1) headerParams[key] = a.Configuration.DefaultHeader[key]
}
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
}
// to determine the Content-Type header // to determine the Content-Type header
localVarHttpContentTypes := []string { localVarHttpContentTypes := []string {
} }
//set Content-Type header //set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes) localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" { if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType) headerParams["Content-Type"] = localVarHttpContentType
} }
// to determine the Accept header
// to determine the Accept header localVarHttpHeaderAccepts := []string {
localVarHttpHeaderAccepts := []string { "application/xml",
"application/xml", "application/json",
"application/json", }
} //set Accept header
//set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" {
if localVarHttpHeaderAccept != "" { headerParams["Accept"] = localVarHttpHeaderAccept
_sling = _sling.Set("Accept", localVarHttpHeaderAccept) }
}
var successPayload = new(Order) var successPayload = new(Order)
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive(successPayload, &failurePayload) if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
} }
return *successPayload, err err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
} }
/** /**
* Place an order for a pet * Place an order for a pet
@ -275,79 +221,62 @@ func (a StoreApi) GetOrderById (orderId int64) (Order, error) {
* @param body order placed for purchasing the pet * @param body order placed for purchasing the pet
* @return Order * @return Order
*/ */
func (a StoreApi) PlaceOrder (body Order) (Order, error) { func (a StoreApi) PlaceOrder (body Order) (Order, APIResponse, error) {
// verify the required parameter 'body' is set
if &body == nil {
return *new(Order), errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder")
}
_sling := sling.New().Post(a.Configuration.BasePath)
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/store/order"
// create path and map variables // verify the required parameter 'body' is set
path := "/v2/store/order" if &body == nil {
return *new(Order), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder")
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
}
// to determine the Content-Type header
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType)
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
"application/xml",
"application/json",
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
}
// body params
_sling = _sling.BodyJSON(body)
var successPayload = new(Order)
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive(successPayload, &failurePayload)
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
} }
return *successPayload, err headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
headerParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
headerParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
"application/xml",
"application/json",
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
postBody = &body
var successPayload = new(Order)
httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
} }

File diff suppressed because it is too large Load Diff

View File

@ -4,6 +4,7 @@ import (
sw "./go-petstore" sw "./go-petstore"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"testing" "testing"
"os"
) )
func TestAddPet(t *testing.T) { func TestAddPet(t *testing.T) {
@ -11,19 +12,36 @@ func TestAddPet(t *testing.T) {
newPet := (sw.Pet{Id: 12830, Name: "gopher", newPet := (sw.Pet{Id: 12830, Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}) PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"})
err := s.AddPet(newPet) apiResponse, err := s.AddPet(newPet)
if err != nil { if err != nil {
t.Errorf("Error while adding pet") t.Errorf("Error while adding pet")
t.Log(err) t.Log(err)
} }
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse.Response)
}
}
func TestFindPetsByStatusWithMissingParam(t *testing.T) {
s := sw.NewPetApi()
_, apiResponse, err := s.FindPetsByStatus(nil)
if err != nil {
t.Errorf("Error while testing TestFindPetsByStatusWithMissingParam")
t.Log(err)
}
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse)
}
} }
func TestGetPetById(t *testing.T) { func TestGetPetById(t *testing.T) {
assert := assert.New(t) assert := assert.New(t)
s := sw.NewPetApi() s := sw.NewPetApi()
resp, err := s.GetPetById(12830) resp, apiResponse, err := s.GetPetById(12830)
if err != nil { if err != nil {
t.Errorf("Error while getting pet by id") t.Errorf("Error while getting pet by id")
t.Log(err) t.Log(err)
@ -34,14 +52,83 @@ func TestGetPetById(t *testing.T) {
//t.Log(resp) //t.Log(resp)
} }
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse.Response)
}
}
func TestGetPetByIdWithInvalidID(t *testing.T) {
s := sw.NewPetApi()
resp, apiResponse, err := s.GetPetById(999999999)
if err != nil {
t.Errorf("Error while getting pet by invalid id")
t.Log(err)
t.Log(apiResponse)
} else {
t.Log(resp)
}
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse.Response)
}
} }
func TestUpdatePetWithForm(t *testing.T) { func TestUpdatePetWithForm(t *testing.T) {
s := sw.NewPetApi() s := sw.NewPetApi()
err := s.UpdatePetWithForm(12830, "golang", "available") apiResponse, err := s.UpdatePetWithForm(12830, "golang", "available")
if err != nil { if err != nil {
t.Errorf("Error while updating pet by id") t.Errorf("Error while updating pet by id")
t.Log(err) t.Log(err)
t.Log(apiResponse)
}
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse.Response)
}
}
func TestFindPetsByStatus(t *testing.T) {
s := sw.NewPetApi()
resp, apiResponse, err := s.FindPetsByStatus([]string {"pending"})
if err != nil {
t.Errorf("Error while getting pet by id")
t.Log(err)
t.Log(apiResponse)
} else {
t.Log(apiResponse)
if len(resp) == 0 {
t.Errorf("Error no pets returned")
}
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse.Response)
}
}
}
func TestUploadFile(t *testing.T) {
s := sw.NewPetApi()
file, _ := os.Open("../python/testfiles/foo.png")
_, apiResponse, err := s.UploadFile(12830, "golang", file)
if err != nil {
t.Errorf("Error while uploading file")
t.Log(err)
}
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse.Response)
}
}
func TestDeletePet(t *testing.T) {
s := sw.NewPetApi()
apiResponse, err := s.DeletePet(12830, "")
if err != nil {
t.Errorf("Error while deleting pet by id")
t.Log(err)
}
if apiResponse.Response.StatusCode != 200 {
t.Log(apiResponse.Response)
} }
} }

View File

@ -22,7 +22,9 @@ func main() {
s.UpdatePetWithForm(12830, "golang", "available") s.UpdatePetWithForm(12830, "golang", "available")
// test GET // test GET
resp, err := s.GetPetById(12830) resp, err, apiResponse := s.GetPetById(12830)
fmt.Println("GetPetById: ", resp, err) fmt.Println("GetPetById: ", resp, err, apiResponse)
err2, apiResponse2 := s.DeletePet(12830, "")
fmt.Println("DeletePet: ", err2, apiResponse2)
} }

View File

@ -0,0 +1,42 @@
apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'eclipse'
def artifactory = 'buildserver.supportspace.com'
group = 'com.supportspace'
archivesBaseName = 'swagger-gen-groovy'
version = '0.1'
buildscript {
repositories {
maven { url 'http://repo.jfrog.org/artifactory/gradle-plugins' }
}
dependencies {
classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.0.16')
}
}
repositories {
mavenCentral()
mavenLocal()
mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone'])
maven { url "http://$artifactory:8080/artifactory/repo" }
}
ext {
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.6'
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
}
task wrapper(type: Wrapper) { gradleVersion = '1.6' }

View File

@ -0,0 +1,50 @@
package io.swagger.api;
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import static groovyx.net.http.ContentType.JSON
import static java.net.URI.create;
class ApiUtils {
def invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, method, container, type) {
def (url, uriPath) = buildUrlAndUriPath(basePath, versionPath, resourcePath)
println "url=$url uriPath=$uriPath"
def http = new HTTPBuilder(url)
http.request( Method.valueOf(method), JSON ) {
uri.path = uriPath
uri.query = queryParams
response.success = { resp, json ->
if (type != null) {
onSuccess(parse(json, container, type))
}
}
response.failure = { resp ->
onFailure(resp.status, resp.statusLine.reasonPhrase)
}
}
}
def buildUrlAndUriPath(basePath, versionPath, resourcePath) {
// HTTPBuilder expects to get as its constructor parameter an URL,
// without any other additions like path, therefore we need to cut the path
// from the basePath as it is represented by swagger APIs
// we use java.net.URI to manipulate the basePath
// then the uriPath will hold the rest of the path
URI baseUri = create(basePath)
def pathOnly = baseUri.getPath()
[basePath-pathOnly, pathOnly+versionPath+resourcePath]
}
def parse(object, container, clazz) {
if (container == "List") {
return object.collect {parse(it, "", clazz)}
} else {
return clazz.newInstance(object)
}
}
}

View File

@ -0,0 +1,184 @@
package io.swagger.api;
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import io.swagger.api.ApiUtils
import io.swagger.model.Pet
import java.io.File
import io.swagger.model.ModelApiResponse
import java.util.*;
@Mixin(ApiUtils)
class PetApi {
String basePath = "http://petstore.swagger.io/v2"
String versionPath = "/api/v1"
def addPet ( Pet body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (body == null) {
throw new RuntimeException("missing required params body")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def deletePet ( Long petId, String apiKey, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet/{petId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (petId == null) {
throw new RuntimeException("missing required params petId")
}
headerParams.put("apiKey", apiKey)
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"DELETE", "",
null )
}
def findPetsByStatus ( List<String> status, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet/findByStatus"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (status == null) {
throw new RuntimeException("missing required params status")
}
if (!"null".equals(String.valueOf(status)))
queryParams.put("status", String.valueOf(status))
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "array",
Pet.class )
}
def findPetsByTags ( List<String> tags, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet/findByTags"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (tags == null) {
throw new RuntimeException("missing required params tags")
}
if (!"null".equals(String.valueOf(tags)))
queryParams.put("tags", String.valueOf(tags))
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "array",
Pet.class )
}
def getPetById ( Long petId, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet/{petId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (petId == null) {
throw new RuntimeException("missing required params petId")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
Pet.class )
}
def updatePet ( Pet body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (body == null) {
throw new RuntimeException("missing required params body")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"PUT", "",
null )
}
def updatePetWithForm ( Long petId, String name, String status, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet/{petId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (petId == null) {
throw new RuntimeException("missing required params petId")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def uploadFile ( Long petId, String additionalMetadata, File file, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/pet/{petId}/uploadImage"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (petId == null) {
throw new RuntimeException("missing required params petId")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
ModelApiResponse.class )
}
}

View File

@ -0,0 +1,93 @@
package io.swagger.api;
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import io.swagger.api.ApiUtils
import io.swagger.model.Order
import java.util.*;
@Mixin(ApiUtils)
class StoreApi {
String basePath = "http://petstore.swagger.io/v2"
String versionPath = "/api/v1"
def deleteOrder ( String orderId, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/store/order/{orderId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (orderId == null) {
throw new RuntimeException("missing required params orderId")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"DELETE", "",
null )
}
def getInventory ( Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/store/inventory"
// query params
def queryParams = [:]
def headerParams = [:]
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "map",
Map.class )
}
def getOrderById ( Long orderId, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/store/order/{orderId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (orderId == null) {
throw new RuntimeException("missing required params orderId")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
Order.class )
}
def placeOrder ( Order body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/store/order"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (body == null) {
throw new RuntimeException("missing required params body")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
Order.class )
}
}

View File

@ -0,0 +1,185 @@
package io.swagger.api;
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import io.swagger.api.ApiUtils
import io.swagger.model.User
import java.util.*;
@Mixin(ApiUtils)
class UserApi {
String basePath = "http://petstore.swagger.io/v2"
String versionPath = "/api/v1"
def createUser ( User body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (body == null) {
throw new RuntimeException("missing required params body")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def createUsersWithArrayInput ( List<User> body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user/createWithArray"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (body == null) {
throw new RuntimeException("missing required params body")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def createUsersWithListInput ( List<User> body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user/createWithList"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (body == null) {
throw new RuntimeException("missing required params body")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def deleteUser ( String username, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user/{username}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (username == null) {
throw new RuntimeException("missing required params username")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"DELETE", "",
null )
}
def getUserByName ( String username, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user/{username}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (username == null) {
throw new RuntimeException("missing required params username")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
User.class )
}
def loginUser ( String username, String password, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user/login"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (username == null) {
throw new RuntimeException("missing required params username")
}
// verify required params are set
if (password == null) {
throw new RuntimeException("missing required params password")
}
if (!"null".equals(String.valueOf(username)))
queryParams.put("username", String.valueOf(username))
if (!"null".equals(String.valueOf(password)))
queryParams.put("password", String.valueOf(password))
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
String.class )
}
def logoutUser ( Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user/logout"
// query params
def queryParams = [:]
def headerParams = [:]
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
null )
}
def updateUser ( String username, User body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/user/{username}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if (username == null) {
throw new RuntimeException("missing required params username")
}
// verify required params are set
if (body == null) {
throw new RuntimeException("missing required params body")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"PUT", "",
null )
}
}

View File

@ -0,0 +1,16 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class Category {
Long id = null
String name = null
}

View File

@ -0,0 +1,18 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class ModelApiResponse {
Integer code = null
String type = null
String message = null
}

View File

@ -0,0 +1,27 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
@Canonical
class Order {
Long id = null
Long petId = null
Integer quantity = null
Date shipDate = null
/* Order Status */
String status = null
Boolean complete = false
}

View File

@ -0,0 +1,30 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.model.Category;
import io.swagger.model.Tag;
import java.util.ArrayList;
import java.util.List;
@Canonical
class Pet {
Long id = null
Category category = null
String name = null
List<String> photoUrls = new ArrayList<String>()
List<Tag> tags = new ArrayList<Tag>()
/* pet status in the store */
String status = null
}

View File

@ -0,0 +1,16 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class Tag {
Long id = null
String name = null
}

View File

@ -0,0 +1,29 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class User {
Long id = null
String username = null
String firstName = null
String lastName = null
String email = null
String password = null
String phone = null
/* User Status */
Integer userStatus = null
}

View File

@ -0,0 +1,50 @@
package io.swagger.api;
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import static groovyx.net.http.ContentType.JSON
import static java.net.URI.create;
class ApiUtils {
def invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, method, container, type) {
def (url, uriPath) = buildUrlAndUriPath(basePath, versionPath, resourcePath)
println "url=$url uriPath=$uriPath"
def http = new HTTPBuilder(url)
http.request( Method.valueOf(method), JSON ) {
uri.path = uriPath
uri.query = queryParams
response.success = { resp, json ->
if (type != null) {
onSuccess(parse(json, container, type))
}
}
response.failure = { resp ->
onFailure(resp.status, resp.statusLine.reasonPhrase)
}
}
}
def buildUrlAndUriPath(basePath, versionPath, resourcePath) {
// HTTPBuilder expects to get as its constructor parameter an URL,
// without any other additions like path, therefore we need to cut the path
// from the basePath as it is represented by swagger APIs
// we use java.net.URI to manipulate the basePath
// then the uriPath will hold the rest of the path
URI baseUri = create(basePath)
def pathOnly = baseUri.getPath()
[basePath-pathOnly, pathOnly+versionPath+resourcePath]
}
def parse(object, container, clazz) {
if (container == "List") {
return object.collect {parse(it, "", clazz)}
} else {
return clazz.newInstance(object)
}
}
}

View File

@ -0,0 +1,218 @@
package io.swagger.api;
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import io.swagger.api.ApiUtils
//-------------
import io.swagger.model.Pet
import java.io.File
import io.swagger.model.ModelApiResponse
import java.util.*;
@Mixin(ApiUtils)
class PetApi {
String basePath = "http://petstore.swagger.io/v2"
String versionPath = "/api/v1"
def addPet ( Pet body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = ""
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def deletePet ( Long petId, String apiKey, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/{petId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if( // verify required params are set
if() {
throw new RuntimeException("missing required params")
}
) {
throw new RuntimeException("missing required params")
}
headerParams.put("apiKey", apiKey)
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"DELETE", "",
null )
}
def findPetsByStatus ( List<String> status, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/findByStatus"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
if(!"null".equals(String.valueOf(status)))
queryParams.put("status", String.valueOf(status))
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "List",
Pet.class )
}
def findPetsByTags ( List<String> tags, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/findByTags"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
if(!"null".equals(String.valueOf(tags)))
queryParams.put("tags", String.valueOf(tags))
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "List",
Pet.class )
}
def getPetById ( Long petId, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/{petId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
Pet.class )
}
def updatePet ( Pet body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = ""
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"PUT", "",
null )
}
def updatePetWithForm ( Long petId, String name, String status, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/{petId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if( // verify required params are set
if( // verify required params are set
if() {
throw new RuntimeException("missing required params")
}
) {
throw new RuntimeException("missing required params")
}
) {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def uploadFile ( Long petId, String additionalMetadata, File file, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/{petId}/uploadImage"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if( // verify required params are set
if( // verify required params are set
if() {
throw new RuntimeException("missing required params")
}
) {
throw new RuntimeException("missing required params")
}
) {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
ModelApiResponse.class )
}
}

View File

@ -0,0 +1,104 @@
package io.swagger.api;
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import io.swagger.api.ApiUtils
//-------------
import java.util.Map
import io.swagger.model.Order
import java.util.*;
@Mixin(ApiUtils)
class StoreApi {
String basePath = "http://petstore.swagger.io/v2"
String versionPath = "/api/v1"
def deleteOrder ( String orderId, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/order/{orderId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"DELETE", "",
null )
}
def getInventory ( Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/inventory"
// query params
def queryParams = [:]
def headerParams = [:]
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "Map",
Map.class )
}
def getOrderById ( Long orderId, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/order/{orderId}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
Order.class )
}
def placeOrder ( Order body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/order"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
Order.class )
}
}

View File

@ -0,0 +1,200 @@
package io.swagger.api;
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import io.swagger.api.ApiUtils
//-------------
import io.swagger.model.User
import java.util.List
import java.util.*;
@Mixin(ApiUtils)
class UserApi {
String basePath = "http://petstore.swagger.io/v2"
String versionPath = "/api/v1"
def createUser ( User body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = ""
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def createUsersWithArrayInput ( List<User> body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/createWithArray"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def createUsersWithListInput ( List<User> body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/createWithList"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"POST", "",
null )
}
def deleteUser ( String username, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/{username}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"DELETE", "",
null )
}
def getUserByName ( String username, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/{username}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if() {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
User.class )
}
def loginUser ( String username, String password, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/login"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if( // verify required params are set
if() {
throw new RuntimeException("missing required params")
}
) {
throw new RuntimeException("missing required params")
}
if(!"null".equals(String.valueOf(username)))
queryParams.put("username", String.valueOf(username))
if(!"null".equals(String.valueOf(password)))
queryParams.put("password", String.valueOf(password))
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
String.class )
}
def logoutUser ( Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/logout"
// query params
def queryParams = [:]
def headerParams = [:]
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"GET", "",
null )
}
def updateUser ( String username, User body, Closure onSuccess, Closure onFailure) {
// create path and map variables
String resourcePath = "/{username}"
// query params
def queryParams = [:]
def headerParams = [:]
// verify required params are set
if( // verify required params are set
if() {
throw new RuntimeException("missing required params")
}
) {
throw new RuntimeException("missing required params")
}
invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams,
"PUT", "",
null )
}
}

View File

@ -0,0 +1,16 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class Category {
Long id = null
String name = null
}

View File

@ -0,0 +1,18 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class ModelApiResponse {
Integer code = null
String type = null
String message = null
}

View File

@ -0,0 +1,27 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
@Canonical
class Order {
Long id = null
Long petId = null
Integer quantity = null
Date shipDate = null
/* Order Status */
String status = null
Boolean complete = false
}

View File

@ -0,0 +1,30 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.model.Category;
import io.swagger.model.Tag;
import java.util.ArrayList;
import java.util.List;
@Canonical
class Pet {
Long id = null
Category category = null
String name = null
List<String> photoUrls = new ArrayList<String>()
List<Tag> tags = new ArrayList<Tag>()
/* pet status in the store */
String status = null
}

View File

@ -0,0 +1,16 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class Tag {
Long id = null
String name = null
}

View File

@ -0,0 +1,29 @@
package io.swagger.model;
import groovy.transform.Canonical
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@Canonical
class User {
Long id = null
String username = null
String firstName = null
String lastName = null
String email = null
String password = null
String phone = null
/* User Status */
Integer userStatus = null
}

View File

@ -94,10 +94,10 @@ if(hasProperty('target') && target == 'android') {
} }
ext { ext {
swagger_annotations_version = "1.5.0" swagger_annotations_version = "1.5.8"
jackson_version = "2.4.2" jackson_version = "2.7.0"
jersey_version = "1.18" jersey_version = "1.19.1"
jodatime_version = "2.3" jodatime_version = "2.9.3"
junit_version = "4.12" junit_version = "4.12"
} }

View File

@ -6,6 +6,7 @@ Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **Integer** | | **name** | **Integer** | |
**snakeCase** | **Integer** | | [optional] **snakeCase** | **Integer** | | [optional]
**property** | **String** | | [optional]

View File

@ -172,9 +172,9 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.8</swagger-annotations-version> <swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>1.18</jersey-version> <jersey-version>1.19.1</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.7.0</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.9.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
</properties> </properties>

View File

@ -8,8 +8,8 @@ import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.model.Pet; import io.swagger.client.model.Pet;
import io.swagger.client.model.ModelApiResponse;
import java.io.File; import java.io.File;
import io.swagger.client.model.ModelApiResponse;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;

View File

@ -17,6 +17,7 @@ public class Name {
private Integer name = null; private Integer name = null;
private Integer snakeCase = null; private Integer snakeCase = null;
private String property = null;
/** /**
@ -43,6 +44,23 @@ public class Name {
} }
/**
**/
public Name property(String property) {
this.property = property;
return this;
}
@ApiModelProperty(example = "null", value = "")
@JsonProperty("property")
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
@Override @Override
public boolean equals(java.lang.Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
@ -53,12 +71,13 @@ public class Name {
} }
Name name = (Name) o; Name name = (Name) o;
return Objects.equals(this.name, name.name) && return Objects.equals(this.name, name.name) &&
Objects.equals(this.snakeCase, name.snakeCase); Objects.equals(this.snakeCase, name.snakeCase) &&
Objects.equals(this.property, name.property);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(name, snakeCase); return Objects.hash(name, snakeCase, property);
} }
@Override @Override
@ -68,6 +87,7 @@ public class Name {
sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n");
sb.append(" property: ").append(toIndentedString(property)).append("\n");
sb.append("}"); sb.append("}");
return sb.toString(); return sb.toString();
} }

View File

@ -94,11 +94,12 @@ if(hasProperty('target') && target == 'android') {
} }
ext { ext {
swagger_annotations_version = "1.5.0" swagger_annotations_version = "1.5.8"
jackson_version = "2.6.3" jackson_version = "2.7.0"
feign_version = "8.1.1" feign_version = "8.16.0"
jodatime_version = "2.5" jodatime_version = "2.9.3"
junit_version = "4.12" junit_version = "4.12"
oltu_version = "1.0.1"
} }
dependencies { dependencies {
@ -111,6 +112,7 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile "joda-time:joda-time:$jodatime_version" compile "joda-time:joda-time:$jodatime_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "com.brsanthu:migbase64:2.2" compile "com.brsanthu:migbase64:2.2"
testCompile "junit:junit:$junit_version" testCompile "junit:junit:$junit_version"
} }

View File

@ -110,7 +110,7 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<!-- HTTP client: Netflix Feign --> <!-- HTTP client: Netflix Feign -->
@ -179,12 +179,12 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-core-version>1.5.8</swagger-core-version>
<feign-version>8.1.1</feign-version> <feign-version>8.16.0</feign-version>
<jackson-version>2.6.3</jackson-version> <jackson-version>2.7.0</jackson-version>
<jodatime-version>2.5</jodatime-version> <jodatime-version>2.9.3</jodatime-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<oltu-version>1.0.0</oltu-version> <oltu-version>1.0.1</oltu-version>
</properties> </properties>
</project> </project>

View File

@ -14,7 +14,7 @@ import feign.codec.EncodeException;
import feign.codec.Encoder; import feign.codec.Encoder;
import feign.RequestTemplate; import feign.RequestTemplate;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-19T19:29:57.731+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public class FormAwareEncoder implements Encoder { public class FormAwareEncoder implements Encoder {
public static final String UTF_8 = "utf-8"; public static final String UTF_8 = "utf-8";
private static final String LINE_FEED = "\r\n"; private static final String LINE_FEED = "\r\n";

View File

@ -1,6 +1,6 @@
package io.swagger.client; package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-19T19:29:57.731+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public class StringUtil { public class StringUtil {
/** /**
* Check if the given array contains the given value (with case-insensitive comparison). * Check if the given array contains the given value (with case-insensitive comparison).

View File

@ -3,8 +3,8 @@ package io.swagger.client.api;
import io.swagger.client.ApiClient; import io.swagger.client.ApiClient;
import io.swagger.client.model.Pet; import io.swagger.client.model.Pet;
import io.swagger.client.model.ModelApiResponse;
import java.io.File; import java.io.File;
import io.swagger.client.model.ModelApiResponse;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -12,7 +12,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import feign.*; import feign.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-21T18:26:32.462+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public interface PetApi extends ApiClient.Api { public interface PetApi extends ApiClient.Api {

View File

@ -10,7 +10,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import feign.*; import feign.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-19T19:29:57.731+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public interface StoreApi extends ApiClient.Api { public interface StoreApi extends ApiClient.Api {

View File

@ -10,7 +10,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import feign.*; import feign.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-19T19:29:57.731+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public interface UserApi extends ApiClient.Api { public interface UserApi extends ApiClient.Api {

View File

@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-19T19:29:57.731+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public class Animal { public class Animal {
private String className = null; private String className = null;

View File

@ -10,7 +10,7 @@ import io.swagger.client.model.Animal;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-19T19:29:57.731+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public class Cat extends Animal { public class Cat extends Animal {
private String className = null; private String className = null;

View File

@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-19T19:29:57.731+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:48:24.088+08:00")
public class Category { public class Category {
private Long id = null; private Long id = null;

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