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("}");
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;
import io.swagger.models.ExternalDocs;
import java.util.*;
public class CodegenModel {
@ -18,6 +17,8 @@ public class CodegenModel {
public String discriminator;
public String defaultValue;
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<String> allowableValues;
@ -37,4 +38,113 @@ public class CodegenModel {
allVars = vars;
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);
}
@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 CodegenProperty items;
public Map<String, Object> vendorExtensions;
public Boolean hasValidation;
/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
@ -120,6 +121,7 @@ public class CodegenParameter {
output.items = this.items;
}
output.vendorExtensions = this.vendorExtensions;
output.hasValidation = this.hasValidation;
output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray;
output.isString = this.isString;
@ -135,5 +137,185 @@ public class CodegenParameter {
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 CodegenProperty items;
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
public int hashCode()
@ -85,6 +92,7 @@ public class CodegenProperty {
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.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 + ((isInteger == null) ? 0 : isInteger.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))) {
return false;
}
if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) {
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))) {
return false;
}
if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) {
return false;
}

View File

@ -22,4 +22,71 @@ public class CodegenResponse {
public boolean isWildcard() {
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
public String flow, authorizationUrl, tokenUrl;
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;
}
/**
* 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
*
@ -1094,6 +1104,10 @@ public class DefaultCodegen {
property.exclusiveMinimum = np.getExclusiveMinimum();
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
Map<String, Object> allowableValues = new HashMap<String, Object>();
if (np.getMinimum() != null) {
@ -1111,7 +1125,12 @@ public class DefaultCodegen {
StringProperty sp = (StringProperty) p;
property.maxLength = sp.getMaxLength();
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;
if (sp.getEnum() != null) {
List<String> _enum = sp.getEnum();
@ -1802,9 +1821,6 @@ public class DefaultCodegen {
if (model.complexType != null) {
imports.add(model.complexType);
}
p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength();
p.pattern = qp.getPattern();
p.maximum = qp.getMaximum();
p.exclusiveMaximum = qp.isExclusiveMaximum();
@ -1812,11 +1828,20 @@ public class DefaultCodegen {
p.exclusiveMinimum = qp.isExclusiveMinimum();
p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength();
p.pattern = qp.getPattern();
p.pattern = toRegularExpression(qp.getPattern());
p.maxItems = qp.getMaxItems();
p.minItems = qp.getMinItems();
p.uniqueItems = qp.isUniqueItems();
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 {
if (!(param instanceof BodyParameter)) {
LOGGER.error("Cannot use Parameter " + param + " as Body Parameter");
@ -1889,7 +1914,7 @@ public class DefaultCodegen {
// set the example value
// if not specified in x-example, generate a default value
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)) {
p.example = p.paramName + "_example";
} else if (Boolean.TRUE.equals(p.isBoolean)) {
@ -2307,6 +2332,12 @@ public class DefaultCodegen {
addImport(m, cp.baseType);
addImport(m, cp.complexType);
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")
public String removeNonNameElementToCamelCase(String name) {
String nonNameElementPattern = "[-_:;#]";
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'.
return removeNonNameElementToCamelCase(name, "[-_:;#]");
}
/**
* 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
@Override
public String apply(String input) {
return StringUtils.capitalize(input);
}
}), "");
if (name.length() > 0) {
name = name.substring(0, 1).toLowerCase() + name.substring(1);
if (result.length() > 0) {
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();
}
@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();
}
@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
// ================

View File

@ -51,7 +51,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
"case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch",
"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
);
@ -104,6 +104,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
importMapping = new HashMap<String, String>();
importMapping.put("time.Time", "time");
importMapping.put("*os.File", "os");
importMapping.put("os", "io/ioutil");
cliOptions.clear();
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("configuration.mustache", "", "configuration.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"));
}
@ -323,7 +325,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
return swaggerType;
}
return camelize(swaggerType, false);
return toModelName(swaggerType);
}
@Override
@ -374,6 +376,23 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
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;
}
@ -388,6 +407,24 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
if (_import.startsWith(prefix))
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;
}

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("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_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");
library.setDefault(DEFAULT_LIBRARY);

View File

@ -70,6 +70,11 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
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");
supportingFiles.clear();
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
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("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
@ -72,6 +73,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
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(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() {
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)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}

View File

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

View File

@ -62,6 +62,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
// mapped to String as a workaround
typeMapping.put("binary", "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
setReservedWordsLowerCase(

View File

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

View File

@ -59,6 +59,11 @@ public class SpringMVCServerCodegen extends JavaClientCodegen {
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));
}

View File

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

View File

@ -23,9 +23,20 @@ repositories {
maven { url "http://$artifactory:8080/artifactory/repo" }
}
ext {
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
}
dependencies {
groovy "org.codehaus.groovy:groovy-all:2.0.5"
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6'
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

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

View File

@ -94,11 +94,12 @@ if(hasProperty('target') && target == 'android') {
}
ext {
swagger_annotations_version = "1.5.0"
jackson_version = "2.6.3"
feign_version = "8.1.1"
jodatime_version = "2.5"
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
feign_version = "8.16.0"
jodatime_version = "2.9.3"
junit_version = "4.12"
oltu_version = "1.0.1"
}
dependencies {
@ -111,6 +112,7 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
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"
testCompile "junit:junit:$junit_version"
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,7 +6,6 @@ import (
"fmt"
"encoding/json"
"errors"
"github.com/dghubble/sling"
{{#imports}} "{{import}}"
{{/imports}}
)
@ -38,60 +37,63 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}}{
{{#allParams}} * @param {{paramName}} {{description}}
{{/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) {
var httpMethod = "{{httpMethod}}"
// create path and map variables
path := a.Configuration.BasePath + "{{path}}"
{{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1)
{{/pathParams}}
{{#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}}")
return {{#returnType}}*new({{{returnType}}}), {{/returnType}}*NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")
}
{{/required}}
{{/allParams}}
_sling := sling.New().{{httpMethod}}(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
{{#authMethods}}// authentication ({{name}}) required
{{#isApiKey}}{{#isKeyInHeader}}
// set key with prefix in header
_sling.Set("{{keyParamName}}", a.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))
headerParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}")
{{/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}}
queryParams["{{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())
headerParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
{{/isBasic}}
{{#isOAuth}}
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["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}}
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
{{#hasQueryParams}} type QueryParams struct {
{{#queryParams}}{{vendorExtensions.x-exportParamName}} {{dataType}} `url:"{{baseName}},omitempty"`
{{#hasQueryParams}}
{{#queryParams}}
queryParams["{{paramName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}})
{{/queryParams}}
}
_sling = _sling.QueryStruct(&QueryParams{ {{#queryParams}}{{vendorExtensions.x-exportParamName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/queryParams}} })
{{/hasQueryParams}}
// to determine the Content-Type header
@ -101,11 +103,10 @@ func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{
{{/consumes}}
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType)
headerParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
{{#produces}}
@ -113,55 +114,38 @@ func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{
{{/produces}}
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}"
_sling = _sling.Set("{{baseName}}", {{paramName}})
headerParams["{{baseName}}"] = {{paramName}}
{{/headerParams}}{{/hasHeaderParams}}
{{#hasFormParams}} type FormParams struct {
{{#formParams}} {{vendorExtensions.x-exportParamName}} {{dataType}} `url:"{{baseName}},omitempty"`
{{#hasFormParams}}
{{#formParams}}
{{#isFile}}fbs, _ := ioutil.ReadAll(file)
fileBytes = fbs
fileName = file.Name()
{{/isFile}}
{{^isFile}}formParams["{{paramName}}"] = {{paramName}}
{{/isFile}}
{{/formParams}}
}
_sling = _sling.BodyForm(&FormParams{ {{#formParams}}{{vendorExtensions.x-exportParamName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/formParams}} })
{{/hasFormParams}}
{{#hasBodyParam}}{{#bodyParams}}// body params
_sling = _sling.BodyJSON({{paramName}})
{{/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)
// 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 {
return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err
}
{{#returnType}}
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))
}
}
}
err = json.Unmarshal(httpResponse.Body(), &successPayload)
{{/returnType}}
return {{#returnType}}*successPayload, {{/returnType}}err
return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err
}
{{/operation}}
{{/operations}}

View File

@ -2,13 +2,18 @@ package {{packageName}}
import (
"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){
return ""
}
@ -19,7 +24,7 @@ func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
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){
return ""
}
@ -39,3 +44,80 @@ func contains(source []string, containvalue string) bool {
}
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 {
UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
ApiKeyPrefix map[string] string `json:"apiKeyPrefix,omitempty"`
ApiKey map[string] string `json:"apiKey,omitempty"`
Debug bool `json:"debug,omitempty"`
APIKeyPrefix map[string] string `json:"APIKeyPrefix,omitempty"`
APIKey map[string] string `json:"APIKey,omitempty"`
debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
Timeout int `json:"timeout,omitempty"`
@ -19,17 +19,17 @@ type Configuration struct {
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
ApiClient ApiClient `json:"apiClient,omitempty"`
APIClient APIClient `json:"APIClient,omitempty"`
}
func NewConfiguration() *Configuration {
return &Configuration{
BasePath: "{{basePath}}",
UserName: "",
Debug: false,
debug: false,
DefaultHeader: make(map[string]string),
ApiKey: make(map[string]string),
ApiKeyPrefix: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
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
}
func (c *Configuration) GetApiKeyWithPrefix(apiKeyIdentifier string) string {
if c.ApiKeyPrefix[apiKeyIdentifier] != ""{
return c.ApiKeyPrefix[apiKeyIdentifier] + " " + c.ApiKey[apiKeyIdentifier]
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[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}}DeserializationErrorDomainKey = @"{{classPrefix}}DeserializationErrorDomainKey";
NSInteger const {{classPrefix}}TypeMismatchErrorCode = 143553;
static long requestId = 0;
static bool offlineState = false;
static NSMutableSet * queuedRequests = nil;
@ -288,13 +292,7 @@ static void (^reachabilityChangeBlock)(int);
#pragma mark - Deserialize methods
- (id) deserialize:(id) data class:(NSString *) class {
NSRegularExpression *regexp = nil;
NSTextCheckingResult *match = nil;
NSMutableArray *resultArray = nil;
NSMutableDictionary *resultDict = nil;
NSString *innerType = nil;
- (id) deserialize:(id) data class:(NSString *) class error:(NSError **) error {
// return nil if data is nil or class is nil
if (!data || !class) {
return nil;
@ -310,6 +308,12 @@ static void (^reachabilityChangeBlock)(int);
return data;
}
NSRegularExpression *regexp = nil;
NSTextCheckingResult *match = nil;
NSMutableArray *resultArray = nil;
NSMutableDictionary *resultDict = nil;
NSString *innerType = nil;
// list of models
NSString *arrayOfModelsPat = @"NSArray<(.+)>";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat
@ -321,14 +325,25 @@ static void (^reachabilityChangeBlock)(int);
range:NSMakeRange(0, [class length])];
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;
innerType = [class substringWithRange:[match rangeAtIndex:1]];
resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]];
[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;
}
@ -348,7 +363,12 @@ static void (^reachabilityChangeBlock)(int);
resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]];
[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;
@ -369,7 +389,12 @@ static void (^reachabilityChangeBlock)(int);
resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]];
[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;
@ -407,7 +432,7 @@ static void (^reachabilityChangeBlock)(int);
// model
Class ModelClass = NSClassFromString(class);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [[ModelClass alloc] initWithDictionary:data error:nil];
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
}
return nil;
@ -635,7 +660,12 @@ static void (^reachabilityChangeBlock)(int);
}
else {
[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;

View File

@ -25,6 +25,16 @@
*/
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
*/
@ -171,8 +181,9 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*
* @param data The data will be deserialized.
* @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

View File

@ -31,6 +31,7 @@ Then either install the gem locally:
```shell
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/).

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
def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: {{classname}}#{{operationId}} ..."
@api_client.config.logger.debug "Calling API: {{classname}}.{{operationId}} ..."
end
{{#allParams}}{{#required}}
{{#allParams}}
{{#required}}
# 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}}})
fail "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}}'
fail ArgumentError, "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"
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
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}
{{#vars}}
if attributes[:'{{{baseName}}}']
{{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array)
if attributes.has_key?(:'{{{baseName}}}')
{{#isContainer}}
if (value = attributes[:'{{{baseName}}}']).is_a?(Array)
self.{{{name}}} = value
end{{/isContainer}}{{^isContainer}}self.{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}{{#defaultValue}}
else
self.{{{name}}} = {{{defaultValue}}}{{/defaultValue}}
end
{{/isContainer}}
{{^isContainer}}
self.{{{name}}} = attributes[:'{{{baseName}}}']
{{/isContainer}}
{{#defaultValue}}
else
self.{{{name}}} = {{{defaultValue}}}
{{/defaultValue}}
end
{{/vars}}
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).
# @param [Object] {{{name}}} Object to be assigned
def {{{name}}}=({{{name}}})
allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]
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
@{{{name}}} = {{{name}}}
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.
# @param [Object] Object to be compared
def ==(o)

View File

@ -137,9 +137,22 @@ class Decoders {
// Decoder for {{{classname}}}
Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in
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}}
instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? ""){{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/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}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? "") {{/isEnum}}{{^isEnum}}
instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]){{/isEnum}}{{/vars}}
{{/unwrapRequired}}
return instance
}{{/model}}
{{/models}}

View File

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

View File

@ -21,15 +21,24 @@ public class {{classname}}: JSONEncodable {
{{#vars}}
{{#isEnum}}
{{#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}}
{{#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}}
{{/vars}}
{{^unwrapRequired}}
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
func encodeToJSON() -> AnyObject {

View File

@ -559,6 +559,97 @@ paths:
description: Invalid username supplied
'404':
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:
petstore_auth:
type: oauth2
@ -755,25 +846,39 @@ definitions:
type: object
required:
- number
- byte
- date
- password
properties:
integer:
type: integer
maximum: 100
minimum: 10
int32:
type: integer
format: int32
maximum: 200
minimum: 20
int64:
type: integer
format: int64
number:
maximum: 543.2
minimum: 32.1
type: number
float:
type: number
format: float
maximum: 987.6
minimum: 54.3
double:
type: number
format: double
maximum: 123.4
minimum: 67.8
string:
type: string
pattern: /[a-z]/i
byte:
type: string
format: byte
@ -786,9 +891,14 @@ definitions:
dateTime:
type: string
format: date-time
uuid:
type: string
format: uuid
password:
type: string
format: password
maxLength: 64
minLength: 10
externalDocs:
description: Find out more about Swagger
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
- 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
## Installation
@ -46,8 +46,8 @@ Class | Method | HTTP request | Description
## Documentation For Models
- [ApiResponse](docs/ApiResponse.md)
- [Category](docs/Category.md)
- [ModelApiResponse](docs/ModelApiResponse.md)
- [Order](docs/Order.md)
- [Pet](docs/Pet.md)
- [Tag](docs/Tag.md)
@ -57,12 +57,6 @@ Class | Method | HTTP request | Description
## Documentation For Authorization
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## petstore_auth
- **Type**: OAuth
@ -72,6 +66,12 @@ Class | Method | HTTP request | Description
- **write:pets**: modify pets in your account
- **read:pets**: read your pets
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## Author

View File

@ -2,13 +2,18 @@ package swagger
import (
"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){
return ""
}
@ -19,7 +24,7 @@ func (c *ApiClient) SelectHeaderContentType(contentTypes []string) string {
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){
return ""
}
@ -39,3 +44,80 @@ func contains(source []string, containvalue string) bool {
}
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
import (
"net/http"
)
type ApiResponse struct {
Code int32 `json:"code,omitempty"`
Type_ string `json:"type,omitempty"`
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 {
UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
ApiKeyPrefix map[string] string `json:"apiKeyPrefix,omitempty"`
ApiKey map[string] string `json:"apiKey,omitempty"`
Debug bool `json:"debug,omitempty"`
APIKeyPrefix map[string] string `json:"APIKeyPrefix,omitempty"`
APIKey map[string] string `json:"APIKey,omitempty"`
debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
Timeout int `json:"timeout,omitempty"`
@ -19,17 +19,17 @@ type Configuration struct {
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
ApiClient ApiClient `json:"apiClient,omitempty"`
APIClient APIClient `json:"APIClient,omitempty"`
}
func NewConfiguration() *Configuration {
return &Configuration{
BasePath: "http://petstore.swagger.io/v2",
UserName: "",
Debug: false,
debug: false,
DefaultHeader: make(map[string]string),
ApiKey: make(map[string]string),
ApiKeyPrefix: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
}
}
@ -42,10 +42,18 @@ func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
func (c *Configuration) GetApiKeyWithPrefix(apiKeyIdentifier string) string {
if c.ApiKeyPrefix[apiKeyIdentifier] != ""{
return c.ApiKeyPrefix[apiKeyIdentifier] + " " + c.ApiKey[apiKeyIdentifier]
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[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)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json
@ -66,7 +66,7 @@ void (empty response body)
[petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
@ -95,7 +95,7 @@ Name | Type | Description | Notes
[petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
@ -124,7 +124,7 @@ Name | Type | Description | Notes
[petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
@ -153,7 +153,7 @@ Name | Type | Description | Notes
[api_key](../README.md#api_key)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
@ -182,7 +182,7 @@ void (empty response body)
[petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: application/xml, application/json
@ -213,7 +213,7 @@ void (empty response body)
[petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **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)
# **UploadFile**
> ApiResponse UploadFile($petId, $additionalMetadata, $file)
> ModelApiResponse UploadFile($petId, $additionalMetadata, $file)
uploads an image
@ -238,13 +238,13 @@ Name | Type | Description | Notes
### Return type
[**ApiResponse**](ApiResponse.md)
[**ModelApiResponse**](ApiResponse.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP reuqest headers
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json

View File

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

View File

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

View File

@ -5,8 +5,8 @@ import (
"fmt"
"encoding/json"
"errors"
"github.com/dghubble/sling"
"os"
"io/ioutil"
)
type PetApi struct {
@ -35,28 +35,34 @@ func NewPetApiWithBasePath(basePath string) *PetApi{
* @param body Pet object that needs to be added to the store
* @return void
*/
func (a PetApi) AddPet (body Pet) (error) {
func (a PetApi) AddPet (body Pet) (APIResponse, error) {
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/pet"
// verify the required parameter 'body' is set
if &body == nil {
return errors.New("Missing required parameter 'body' when calling PetApi->AddPet")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling PetApi->AddPet")
}
_sling := sling.New().Post(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (petstore_auth) required
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// create path and map variables
path := "/v2/pet"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -66,58 +72,33 @@ func (a PetApi) AddPet (body Pet) (error) {
"application/xml",
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
_sling = _sling.BodyJSON(body)
postBody = &body
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Deletes a pet
@ -126,29 +107,35 @@ func (a PetApi) AddPet (body Pet) (error) {
* @param apiKey
* @return void
*/
func (a PetApi) DeletePet (petId int64, apiKey string) (error) {
func (a PetApi) DeletePet (petId int64, apiKey string) (APIResponse, error) {
var httpMethod = "Delete"
// create path and map variables
path := a.Configuration.BasePath + "/pet/{petId}"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
// verify the required parameter 'petId' is set
if &petId == nil {
return errors.New("Missing required parameter 'petId' when calling PetApi->DeletePet")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->DeletePet")
}
_sling := sling.New().Delete(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (petstore_auth) required
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// create path and map variables
path := "/v2/pet/{petId}"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -156,58 +143,33 @@ func (a PetApi) DeletePet (petId int64, apiKey string) (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// header params "api_key"
_sling = _sling.Set("api_key", apiKey)
headerParams["api_key"] = apiKey
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Finds Pets by status
@ -215,89 +177,69 @@ func (a PetApi) DeletePet (petId int64, apiKey string) (error) {
* @param status Status values that need to be considered for filter
* @return []Pet
*/
func (a PetApi) FindPetsByStatus (status []string) ([]Pet, error) {
func (a PetApi) FindPetsByStatus (status []string) ([]Pet, APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := a.Configuration.BasePath + "/pet/findByStatus"
// verify the required parameter 'status' is set
if &status == nil {
return *new([]Pet), errors.New("Missing required parameter 'status' when calling PetApi->FindPetsByStatus")
return *new([]Pet), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'status' when calling PetApi->FindPetsByStatus")
}
_sling := sling.New().Get(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (petstore_auth) required
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// create path and map variables
path := "/v2/pet/findByStatus"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
type QueryParams struct {
Status []string `url:"status,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{ Status: status })
queryParams["status"] = a.Configuration.APIClient.ParameterToString(status)
// to determine the Content-Type header
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new([]Pet)
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Finds Pets by tags
@ -305,89 +247,69 @@ func (a PetApi) FindPetsByStatus (status []string) ([]Pet, error) {
* @param tags Tags to filter by
* @return []Pet
*/
func (a PetApi) FindPetsByTags (tags []string) ([]Pet, error) {
func (a PetApi) FindPetsByTags (tags []string) ([]Pet, APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := a.Configuration.BasePath + "/pet/findByTags"
// verify the required parameter 'tags' is set
if &tags == nil {
return *new([]Pet), errors.New("Missing required parameter 'tags' when calling PetApi->FindPetsByTags")
return *new([]Pet), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'tags' when calling PetApi->FindPetsByTags")
}
_sling := sling.New().Get(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (petstore_auth) required
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// create path and map variables
path := "/v2/pet/findByTags"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
type QueryParams struct {
Tags []string `url:"tags,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{ Tags: tags })
queryParams["tags"] = a.Configuration.APIClient.ParameterToString(tags)
// to determine the Content-Type header
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new([]Pet)
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Find pet by ID
@ -395,28 +317,34 @@ func (a PetApi) FindPetsByTags (tags []string) ([]Pet, error) {
* @param petId ID of pet to return
* @return Pet
*/
func (a PetApi) GetPetById (petId int64) (Pet, error) {
func (a PetApi) GetPetById (petId int64) (Pet, APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := a.Configuration.BasePath + "/pet/{petId}"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
// verify the required parameter 'petId' is set
if &petId == nil {
return *new(Pet), errors.New("Missing required parameter 'petId' when calling PetApi->GetPetById")
return *new(Pet), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->GetPetById")
}
_sling := sling.New().Get(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (api_key) required
// set key with prefix in header
_sling.Set("api_key", a.Configuration.GetApiKeyWithPrefix("api_key"))
headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key")
// create path and map variables
path := "/v2/pet/{petId}"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -424,56 +352,33 @@ func (a PetApi) GetPetById (petId int64) (Pet, error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(Pet)
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Update an existing pet
@ -481,28 +386,34 @@ func (a PetApi) GetPetById (petId int64) (Pet, error) {
* @param body Pet object that needs to be added to the store
* @return void
*/
func (a PetApi) UpdatePet (body Pet) (error) {
func (a PetApi) UpdatePet (body Pet) (APIResponse, error) {
var httpMethod = "Put"
// create path and map variables
path := a.Configuration.BasePath + "/pet"
// verify the required parameter 'body' is set
if &body == nil {
return errors.New("Missing required parameter 'body' when calling PetApi->UpdatePet")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling PetApi->UpdatePet")
}
_sling := sling.New().Put(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (petstore_auth) required
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// create path and map variables
path := "/v2/pet"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -512,58 +423,33 @@ func (a PetApi) UpdatePet (body Pet) (error) {
"application/xml",
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
_sling = _sling.BodyJSON(body)
postBody = &body
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Updates a pet in the store with form data
@ -573,29 +459,35 @@ func (a PetApi) UpdatePet (body Pet) (error) {
* @param status Updated status of the pet
* @return void
*/
func (a PetApi) UpdatePetWithForm (petId int64, name string, status string) (error) {
func (a PetApi) UpdatePetWithForm (petId int64, name string, status string) (APIResponse, error) {
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/pet/{petId}"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
// verify the required parameter 'petId' is set
if &petId == nil {
return errors.New("Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm")
}
_sling := sling.New().Post(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (petstore_auth) required
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// create path and map variables
path := "/v2/pet/{petId}"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -604,61 +496,33 @@ func (a PetApi) UpdatePetWithForm (petId int64, name string, status string) (err
"application/x-www-form-urlencoded",
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
type FormParams struct {
Name string `url:"name,omitempty"`
Status string `url:"status,omitempty"`
}
_sling = _sling.BodyForm(&FormParams{ Name: name,Status: status })
formParams["name"] = name
formParams["status"] = status
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* uploads an image
@ -666,31 +530,37 @@ func (a PetApi) UpdatePetWithForm (petId int64, name string, status string) (err
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return ApiResponse
* @return ModelApiResponse
*/
func (a PetApi) UploadFile (petId int64, additionalMetadata string, file *os.File) (ApiResponse, error) {
func (a PetApi) UploadFile (petId int64, additionalMetadata string, file *os.File) (ModelApiResponse, APIResponse, error) {
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/pet/{petId}/uploadImage"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
// verify the required parameter 'petId' is set
if &petId == nil {
return *new(ApiResponse), errors.New("Missing required parameter 'petId' when calling PetApi->UploadFile")
return *new(ModelApiResponse), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->UploadFile")
}
_sling := sling.New().Post(a.Configuration.BasePath)
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (petstore_auth) required
// oauth required
if a.Configuration.AccessToken != ""{
_sling.Set("Authorization", "Bearer " + a.Configuration.AccessToken)
headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken
}
// create path and map variables
path := "/v2/pet/{petId}/uploadImage"
path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1)
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -699,58 +569,34 @@ func (a PetApi) UploadFile (petId int64, additionalMetadata string, file *os.Fil
"multipart/form-data",
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType)
headerParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
"application/json",
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
type FormParams struct {
AdditionalMetadata string `url:"additionalMetadata,omitempty"`
File *os.File `url:"file,omitempty"`
}
_sling = _sling.BodyForm(&FormParams{ AdditionalMetadata: additionalMetadata,File: file })
formParams["additionalMetadata"] = additionalMetadata
fbs, _ := ioutil.ReadAll(file)
fileBytes = fbs
fileName = file.Name()
var successPayload = new(ApiResponse)
var successPayload = new(ModelApiResponse)
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}

View File

@ -5,7 +5,6 @@ import (
"fmt"
"encoding/json"
"errors"
"github.com/dghubble/sling"
)
type StoreApi struct {
@ -34,23 +33,29 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi{
* @param orderId ID of the order that needs to be deleted
* @return void
*/
func (a StoreApi) DeleteOrder (orderId string) (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)
func (a StoreApi) DeleteOrder (orderId string) (APIResponse, error) {
var httpMethod = "Delete"
// create path and map variables
path := "/v2/store/order/{orderId}"
path := a.Configuration.BasePath + "/store/order/{orderId}"
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
_sling = _sling.Path(path)
// verify the required parameter 'orderId' is set
if &orderId == nil {
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder")
}
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 {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -58,79 +63,60 @@ func (a StoreApi) DeleteOrder (orderId string) (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return map[string]int32
*/
func (a StoreApi) GetInventory () (map[string]int32, error) {
_sling := sling.New().Get(a.Configuration.BasePath)
func (a StoreApi) GetInventory () (map[string]int32, APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := a.Configuration.BasePath + "/store/inventory"
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
// authentication (api_key) required
// set key with prefix in header
_sling.Set("api_key", a.Configuration.GetApiKeyWithPrefix("api_key"))
headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key")
// create path and map variables
path := "/v2/store/inventory"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -138,55 +124,32 @@ func (a StoreApi) GetInventory () (map[string]int32, error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", localVarHttpContentType)
headerParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string {
"application/json",
}
//set Accept header
localVarHttpHeaderAccept := a.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Find purchase order by ID
@ -194,23 +157,29 @@ func (a StoreApi) GetInventory () (map[string]int32, error) {
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
func (a StoreApi) GetOrderById (orderId int64) (Order, error) {
// verify the required parameter 'orderId' is set
if &orderId == nil {
return *new(Order), errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById")
}
_sling := sling.New().Get(a.Configuration.BasePath)
func (a StoreApi) GetOrderById (orderId int64) (Order, APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := "/v2/store/order/{orderId}"
path := a.Configuration.BasePath + "/store/order/{orderId}"
path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1)
_sling = _sling.Path(path)
// 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
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -218,56 +187,33 @@ func (a StoreApi) GetOrderById (orderId int64) (Order, error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Place an order for a pet
@ -275,22 +221,28 @@ func (a StoreApi) GetOrderById (orderId int64) (Order, error) {
* @param body order placed for purchasing the pet
* @return Order
*/
func (a StoreApi) PlaceOrder (body Order) (Order, error) {
func (a StoreApi) PlaceOrder (body Order) (Order, APIResponse, error) {
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/store/order"
// verify the required parameter 'body' is set
if &body == nil {
return *new(Order), errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder")
return *new(Order), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder")
}
_sling := sling.New().Post(a.Configuration.BasePath)
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
path := "/v2/store/order"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -298,56 +250,33 @@ func (a StoreApi) PlaceOrder (body Order) (Order, error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
_sling = _sling.BodyJSON(body)
postBody = &body
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}

View File

@ -5,7 +5,6 @@ import (
"fmt"
"encoding/json"
"errors"
"github.com/dghubble/sling"
)
type UserApi struct {
@ -34,22 +33,28 @@ func NewUserApiWithBasePath(basePath string) *UserApi{
* @param body Created user object
* @return void
*/
func (a UserApi) CreateUser (body User) (error) {
func (a UserApi) CreateUser (body User) (APIResponse, error) {
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/user"
// verify the required parameter 'body' is set
if &body == nil {
return errors.New("Missing required parameter 'body' when calling UserApi->CreateUser")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->CreateUser")
}
_sling := sling.New().Post(a.Configuration.BasePath)
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
path := "/v2/user"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -57,58 +62,33 @@ func (a UserApi) CreateUser (body User) (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
_sling = _sling.BodyJSON(body)
postBody = &body
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Creates list of users with given input array
@ -116,22 +96,28 @@ func (a UserApi) CreateUser (body User) (error) {
* @param body List of user object
* @return void
*/
func (a UserApi) CreateUsersWithArrayInput (body []User) (error) {
func (a UserApi) CreateUsersWithArrayInput (body []User) (APIResponse, error) {
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/user/createWithArray"
// verify the required parameter 'body' is set
if &body == nil {
return errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithArrayInput")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithArrayInput")
}
_sling := sling.New().Post(a.Configuration.BasePath)
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
path := "/v2/user/createWithArray"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -139,58 +125,33 @@ func (a UserApi) CreateUsersWithArrayInput (body []User) (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
_sling = _sling.BodyJSON(body)
postBody = &body
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Creates list of users with given input array
@ -198,22 +159,28 @@ func (a UserApi) CreateUsersWithArrayInput (body []User) (error) {
* @param body List of user object
* @return void
*/
func (a UserApi) CreateUsersWithListInput (body []User) (error) {
func (a UserApi) CreateUsersWithListInput (body []User) (APIResponse, error) {
var httpMethod = "Post"
// create path and map variables
path := a.Configuration.BasePath + "/user/createWithList"
// verify the required parameter 'body' is set
if &body == nil {
return errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput")
}
_sling := sling.New().Post(a.Configuration.BasePath)
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
path := "/v2/user/createWithList"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -221,58 +188,33 @@ func (a UserApi) CreateUsersWithListInput (body []User) (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
_sling = _sling.BodyJSON(body)
postBody = &body
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Delete user
@ -280,23 +222,29 @@ func (a UserApi) CreateUsersWithListInput (body []User) (error) {
* @param username The name that needs to be deleted
* @return void
*/
func (a UserApi) DeleteUser (username string) (error) {
// verify the required parameter 'username' is set
if &username == nil {
return errors.New("Missing required parameter 'username' when calling UserApi->DeleteUser")
}
_sling := sling.New().Delete(a.Configuration.BasePath)
func (a UserApi) DeleteUser (username string) (APIResponse, error) {
var httpMethod = "Delete"
// create path and map variables
path := "/v2/user/{username}"
path := a.Configuration.BasePath + "/user/{username}"
path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", username), -1)
_sling = _sling.Path(path)
// verify the required parameter 'username' is set
if &username == nil {
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->DeleteUser")
}
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 {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -304,56 +252,31 @@ func (a UserApi) DeleteUser (username string) (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Get user by user name
@ -361,23 +284,29 @@ func (a UserApi) DeleteUser (username string) (error) {
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
func (a UserApi) GetUserByName (username string) (User, error) {
// verify the required parameter 'username' is set
if &username == nil {
return *new(User), errors.New("Missing required parameter 'username' when calling UserApi->GetUserByName")
}
_sling := sling.New().Get(a.Configuration.BasePath)
func (a UserApi) GetUserByName (username string) (User, APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := "/v2/user/{username}"
path := a.Configuration.BasePath + "/user/{username}"
path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", username), -1)
_sling = _sling.Path(path)
// verify the required parameter 'username' is set
if &username == nil {
return *new(User), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->GetUserByName")
}
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 {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -385,56 +314,33 @@ func (a UserApi) GetUserByName (username string) (User, error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(User)
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Logs user into the system
@ -443,106 +349,92 @@ func (a UserApi) GetUserByName (username string) (User, error) {
* @param password The password for login in clear text
* @return string
*/
func (a UserApi) LoginUser (username string, password string) (string, error) {
func (a UserApi) LoginUser (username string, password string) (string, APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := a.Configuration.BasePath + "/user/login"
// verify the required parameter 'username' is set
if &username == nil {
return *new(string), errors.New("Missing required parameter 'username' when calling UserApi->LoginUser")
return *new(string), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->LoginUser")
}
// verify the required parameter 'password' is set
if &password == nil {
return *new(string), errors.New("Missing required parameter 'password' when calling UserApi->LoginUser")
return *new(string), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'password' when calling UserApi->LoginUser")
}
_sling := sling.New().Get(a.Configuration.BasePath)
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
path := "/v2/user/login"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
type QueryParams struct {
Username string `url:"username,omitempty"`
Password string `url:"password,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{ Username: username,Password: password })
queryParams["username"] = a.Configuration.APIClient.ParameterToString(username)
queryParams["password"] = a.Configuration.APIClient.ParameterToString(password)
// to determine the Content-Type header
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(string)
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 {
// 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))
}
}
if err != nil {
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
return *successPayload, err
err = json.Unmarshal(httpResponse.Body(), &successPayload)
return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Logs out current logged in user session
*
* @return void
*/
func (a UserApi) LogoutUser () (error) {
_sling := sling.New().Get(a.Configuration.BasePath)
func (a UserApi) LogoutUser () (APIResponse, error) {
var httpMethod = "Get"
// create path and map variables
path := "/v2/user/logout"
path := a.Configuration.BasePath + "/user/logout"
headerParams := make(map[string]string)
queryParams := make(map[string]string)
formParams := make(map[string]string)
var postBody interface{}
var fileName string
var fileBytes []byte
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -550,56 +442,31 @@ func (a UserApi) LogoutUser () (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}
/**
* Updated user
@ -608,27 +475,33 @@ func (a UserApi) LogoutUser () (error) {
* @param body Updated user object
* @return void
*/
func (a UserApi) UpdateUser (username string, body User) (error) {
func (a UserApi) UpdateUser (username string, body User) (APIResponse, error) {
var httpMethod = "Put"
// create path and map variables
path := a.Configuration.BasePath + "/user/{username}"
path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", username), -1)
// verify the required parameter 'username' is set
if &username == nil {
return errors.New("Missing required parameter 'username' when calling UserApi->UpdateUser")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->UpdateUser")
}
// verify the required parameter 'body' is set
if &body == nil {
return errors.New("Missing required parameter 'body' when calling UserApi->UpdateUser")
return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->UpdateUser")
}
_sling := sling.New().Put(a.Configuration.BasePath)
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
path := "/v2/user/{username}"
path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", username), -1)
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
headerParams[key] = a.Configuration.DefaultHeader[key]
}
@ -636,56 +509,31 @@ func (a UserApi) UpdateUser (username string, body User) (error) {
localVarHttpContentTypes := []string {
}
//set Content-Type header
localVarHttpContentType := a.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes)
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
_sling = _sling.Set("Content-Type", 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)
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
_sling = _sling.Set("Accept", localVarHttpHeaderAccept)
headerParams["Accept"] = localVarHttpHeaderAccept
}
// body params
_sling = _sling.BodyJSON(body)
postBody = &body
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(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))
}
}
if err != nil {
return *NewAPIResponse(httpResponse.RawResponse), err
}
return err
return *NewAPIResponse(httpResponse.RawResponse), err
}

View File

@ -4,6 +4,7 @@ import (
sw "./go-petstore"
"github.com/stretchr/testify/assert"
"testing"
"os"
)
func TestAddPet(t *testing.T) {
@ -11,19 +12,36 @@ func TestAddPet(t *testing.T) {
newPet := (sw.Pet{Id: 12830, Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"})
err := s.AddPet(newPet)
apiResponse, err := s.AddPet(newPet)
if err != nil {
t.Errorf("Error while adding pet")
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) {
assert := assert.New(t)
s := sw.NewPetApi()
resp, err := s.GetPetById(12830)
resp, apiResponse, err := s.GetPetById(12830)
if err != nil {
t.Errorf("Error while getting pet by id")
t.Log(err)
@ -34,14 +52,83 @@ func TestGetPetById(t *testing.T) {
//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) {
s := sw.NewPetApi()
err := s.UpdatePetWithForm(12830, "golang", "available")
apiResponse, err := s.UpdatePetWithForm(12830, "golang", "available")
if err != nil {
t.Errorf("Error while updating pet by id")
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")
// test GET
resp, err := s.GetPetById(12830)
fmt.Println("GetPetById: ", resp, err)
resp, err, apiResponse := s.GetPetById(12830)
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 {
swagger_annotations_version = "1.5.0"
jackson_version = "2.4.2"
jersey_version = "1.18"
jodatime_version = "2.3"
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
jersey_version = "1.19.1"
jodatime_version = "2.9.3"
junit_version = "4.12"
}

View File

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

View File

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

View File

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

View File

@ -17,6 +17,7 @@ public class Name {
private Integer name = 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
public boolean equals(java.lang.Object o) {
if (this == o) {
@ -53,12 +71,13 @@ public class Name {
}
Name name = (Name) o;
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
public int hashCode() {
return Objects.hash(name, snakeCase);
return Objects.hash(name, snakeCase, property);
}
@Override
@ -68,6 +87,7 @@ public class Name {
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n");
sb.append(" property: ").append(toIndentedString(property)).append("\n");
sb.append("}");
return sb.toString();
}

View File

@ -94,11 +94,12 @@ if(hasProperty('target') && target == 'android') {
}
ext {
swagger_annotations_version = "1.5.0"
jackson_version = "2.6.3"
feign_version = "8.1.1"
jodatime_version = "2.5"
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
feign_version = "8.16.0"
jodatime_version = "2.9.3"
junit_version = "4.12"
oltu_version = "1.0.1"
}
dependencies {
@ -111,6 +112,7 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
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"
testCompile "junit:junit:$junit_version"
}

View File

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

View File

@ -14,7 +14,7 @@ import feign.codec.EncodeException;
import feign.codec.Encoder;
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 static final String UTF_8 = "utf-8";
private static final String LINE_FEED = "\r\n";

View File

@ -1,6 +1,6 @@
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 {
/**
* 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.model.Pet;
import io.swagger.client.model.ModelApiResponse;
import java.io.File;
import io.swagger.client.model.ModelApiResponse;
import java.util.ArrayList;
import java.util.HashMap;
@ -12,7 +12,7 @@ import java.util.List;
import java.util.Map;
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 {

View File

@ -10,7 +10,7 @@ import java.util.List;
import java.util.Map;
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 {

View File

@ -10,7 +10,7 @@ import java.util.List;
import java.util.Map;
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 {

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 {
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 {
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 {
private Long id = null;

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