diff --git a/bin/swift-petstore.sh b/bin/swift-petstore.sh new file mode 100755 index 00000000000..ce6a7e702f0 --- /dev/null +++ b/bin/swift-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -o samples/client/petstore/swift" + +java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index a2b4258532f..2513bedfcb9 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -3,6 +3,8 @@ package com.wordnik.swagger.codegen; import java.io.File; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -12,12 +14,17 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.annotation.Nullable; + import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.base.Function; +import com.google.common.collect.Lists; import com.wordnik.swagger.codegen.examples.ExampleGenerator; import com.wordnik.swagger.models.ArrayModel; +import com.wordnik.swagger.models.ComposedModel; import com.wordnik.swagger.models.Model; import com.wordnik.swagger.models.ModelImpl; import com.wordnik.swagger.models.Operation; @@ -53,8 +60,9 @@ import com.wordnik.swagger.models.properties.RefProperty; import com.wordnik.swagger.models.properties.StringProperty; import com.wordnik.swagger.util.Json; + public class DefaultCodegen { - Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); protected String outputFolder = ""; protected Set defaultIncludes = new HashSet(); @@ -192,6 +200,7 @@ public class DefaultCodegen { } public String toParamName(String name) { + name = removeNonNameElementToCamelCase(name); if(reservedWords.contains(name)) { return escapeReservedWord(name); } @@ -466,100 +475,28 @@ public class DefaultCodegen { m.classVarName = toVarName(name); m.modelJson = Json.pretty(model); m.externalDocs = model.getExternalDocs(); - int count = 0; if(model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); - CodegenProperty cp = fromProperty(name, arrayProperty); - if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) - m.imports.add(cp.complexType); - m.parent = toInstantiationType(arrayProperty); - String containerType = cp.containerType; - if(instantiationTypes.containsKey(containerType)) - m.imports.add(instantiationTypes.get(containerType)); - if(typeMapping.containsKey(containerType)) { - containerType = typeMapping.get(containerType); - cp.containerType = containerType; - m.imports.add(containerType); - } + addParentContainer(m, name, arrayProperty); } else if (model instanceof RefModel) { // TODO - } - else { + } else if (model instanceof ComposedModel) { + final ComposedModel composed = (ComposedModel) model; + final RefModel parent = (RefModel) composed.getParent(); + final String parentModel = toModelName(parent.getSimpleRef()); + m.parent = parentModel; + addImport(m, parentModel); + final ModelImpl child = (ModelImpl) composed.getChild(); + addVars(m, child.getProperties(), child.getRequired()); + } else { ModelImpl impl = (ModelImpl) model; if(impl.getAdditionalProperties() != null) { MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties()); - CodegenProperty cp = fromProperty(name, mapProperty); - if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) - m.imports.add(cp.complexType); - m.parent = toInstantiationType(mapProperty); - String containerType = cp.containerType; - if(instantiationTypes.containsKey(containerType)) - m.imports.add(instantiationTypes.get(containerType)); - if(typeMapping.containsKey(containerType)) { - containerType = typeMapping.get(containerType); - cp.containerType = containerType; - m.imports.add(containerType); - } - } - if(impl.getProperties() != null && impl.getProperties().size() > 0) { - m.hasVars = true; - m.hasEnums = false; - for(String key: impl.getProperties().keySet()) { - Property prop = impl.getProperties().get(key); - - if(prop == null) { - LOGGER.warn("null property for " + key); - } - else { - CodegenProperty cp; - try{ - cp = fromProperty(key, prop); - } - catch(Exception e) { - System.out.println("failed to process model " + name); - throw new RuntimeException(e); - } - cp.required = null; - if(impl.getRequired() != null) { - for(String req : impl.getRequired()) { - if(key.equals(req)) - cp.required = true; - } - } - if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) { - m.imports.add(cp.complexType); - } - m.vars.add(cp); - count += 1; - if (cp.isEnum) - m.hasEnums = true; - if(count != impl.getProperties().keySet().size()) - cp.hasMore = new Boolean(true); - if(cp.isContainer != null) { - String arrayImport = typeMapping.get("array"); - if(arrayImport != null && - !languageSpecificPrimitives.contains(arrayImport) && - !defaultIncludes.contains(arrayImport)) - m.imports.add(arrayImport); - } - - if(cp.complexType != null && - !languageSpecificPrimitives.contains(cp.complexType) && - !defaultIncludes.contains(cp.complexType)) - m.imports.add(cp.complexType); - - if(cp.baseType != null && - !languageSpecificPrimitives.contains(cp.baseType) && - !defaultIncludes.contains(cp.baseType)) - m.imports.add(cp.baseType); - } - } - } - else { - m.emptyVars = true; + addParentContainer(m, name, mapProperty); } + addVars(m, impl.getProperties(), impl.getRequired()); } return m; } @@ -718,6 +655,7 @@ public class DefaultCodegen { operationId = builder.toString(); LOGGER.warn("generated operationId " + operationId); } + operationId = removeNonNameElementToCamelCase(operationId); op.path = path; op.operationId = toOperationId(operationId); op.summary = escapeText(operation.getSummary()); @@ -1141,6 +1079,62 @@ public class DefaultCodegen { co.baseName = tag; } + private void addParentContainer(CodegenModel m, String name, Property property) { + final CodegenProperty tmp = fromProperty(name, property); + addImport(m, tmp.complexType); + m.parent = toInstantiationType(property); + final String containerType = tmp.containerType; + final String instantiationType = instantiationTypes.get(containerType); + if (instantiationType != null) { + addImport(m, instantiationType); + } + final String mappedType = typeMapping.get(containerType); + if (mappedType != null) { + addImport(m, mappedType); + } + } + + private void addImport(CodegenModel m, String type) { + if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { + m.imports.add(type); + } + } + + private void addVars(CodegenModel m, Map properties, Collection required) { + if (properties != null && properties.size() > 0) { + m.hasVars = true; + m.hasEnums = false; + final int totalCount = properties.size(); + final Set mandatory = required == null ? Collections. emptySet() : new HashSet(required); + int count = 0; + for (Map.Entry entry : properties.entrySet()) { + final String key = entry.getKey(); + final Property prop = entry.getValue(); + + if (prop == null) { + LOGGER.warn("null property for " + key); + } else { + final CodegenProperty cp = fromProperty(key, prop); + cp.required = mandatory.contains(key) ? true : null; + if (cp.isEnum) { + m.hasEnums = true; + } + count += 1; + if (count != totalCount) + cp.hasMore = true; + if (cp.isContainer != null) { + addImport(m, typeMapping.get("array")); + } + addImport(m, cp.baseType); + addImport(m, cp.complexType); + m.vars.add(cp); + } + } + } else { + m.emptyVars = true; + } + } + /* underscore and camelize are copied from Twitter elephant bird * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java */ @@ -1166,6 +1160,26 @@ public class DefaultCodegen { return word; } + /** + * Remove characters not suitable for variable or method name from the input and camelize it + * @param name + * @return + */ + public String removeNonNameElementToCamelCase(String name) { + String nonNameElementPattern = "[-_:;#]"; + name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function() { + @Nullable + @Override + public String apply(String input) { + return StringUtils.capitalize(input); + } + }), ""); + if (name.length() > 0) { + name = name.substring(0, 1).toLowerCase() + name.substring(1); + } + return name; + } + public static String camelize(String word) { return camelize(word, false); } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java index 5060899d498..9de427058a1 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java @@ -83,6 +83,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("file", "string"); // path to file typeMapping.put("array", "List"); typeMapping.put("map", "Dictionary"); + typeMapping.put("object", "Object"); } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java new file mode 100644 index 00000000000..e763c51e1ac --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java @@ -0,0 +1,250 @@ +package com.wordnik.swagger.codegen.languages; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.Operation; +import com.wordnik.swagger.models.parameters.HeaderParameter; +import com.wordnik.swagger.models.parameters.Parameter; +import com.wordnik.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; + +import javax.annotation.Nullable; +import java.util.*; +import java.io.File; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { + private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); + protected String sourceFolder = "Classes/Swaggers"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "swift"; + } + + public String getHelp() { + return "Generates a swift client library."; + } + + public SwiftGenerator() { + super(); + outputFolder = "generated-code/swift"; + modelTemplateFiles.put("model.mustache", ".swift"); + apiTemplateFiles.put("api.mustache", ".swift"); + templateDir = "swift"; + apiPackage = "/APIs"; + modelPackage = "/Models"; + + // Inject application name + String appName = System.getProperty("appName"); + if (appName == null) { + appName = "SwaggerClient"; + } + additionalProperties.put("projectName", appName); + + // Inject base url override + String basePathOverride = System.getProperty("basePathOverride"); + if (basePathOverride != null) { + additionalProperties.put("basePathOverride", basePathOverride); + } + + sourceFolder = appName + "/" + sourceFolder; + + supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); + supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "Int", + "Float", + "Double", + "Bool", + "Void", + "String", + "Character") + ); + defaultIncludes = new HashSet( + Arrays.asList( + "NSDate", + "Array", + "Dictionary", + "Set", + "Any", + "Empty", + "AnyObject") + ); + reservedWords = new HashSet( + Arrays.asList( + "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", + "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", + "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", + "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", + "required", "right", "set", "Type", "unowned", "weak") + ); + + typeMapping = new HashMap(); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("date", "NSDate"); + typeMapping.put("Date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); + typeMapping.put("boolean", "Bool"); + typeMapping.put("string", "String"); + typeMapping.put("char", "Character"); + typeMapping.put("short", "Int"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("Integer", "Int"); + typeMapping.put("float", "Float"); + typeMapping.put("number", "Double"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "AnyObject"); + typeMapping.put("file", "NSData"); + + importMapping = new HashMap(); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "[String:" + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toDefaultValue(Property p) { + // nil + return null; + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "[String:" + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "[" + inner + "]"; + } + return null; + } + + @Override + public CodegenProperty fromProperty(String name, Property p) { + CodegenProperty codegenProperty = super.fromProperty(name, p); + if (codegenProperty.isEnum) { + List> swiftEnums = new ArrayList>(); + List values = (List) codegenProperty.allowableValues.get("values"); + for (String value : values) { + Map map = new HashMap(); + map.put("enum", StringUtils.capitalize(value)); + map.put("raw", value); + swiftEnums.add(map); + } + codegenProperty.allowableValues.put("values", swiftEnums); + codegenProperty.datatypeWithEnum = + StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); + } + return codegenProperty; + } + + @Override + public String toApiName(String name) { + if(name.length() == 0) + return "DefaultAPI"; + return initialCaps(name) + "API"; + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + path = normalizePath(path); + List parameters = operation.getParameters(); + parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { + @Override + public boolean apply(@Nullable Parameter parameter) { + return !(parameter instanceof HeaderParameter); + } + })); + operation.setParameters(parameters); + return super.fromOperation(path, httpMethod, operation, definitions); + } + + private static String normalizePath(String path) { + StringBuilder builder = new StringBuilder(); + + int cursor = 0; + Matcher matcher = PATH_PARAM_PATTERN.matcher(path); + boolean found = matcher.find(); + while (found) { + String stringBeforeMatch = path.substring(cursor, matcher.start()); + builder.append(stringBeforeMatch); + + String group = matcher.group().substring(1, matcher.group().length() - 1); + group = camelize(group, true); + builder + .append("{") + .append(group) + .append("}"); + + cursor = matcher.end(); + found = matcher.find(); + } + + String stringAfterMatch = path.substring(cursor); + builder.append(stringAfterMatch); + + return builder.toString(); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache index 94e8f45782d..f1025bc88d3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache @@ -18,6 +18,7 @@ import javax.ws.rs.core.MediaType; import java.util.Collection; import java.util.Map; +import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.Date; @@ -198,47 +199,42 @@ public class ApiInvoker { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(method)) { - if(body == null) + if (contentType.startsWith("application/x-www-form-urlencoded")) { + String encodedFormParams = this + .getXWWWFormUrlencodedParams(formParams); + response = builder.type(contentType).post(ClientResponse.class, + encodedFormParams); + } else if (body == null) { response = builder.post(ClientResponse.class, null); - else if(body instanceof FormDataMultiPart) { + } else if(body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); } else response = builder.type(contentType).post(ClientResponse.class, serialize(body)); } else if ("PUT".equals(method)) { - if(body == null) + if ("application/x-www-form-urlencoded".equals(contentType)) { + String encodedFormParams = this + .getXWWWFormUrlencodedParams(formParams); + response = builder.type(contentType).put(ClientResponse.class, + encodedFormParams); + } else if(body == null) { response = builder.put(ClientResponse.class, serialize(body)); - else { - if("application/x-www-form-urlencoded".equals(contentType)) { - StringBuilder formParamBuilder = new StringBuilder(); - - // encode the form params - for(String key : formParams.keySet()) { - String value = formParams.get(key); - if(value != null && !"".equals(value.trim())) { - if(formParamBuilder.length() > 0) { - formParamBuilder.append("&"); - } - try { - formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8")); - } - catch (Exception e) { - // move on to next - } - } - } - response = builder.type(contentType).put(ClientResponse.class, formParamBuilder.toString()); - } - else + } else { response = builder.type(contentType).put(ClientResponse.class, serialize(body)); } } else if ("DELETE".equals(method)) { - if(body == null) + if ("application/x-www-form-urlencoded".equals(contentType)) { + String encodedFormParams = this + .getXWWWFormUrlencodedParams(formParams); + response = builder.type(contentType).delete(ClientResponse.class, + encodedFormParams); + } else if(body == null) { response = builder.delete(ClientResponse.class); - else + } else { response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); + } } else { throw new ApiException(500, "unknown method type " + method); @@ -271,13 +267,37 @@ public class ApiInvoker { } private void processAuthParams(String[] authNames, Map queryParams, Map headerParams) { - for(String authName : authNames) { + for (String authName : authNames) { Authentication auth = Configuration.getAuthentication(authName); - if(auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); + if (auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); auth.processParams(queryParams, headerParams); } } + private String getXWWWFormUrlencodedParams(Map formParams) { + StringBuilder formParamBuilder = new StringBuilder(); + + for (Entry param : formParams.entrySet()) { + String keyStr = ApiInvoker.parameterToString(param.getKey()); + String valueStr = ApiInvoker.parameterToString(param.getValue()); + + try { + formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) + .append("=") + .append(URLEncoder.encode(valueStr, "utf8")); + formParamBuilder.append("&"); + } catch (UnsupportedEncodingException e) { + // move on to next + } + } + String encodedFormParams = formParamBuilder.toString(); + if (encodedFormParams.endsWith("&")) { + encodedFormParams = encodedFormParams.substring(0, + encodedFormParams.length() - 1); + } + return encodedFormParams; + } + private Client getClient(String host) { if(!hostMap.containsKey(host)) { Client client = Client.create(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index a883850de19..a0afd38f634 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -44,7 +44,6 @@ public class {{classname}} { public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws NotFoundException { - // do some magic! return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig index c9dd5111861..73dbeae62ef 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig @@ -18,5 +18,6 @@ com.wordnik.swagger.codegen.languages.StaticDocCodegen com.wordnik.swagger.codegen.languages.StaticHtmlGenerator com.wordnik.swagger.codegen.languages.SwaggerGenerator com.wordnik.swagger.codegen.languages.SwaggerYamlGenerator +com.wordnik.swagger.codegen.languages.SwiftGenerator com.wordnik.swagger.codegen.languages.TizenClientCodegen com.wordnik.swagger.codegen.languages.AkkaScalaClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache index 9beebc19231..9760e44d81a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache @@ -53,10 +53,13 @@ namespace {{invokerPackage}} { /// JSON string /// Object type /// Object representation of the JSON string - public static object Deserialize(string json, Type type) { + public static object Deserialize(string content, Type type) { + if (type.GetType() == typeof(Object)) + return (Object)content; + try { - return JsonConvert.DeserializeObject(json, type); + return JsonConvert.DeserializeObject(content, type); } catch (IOException e) { throw new ApiException(500, e.Message); diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h index 300cd859778..cd6f52db5c6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h @@ -48,6 +48,9 @@ extern NSString *const SWGResponseObjectErrorKey; +(void) configureCacheReachibilityForHost:(NSString*)host; ++(NSString *) selectHeaderAccept:(NSArray *)accepts; ++(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey; diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m index 6942a21c738..15dbee07459 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m @@ -79,6 +79,51 @@ static bool loggingEnabled = true; } } +/* + * Detect `Accept` from accepts + */ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts +{ + if (accepts == nil || [accepts count] == 0) { + return @""; + } + + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerAccepts addObject:[obj lowercaseString]]; + }]; + + + if ([lowerAccepts containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return [lowerAccepts componentsJoinedByString:@", "]; + } +} + +/* + * Detect `Content-Type` from contentTypes + */ ++ (NSString *) selectHeaderContentType:(NSArray *)contentTypes +{ + if (contentTypes == nil || [contentTypes count] == 0) { + return @"application/json"; + } + + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerContentTypes addObject:[obj lowercaseString]]; + }]; + + if ([lowerContentTypes containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return lowerContentTypes[0]; + } +} + -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index e4c85166b8b..b18790e3b6f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -83,12 +83,6 @@ static NSString * basePath = @"{{basePath}}"; {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [SWGApiClient escape:{{paramName}}]]; {{/pathParams}} - NSArray* requestContentTypes = @[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; {{#queryParams}}if({{paramName}} != nil) { {{#collectionFormat}} @@ -102,6 +96,24 @@ static NSString * basePath = @"{{basePath}}"; {{#headerParams}}if({{paramName}} != nil) headerParams[@"{{baseName}}"] = {{paramName}}; {{/headerParams}} + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; id bodyDictionary = nil; {{#bodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index b8b8eff4295..70717056b9e 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -41,7 +41,7 @@ class APIClient { * @param string $host Base url of the API server (optional) */ function __construct($host = null) { - if ($host == null) { + if ($host === null) { $this->host = '{{basePath}}'; } else { $this->host = $host; @@ -92,25 +92,48 @@ class APIClient { } /** - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent($user_agent) { + return $this->user_agent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] */ public function setTimeout($seconds) { - if (!is_numeric($seconds)) - throw new \InvalidArgumentException('Timeout variable must be numeric.'); + if (!is_numeric($seconds) || $seconds < 0) + throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); $this->curl_timeout = $seconds; } + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getTimeout() { + return $this->curl_timeout; + } + + /** * Get API key (with prefix if set) * @param string key name * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { - if (Configuration::$apiKeyPrefix[$apiKey]) { + if (isset(Configuration::$apiKeyPrefix[$apiKey])) { return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else { + } else if (isset(Configuration::$apiKey[$apiKey])) { return Configuration::$apiKey[$apiKey]; + } else { + return; } } @@ -368,7 +391,7 @@ class APIClient { $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name)) { + if (isset($original_property_name) && isset($data->$original_property_name)) { $instance->$property = self::deserialize($data->$original_property_name, $type); } } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 98be8ff3a5c..1c32eeb01c5 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -25,7 +25,32 @@ namespace {{invokerPackage}}; {{#operations}} class {{classname}} { - function __construct($apiClient) { + function __construct($apiClient = null) { + if (null === $apiClient) { + if (Configuration::$apiClient === null) { + Configuration::$apiClient = new APIClient(); // create a new API client if not present + $this->apiClient = Configuration::$apiClient; + } + else + $this->apiClient = Configuration::$apiClient; // use the default one + } else { + $this->apiClient = $apiClient; // use the one provided by the user + } + } + + private $apiClient; // instance of the APIClient + + /** + * get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * set the API client + */ + public function setApiClient($apiClient) { $this->apiClient = $apiClient; } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 9af553702ae..3eaa8dba1f1 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -31,6 +31,16 @@ class Configuration { public static $username = ''; public static $password = ''; + // an instance of APIClient + public static $apiClient; + + /* + * manually initalize API client + */ + public static function init() { + if (self::$apiClient === null) + self::$apiClient = new APIClient(); + } } diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index b853cbc9c95..fc779a66653 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -29,6 +29,8 @@ from six import iteritems from ..util import remove_none +from ..swagger import ApiClient + {{#operations}} class {{classname}}(object): @@ -68,11 +70,13 @@ class {{classname}}(object): files = remove_none(dict({{#formParams}}{{#isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}})) body_params = {{#bodyParam}}params.get('{{paramName}}'){{/bodyParam}}{{^bodyParam}}None{{/bodyParam}} - accepts = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 549106014e3..ab45eace646 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -105,7 +105,7 @@ class ApiClient(object): def to_path_value(self, obj): """ Convert a string or object to a path-friendly value - + :param obj: object or string value :return string: quoted value @@ -253,7 +253,32 @@ class ApiClient(object): return params + @staticmethod + def select_header_accept(accepts): + """ + Return `Accept` based on an array of accepts provided + """ + if not accepts: + return + accepts = list(map(lambda x: x.lower(), accepts)) + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + @staticmethod + def select_header_content_type(content_types): + """ + Return `Content-Type` baseed on an array of content_types provided + """ + if not content_types: + return 'application/json' + content_types = list(map(lambda x: x.lower(), content_types)) + + if 'application/json' in content_types: + return 'application/json' + else: + return content_types[0] diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index ba38a8157b5..e9f90087db1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -12,7 +12,7 @@ module {{moduleName}} {{#allParams}}{{#required}} # @param {{paramName}} {{description}} {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters {{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} -{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -51,8 +51,9 @@ module {{moduleName}} {{/bodyParam}} {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}} - end + {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil{{/returnType}} + end {{/operation}} end {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 9452a10c56a..87b04b5900f 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -30,7 +30,7 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - def {{nickname}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { + def {{nickname}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} /* = {{{defaultValue}}} */{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { // create path and map variables val path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}",apiInvoker.escape({{paramName}})) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache new file mode 100644 index 00000000000..418f1c8512b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache @@ -0,0 +1,21 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } +} diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache new file mode 100644 index 00000000000..aa39ccfcbdd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -0,0 +1,66 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import PromiseKit + +class {{projectName}}API { + static let basePath = "{{^basePathOverride}}{{basePath}}{{/basePathOverride}}{{basePathOverride}}" + static var credential: NSURLCredential? + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encode() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in enumerate(encoded as! [AnyObject]) { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + required init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + } + + func execute() -> Promise> { fatalError("Not implemented") } + + func addHeader(#name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + func addCredential() -> Self { + self.credential = {{projectName}}API.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + + diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache new file mode 100644 index 00000000000..244d816332c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -0,0 +1,79 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.Manager] = [:] + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute() -> Promise> { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let defer = Promise>.defer() + request.responseJSON(options: .AllowFragments) { (req, res, json, error) in + managerStore.removeValueForKey(managerId) + + if let error = error { + defer.reject(error) + return + } + if res!.statusCode >= 400 { + //TODO: Add error entity + let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: [:]) + defer.reject(error) + return + } + + if () is T { + let response = Response(response: res!, body: () as! T) + defer.fulfill(response) + return + } + if let json: AnyObject = json { + let body = Decoders.decode(clazz: T.self, source: json) + let response = Response(response: res!, body: body) + defer.fulfill(response) + return + } + + defer.reject(NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } + return defer.promise + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} + + diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache new file mode 100644 index 00000000000..af74617bcf2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -0,0 +1,2 @@ +github "Alamofire/Alamofire" >= 1.2 +github "mxcl/PromiseKit" >=1.5.3 diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache new file mode 100644 index 00000000000..c937db23fe3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -0,0 +1,52 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +extension Bool: JSONEncodable { + func encode() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encode() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encode() -> AnyObject { return self } +} + +extension Double: JSONEncodable { + func encode() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encode() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encode() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encode() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encode() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache new file mode 100644 index 00000000000..37c497ddcb9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -0,0 +1,124 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encode() -> AnyObject +} + +class Response { + let statusCode: Int + let header: [String: String] + let body: T + + init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + convenience init(response: NSHTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(#clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(#clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(#clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictinoary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictinoary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(#clazz: T.Type, source: AnyObject) -> T { + initialize() + if source is T { + return source as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(#clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(#clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(#clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let dateTimeFormatter = NSDateFormatter() + dateTimeFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" + let dateFormatter = NSDateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + let sourceString = source as! String + if count(sourceString) == 10 { + return dateFormatter.dateFromString(sourceString)! + } + return dateTimeFormatter.dateFromString(sourceString)! + } {{#models}}{{#model}} + + // Decoder for {{{classname}}} + Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in + let sourceDictionary = source as! [NSObject:AnyObject] + var instance = {{classname}}(){{#vars}}{{#isEnum}} + instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#required}}!{{/required}} {{/isEnum}}{{^isEnum}} + instance.{{name}} = Decoders.decode{{^required}}Optional{{/required}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#required}}!{{/required}}){{/isEnum}}{{/vars}} + return instance + }{{/model}} + {{/models}} + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache new file mode 100644 index 00000000000..e24bdae6773 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -0,0 +1,51 @@ +{{#operations}}// +// {{classname}}.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +extension {{projectName}}API { + {{#description}} + /** {{description}} */{{/description}} + class {{classname}}: APIBase { + {{#operation}} + /** + {{#summary}} + {{{summary}}} + {{/summary}} + - {{httpMethod}} {{path}}{{#notes}} + - {{{notes}}}{{/notes}}{{#subresourceOperation}} + - subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}} + - defaultResponse: {{defaultResponse}}{{/defaultResponse}}{{#authMethods}} + - authMethods: {{authMethods}}{{/authMethods}}{{#responseHeaders}} + - responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}} + - examples: {{{examples}}}{{/examples}}{{#externalDocs}} + - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} + {{/hasParams}}{{#allParams}} + :param: {{paramName}} ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/allParams}} + + :returns: Promise> {{description}} + */ + func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} + path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} + let url = {{projectName}}API.basePath + path + {{#bodyParam}} + let parameters = {{paramName}}{{^required}}?{{/required}}.encode() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} + let nillableParameters: [String:AnyObject?] = {{^queryParams}}[:]{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} + "{{paramName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + ]{{/hasMore}}{{/queryParams}} + let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} + + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "{{httpMethod}}", URLString: url, parameters: parameters, isBody: {{^queryParams}}true{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}) + } + {{/operation}} + } +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache new file mode 100644 index 00000000000..a964882c97c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -0,0 +1,35 @@ +{{#models}}{{#model}}// +// {{classname}}.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +{{#description}} + +/** {{description}} */{{/description}} +class {{classname}}: JSONEncodable { +{{#vars}}{{#isEnum}} + enum {{datatypeWithEnum}}: String { {{#allowableValues}}{{#values}} + case {{enum}} = "{{raw}}"{{/values}}{{/allowableValues}} + } + {{/isEnum}}{{/vars}} + {{#vars}}{{#isEnum}}{{#description}}/** {{description}} */ + {{/description}}var {{name}}: {{{datatypeWithEnum}}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}}{{^isEnum}}{{#description}}/** {{description}} */ + {{/description}}var {{name}}: {{{datatype}}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} + {{/vars}} + + // MARK: JSONEncodable + func encode() -> AnyObject { + var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}} + nillableDictionary["{{name}}"] = self.{{name}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} + nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.rawValue{{/isEnum}}{{^isPrimitiveType}} + nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encode(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} + nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encode(){{/isContainer}}{{/vars}} + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +}{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala index 5407202c5d3..09ffbf0e16c 100644 --- a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala +++ b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala @@ -42,17 +42,17 @@ class ExampleGeneratorTest extends FlatSpec with Matchers { item.get("contentType") match { case `xml` => { types += xml - example should be ("\\n" + - " \\n" + - " string\\n" + - " \\n" + - " \\n" + - " \\n" + - " \\n" + - " string\\n" + - " \\n" + - " \\n" + - " \\n" + + example should be ("\n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + "") } case `json` => { diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala new file mode 100644 index 00000000000..1b6cfc0ecfd --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala @@ -0,0 +1,28 @@ +package Java + +import scala.collection.JavaConverters._ + +import org.junit.runner.RunWith +import org.scalatest.FlatSpec +import org.scalatest.Matchers +import org.scalatest.junit.JUnitRunner +import com.wordnik.swagger.codegen.languages.JavaClientCodegen +import com.wordnik.swagger.models.ComposedModel +import com.wordnik.swagger.models.ModelImpl +import com.wordnik.swagger.models.RefModel +import com.wordnik.swagger.models.properties.StringProperty + +@RunWith(classOf[JUnitRunner]) +class JavaInheritanceTest extends FlatSpec with Matchers { + it should "convert a composed model" in { + val model = new ComposedModel().parent(new RefModel("Base")).child(new ModelImpl().additionalProperties(new StringProperty())) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.parent should be("Base") + cm.imports.asScala should be (Set("Base")) + } +} diff --git a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala index 6255c4deacc..4de884885e4 100644 --- a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala @@ -1,4 +1,4 @@ -package objc +package Objc import com.wordnik.swagger.codegen.languages.ObjcClientCodegen import com.wordnik.swagger.util.Json @@ -217,8 +217,8 @@ class ObjcModelTest extends FlatSpec with Matchers { cm.description should be ("an array model") cm.vars.size should be (0) cm.parent should be ("NSMutableArray") - cm.imports.size should be (3) - (cm.imports.asScala.toSet & Set("SWGChildren", "NSArray", "NSMutableArray")).size should be (3) + cm.imports.size should be (1) + (cm.imports.asScala.toSet & Set("SWGChildren")).size should be (1) } it should "convert an map model" in { @@ -234,8 +234,8 @@ class ObjcModelTest extends FlatSpec with Matchers { cm.description should be ("an map model") cm.vars.size should be (0) cm.parent should be ("NSMutableDictionary") - cm.imports.size should be (3) - (cm.imports.asScala.toSet & Set("SWGChildren", "NSDictionary", "NSMutableDictionary")).size should be (3) + cm.imports.size should be (1) + (cm.imports.asScala.toSet & Set("SWGChildren")).size should be (1) } it should "create proper imports per #316" in { diff --git a/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala b/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala index 090e4cd5ffe..39d76ca168c 100644 --- a/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala @@ -1,4 +1,4 @@ -package Java +package scala import com.wordnik.swagger.codegen.languages.ScalaClientCodegen import com.wordnik.swagger.util.Json @@ -218,8 +218,8 @@ class ScalaModelTest extends FlatSpec with Matchers { cm.description should be ("an array model") cm.vars.size should be (0) cm.parent should be ("ListBuffer[Children]") - cm.imports.size should be (3) - (cm.imports.asScala.toSet & Set("List", "ListBuffer", "Children")).size should be (3) + cm.imports.size should be (2) + (cm.imports.asScala.toSet & Set("ListBuffer", "Children")).size should be (2) } it should "convert an map model" in { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs index 144027b2314..8bb36472835 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs @@ -53,10 +53,13 @@ namespace IO.Swagger.Client { /// JSON string /// Object type /// Object representation of the JSON string - public static object Deserialize(string json, Type type) { + public static object Deserialize(string content, Type type) { + if (type.GetType() == typeof(Object)) + return (Object)content; + try { - return JsonConvert.DeserializeObject(json, type); + return JsonConvert.DeserializeObject(content, type); } catch (IOException e) { throw new ApiException(500, e.Message); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java index a667ebf2c65..8ed18b62c15 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java @@ -18,6 +18,7 @@ import javax.ws.rs.core.MediaType; import java.util.Collection; import java.util.Map; +import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.Date; @@ -198,47 +199,42 @@ public class ApiInvoker { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(method)) { - if(body == null) + if (contentType.startsWith("application/x-www-form-urlencoded")) { + String encodedFormParams = this + .getXWWWFormUrlencodedParams(formParams); + response = builder.type(contentType).post(ClientResponse.class, + encodedFormParams); + } else if (body == null) { response = builder.post(ClientResponse.class, null); - else if(body instanceof FormDataMultiPart) { + } else if(body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); } else response = builder.type(contentType).post(ClientResponse.class, serialize(body)); } else if ("PUT".equals(method)) { - if(body == null) + if ("application/x-www-form-urlencoded".equals(contentType)) { + String encodedFormParams = this + .getXWWWFormUrlencodedParams(formParams); + response = builder.type(contentType).put(ClientResponse.class, + encodedFormParams); + } else if(body == null) { response = builder.put(ClientResponse.class, serialize(body)); - else { - if("application/x-www-form-urlencoded".equals(contentType)) { - StringBuilder formParamBuilder = new StringBuilder(); - - // encode the form params - for(String key : formParams.keySet()) { - String value = formParams.get(key); - if(value != null && !"".equals(value.trim())) { - if(formParamBuilder.length() > 0) { - formParamBuilder.append("&"); - } - try { - formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8")); - } - catch (Exception e) { - // move on to next - } - } - } - response = builder.type(contentType).put(ClientResponse.class, formParamBuilder.toString()); - } - else + } else { response = builder.type(contentType).put(ClientResponse.class, serialize(body)); } } else if ("DELETE".equals(method)) { - if(body == null) + if ("application/x-www-form-urlencoded".equals(contentType)) { + String encodedFormParams = this + .getXWWWFormUrlencodedParams(formParams); + response = builder.type(contentType).delete(ClientResponse.class, + encodedFormParams); + } else if(body == null) { response = builder.delete(ClientResponse.class); - else + } else { response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); + } } else { throw new ApiException(500, "unknown method type " + method); @@ -271,13 +267,37 @@ public class ApiInvoker { } private void processAuthParams(String[] authNames, Map queryParams, Map headerParams) { - for(String authName : authNames) { + for (String authName : authNames) { Authentication auth = Configuration.getAuthentication(authName); - if(auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); + if (auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); auth.processParams(queryParams, headerParams); } } + private String getXWWWFormUrlencodedParams(Map formParams) { + StringBuilder formParamBuilder = new StringBuilder(); + + for (Entry param : formParams.entrySet()) { + String keyStr = ApiInvoker.parameterToString(param.getKey()); + String valueStr = ApiInvoker.parameterToString(param.getValue()); + + try { + formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) + .append("=") + .append(URLEncoder.encode(valueStr, "utf8")); + formParamBuilder.append("&"); + } catch (UnsupportedEncodingException e) { + // move on to next + } + } + String encodedFormParams = formParamBuilder.toString(); + if (encodedFormParams.endsWith("&")) { + encodedFormParams = encodedFormParams.substring(0, + encodedFormParams.length() - 1); + } + return encodedFormParams; + } + private Client getClient(String host) { if(!hostMap.containsKey(host)) { Client client = Client.create(); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java index ccb73755d28..7250a5b445e 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -112,7 +112,7 @@ public class PetApiTest { api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); Pet updated = api.getPetById(fetched.getId()); - assertEquals(updated.getName(), fetched.getName()); + assertEquals(updated.getName(), "furt"); } @Test diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index a3f7b4cae6b..723caec2cdb 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -8,6 +8,7 @@ /* Begin PBXBuildFile section */ BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; }; + CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF31D0981B105E4B00509935 /* SWGApiClientTest.m */; }; CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; }; @@ -55,6 +56,7 @@ /* Begin PBXFileReference section */ 73DA4F1067C343C3962F1542 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; A425648B5C0A4849C7668069 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + CF31D0981B105E4B00509935 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = ""; }; CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JSONValueTransformer+ISO8601.h"; sourceTree = ""; }; CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JSONValueTransformer+ISO8601.m"; sourceTree = ""; }; E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; @@ -207,6 +209,7 @@ isa = PBXGroup; children = ( EA8CD3EB1AC274BE00C47D0B /* PetApiTest.h */, + CF31D0981B105E4B00509935 /* SWGApiClientTest.m */, EA6699C71811D2FB00A70D03 /* PetApiTest.m */, EA6699C21811D2FB00A70D03 /* Supporting Files */, ); @@ -417,6 +420,7 @@ EAB26B0C1AC8DF78002F5C7A /* PetApiTest.h in Sources */, CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */, EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */, + CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/SWGApiClientTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/SWGApiClientTest.m new file mode 100644 index 00000000000..0464bf569e9 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/SWGApiClientTest.m @@ -0,0 +1,59 @@ +#import +#import +#import "SWGApiClient.h" + +@interface SWGApiClientTest : XCTestCase + +@end + +@implementation SWGApiClientTest + +- (void)setUp { + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testSelectHeaderAccept { + NSArray *accepts = nil; + + accepts = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/json", @"application/xml"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"APPLICATION/xml", @"APPLICATION/json"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"text/plain", @"application/xml"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"text/plain, application/xml"); + + accepts = @[]; + XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @""); +} + +- (void)testSelectHeaderContentType { + NSArray *contentTypes = nil; + + contentTypes = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/json", @"application/xml"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"APPLICATION/xml", @"APPLICATION/json"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"text/plain", @"application/xml"]; + XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"text/plain"); + + contentTypes = @[]; + XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); +} + +@end diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock index fe43a2c80eb..6ac776ab37a 100644 --- a/samples/client/petstore/objc/Podfile.lock +++ b/samples/client/petstore/objc/Podfile.lock @@ -1,23 +1,23 @@ PODS: - - AFNetworking (2.5.3): - - AFNetworking/NSURLConnection (= 2.5.3) - - AFNetworking/NSURLSession (= 2.5.3) - - AFNetworking/Reachability (= 2.5.3) - - AFNetworking/Security (= 2.5.3) - - AFNetworking/Serialization (= 2.5.3) - - AFNetworking/UIKit (= 2.5.3) - - AFNetworking/NSURLConnection (2.5.3): + - AFNetworking (2.5.4): + - AFNetworking/NSURLConnection (= 2.5.4) + - AFNetworking/NSURLSession (= 2.5.4) + - AFNetworking/Reachability (= 2.5.4) + - AFNetworking/Security (= 2.5.4) + - AFNetworking/Serialization (= 2.5.4) + - AFNetworking/UIKit (= 2.5.4) + - AFNetworking/NSURLConnection (2.5.4): - AFNetworking/Reachability - AFNetworking/Security - AFNetworking/Serialization - - AFNetworking/NSURLSession (2.5.3): + - AFNetworking/NSURLSession (2.5.4): - AFNetworking/Reachability - AFNetworking/Security - AFNetworking/Serialization - - AFNetworking/Reachability (2.5.3) - - AFNetworking/Security (2.5.3) - - AFNetworking/Serialization (2.5.3) - - AFNetworking/UIKit (2.5.3): + - AFNetworking/Reachability (2.5.4) + - AFNetworking/Security (2.5.4) + - AFNetworking/Serialization (2.5.4) + - AFNetworking/UIKit (2.5.4): - AFNetworking/NSURLConnection - AFNetworking/NSURLSession - ISO8601 (0.2.0) @@ -29,8 +29,8 @@ DEPENDENCIES: - JSONModel (~> 1.0) SPEC CHECKSUMS: - AFNetworking: e1d86c2a96bb5d2e7408da36149806706ee122fe + AFNetworking: 05edc0ac4c4c8cf57bcf4b84be5b0744b6d8e71e ISO8601: 962282de75074c38bbfaa7b133b0e743ed6deb8d JSONModel: ec77e9865236a7a09d9cf7668df6b4b328d9ec1d -COCOAPODS: 0.36.0 +COCOAPODS: 0.37.1 diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h index 300cd859778..cd6f52db5c6 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.h +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -48,6 +48,9 @@ extern NSString *const SWGResponseObjectErrorKey; +(void) configureCacheReachibilityForHost:(NSString*)host; ++(NSString *) selectHeaderAccept:(NSArray *)accepts; ++(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey; diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index 6942a21c738..15dbee07459 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -79,6 +79,51 @@ static bool loggingEnabled = true; } } +/* + * Detect `Accept` from accepts + */ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts +{ + if (accepts == nil || [accepts count] == 0) { + return @""; + } + + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerAccepts addObject:[obj lowercaseString]]; + }]; + + + if ([lowerAccepts containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return [lowerAccepts componentsJoinedByString:@", "]; + } +} + +/* + * Detect `Content-Type` from contentTypes + */ ++ (NSString *) selectHeaderContentType:(NSArray *)contentTypes +{ + if (contentTypes == nil || [contentTypes count] == 0) { + return @"application/json"; + } + + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerContentTypes addObject:[obj lowercaseString]]; + }]; + + if ([lowerContentTypes containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return lowerContentTypes[0]; + } +} + -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 1bab76600e2..9f2b79c51f8 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -77,17 +77,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[@"application/json", @"application/xml"]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; id bodyDictionary = nil; @@ -170,17 +182,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[@"application/json", @"application/xml"]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; id bodyDictionary = nil; @@ -263,12 +287,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; if(status != nil) { @@ -280,6 +298,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -352,12 +388,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; if(tags != nil) { @@ -369,6 +399,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -445,17 +493,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -537,17 +597,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSArray* requestContentTypes = @[@"application/x-www-form-urlencoded"]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; id bodyDictionary = nil; @@ -629,12 +701,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; @@ -642,6 +708,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; if(apiKey != nil) headerParams[@"api_key"] = apiKey; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -709,17 +793,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSArray* requestContentTypes = @[@"multipart/form-data"]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"multipart/form-data"]]; id bodyDictionary = nil; diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index 752fc64d601..75875ff4eae 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -74,17 +74,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -150,17 +162,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -261,17 +285,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -349,17 +385,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index faa086c5d35..3e87268a4c6 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -76,17 +76,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -169,17 +181,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -262,17 +286,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -357,12 +393,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; if(username != nil) { @@ -376,6 +406,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -445,17 +493,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -519,17 +579,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -609,17 +681,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; @@ -706,17 +790,29 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; - NSArray* requestContentTypes = @[]; - NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; - - NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; - NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; id bodyDictionary = nil; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 85087520c8f..f7002fba18d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -41,7 +41,7 @@ class APIClient { * @param string $host Base url of the API server (optional) */ function __construct($host = null) { - if ($host == null) { + if ($host === null) { $this->host = 'http://petstore.swagger.io/v2'; } else { $this->host = $host; @@ -92,25 +92,48 @@ class APIClient { } /** - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent($user_agent) { + return $this->user_agent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] */ public function setTimeout($seconds) { - if (!is_numeric($seconds)) - throw new \InvalidArgumentException('Timeout variable must be numeric.'); + if (!is_numeric($seconds) || $seconds < 0) + throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); $this->curl_timeout = $seconds; } + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getTimeout() { + return $this->curl_timeout; + } + + /** * Get API key (with prefix if set) * @param string key name * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { - if (Configuration::$apiKeyPrefix[$apiKey]) { + if (isset(Configuration::$apiKeyPrefix[$apiKey])) { return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else { + } else if (isset(Configuration::$apiKey[$apiKey])) { return Configuration::$apiKey[$apiKey]; + } else { + return; } } @@ -373,7 +396,7 @@ class APIClient { $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name)) { + if (isset($original_property_name) && isset($data->$original_property_name)) { $instance->$property = self::deserialize($data->$original_property_name, $type); } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 9426efa9170..1f91f8d9063 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -31,6 +31,16 @@ class Configuration { public static $username = ''; public static $password = ''; + // an instance of APIClient + public static $apiClient; + + /* + * manually initalize API client + */ + public static function init() { + if (self::$apiClient === null) + self::$apiClient = new APIClient(); + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index eece13acff7..9456f42bc15 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -24,7 +24,32 @@ namespace SwaggerClient; class PetApi { - function __construct($apiClient) { + function __construct($apiClient = null) { + if (null === $apiClient) { + if (Configuration::$apiClient === null) { + Configuration::$apiClient = new APIClient(); // create a new API client if not present + $this->apiClient = Configuration::$apiClient; + } + else + $this->apiClient = Configuration::$apiClient; // use the default one + } else { + $this->apiClient = $apiClient; // use the one provided by the user + } + } + + private $apiClient; // instance of the APIClient + + /** + * get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * set the API client + */ + public function setApiClient($apiClient) { $this->apiClient = $apiClient; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 609e6568ed4..629201965dc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -24,7 +24,32 @@ namespace SwaggerClient; class StoreApi { - function __construct($apiClient) { + function __construct($apiClient = null) { + if (null === $apiClient) { + if (Configuration::$apiClient === null) { + Configuration::$apiClient = new APIClient(); // create a new API client if not present + $this->apiClient = Configuration::$apiClient; + } + else + $this->apiClient = Configuration::$apiClient; // use the default one + } else { + $this->apiClient = $apiClient; // use the one provided by the user + } + } + + private $apiClient; // instance of the APIClient + + /** + * get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * set the API client + */ + public function setApiClient($apiClient) { $this->apiClient = $apiClient; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index 985ed22a40c..0f4a1bf2dac 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -24,7 +24,32 @@ namespace SwaggerClient; class UserApi { - function __construct($apiClient) { + function __construct($apiClient = null) { + if (null === $apiClient) { + if (Configuration::$apiClient === null) { + Configuration::$apiClient = new APIClient(); // create a new API client if not present + $this->apiClient = Configuration::$apiClient; + } + else + $this->apiClient = Configuration::$apiClient; // use the default one + } else { + $this->apiClient = $apiClient; // use the one provided by the user + } + } + + private $apiClient; // instance of the APIClient + + /** + * get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * set the API client + */ + public function setApiClient($apiClient) { $this->apiClient = $apiClient; } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index bf941756fa6..39c5cecd018 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -7,8 +7,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // add a new pet (id 10005) to ensure the pet object is available for all the tests public static function setUpBeforeClass() { - // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + // skip initializing the API client as it should be automatic + //$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); // new pet $new_pet_id = 10005; $new_pet = new SwaggerClient\models\Pet; @@ -23,10 +23,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $category->id = $new_pet_id; // use the same id as pet $category->name = "test php category"; - $new_pet->tags = [$tag]; + $new_pet->tags = array($tag); $new_pet->category = $category; - $pet_api = new SwaggerClient\PetAPI($api_client); + $pet_api = new SwaggerClient\PetAPI(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } @@ -34,25 +34,50 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test static functions defined in APIClient public function testAPIClient() { - # test selectHeaderAccept + // test selectHeaderAccept $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderAccept(array('application/xml','application/json'))); $this->assertSame(NULL, SwaggerClient\APIClient::selectHeaderAccept(array())); $this->assertSame('application/yaml,application/xml', SwaggerClient\APIClient::selectHeaderAccept(array('application/yaml','application/xml'))); - # test selectHeaderContentType + // test selectHeaderContentType $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array('application/xml','application/json'))); $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array())); $this->assertSame('application/yaml,application/xml', SwaggerClient\APIClient::selectHeaderContentType(array('application/yaml','application/xml'))); - # test addDefaultHeader and getDefaultHeader + // test addDefaultHeader and getDefaultHeader SwaggerClient\APIClient::addDefaultHeader('test1', 'value1'); SwaggerClient\APIClient::addDefaultHeader('test2', 200); - $this->assertSame('value1', SwaggerClient\APIClient::getDefaultHeader()['test1']); - $this->assertSame(200, SwaggerClient\APIClient::getDefaultHeader()['test2']); + $defaultHeader = SwaggerClient\APIClient::getDefaultHeader(); + $this->assertSame('value1', $defaultHeader['test1']); + $this->assertSame(200, $defaultHeader['test2']); - # test deleteDefaultHeader + // test deleteDefaultHeader SwaggerClient\APIClient::deleteDefaultHeader('test2'); - $this->assertFalse(isset(SwaggerClient\APIClient::getDefaultHeader()['test2'])); + $defaultHeader = SwaggerClient\APIClient::getDefaultHeader(); + $this->assertFalse(isset($defaultHeader['test2'])); + + $pet_api = new SwaggerClient\PetAPI(); + $pet_api2 = new SwaggerClient\PetAPI(); + $apiClient3 = new SwaggerClient\APIClient(); + $apiClient3->setUserAgent = 'api client 3'; + $apiClient4 = new SwaggerClient\APIClient(); + $apiClient4->setUserAgent = 'api client 4'; + $pet_api3 = new SwaggerClient\PetAPI($apiClient3); + + // same default api client + $this->assertSame($pet_api->getApiClient(), $pet_api2->getApiClient()); + // confirm using the default api client in the Configuration + $this->assertSame($pet_api->getApiClient(), SwaggerClient\Configuration::$apiClient); + // 2 different api clients are not the same + $this->assertNotEquals($apiClient3, $apiClient4); + // customized pet api not using the default (configuration) api client + $this->assertNotEquals($pet_api3->getApiClient(), SwaggerClient\Configuration::$apiClient); + // customied pet api not using the old pet api's api client + $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); + + // both pet api and pet api2 share the same api client and confirm using timeout value + $pet_api->getApiClient()->setTimeout(999); + $this->assertSame(999, $pet_api2->getApiClient()->getTimeout()); } diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 7d46d8b5821..41c206ee6b0 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -3,12 +3,13 @@ require_once('SwaggerClient-php/SwaggerClient.php'); // initialize the API client -$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); -$api_client->addDefaultHeader("test1", "value1"); +//$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); +//$api_client->addDefaultHeader("test1", "value1"); $petId = 10005; // ID of pet that needs to be fetched try { - $pet_api = new SwaggerClient\PetAPI($api_client); + //$pet_api = new SwaggerClient\PetAPI($api_client); + $pet_api = new SwaggerClient\PetAPI(); // return Pet (model) $response = $pet_api->getPetById($petId); var_dump($response); diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index bf8a51d7ca2..a599aeaabc1 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -29,6 +29,8 @@ from six import iteritems from ..util import remove_none +from ..swagger import ApiClient + class PetApi(object): def __init__(self, api_client): @@ -63,11 +65,13 @@ class PetApi(object): files = remove_none(dict()) body_params = params.get('body') - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = ['application/json', 'application/xml'] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type(['application/json', 'application/xml']) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -102,11 +106,13 @@ class PetApi(object): files = remove_none(dict()) body_params = params.get('body') - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = ['application/json', 'application/xml'] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type(['application/json', 'application/xml']) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -141,11 +147,13 @@ class PetApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -182,11 +190,13 @@ class PetApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -227,11 +237,13 @@ class PetApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -274,11 +286,13 @@ class PetApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = ['application/x-www-form-urlencoded'] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type(['application/x-www-form-urlencoded']) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -318,11 +332,13 @@ class PetApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -363,11 +379,13 @@ class PetApi(object): files = remove_none(dict(file=params.get('file'))) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = ['multipart/form-data'] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type(['multipart/form-data']) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index 0df9a84fe75..7f9b852f7ca 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -29,6 +29,8 @@ from six import iteritems from ..util import remove_none +from ..swagger import ApiClient + class StoreApi(object): def __init__(self, api_client): @@ -62,11 +64,13 @@ class StoreApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -103,11 +107,13 @@ class StoreApi(object): files = remove_none(dict()) body_params = params.get('body') - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -148,11 +154,13 @@ class StoreApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -193,11 +201,13 @@ class StoreApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 720843bd508..2471970c436 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -29,6 +29,8 @@ from six import iteritems from ..util import remove_none +from ..swagger import ApiClient + class UserApi(object): def __init__(self, api_client): @@ -63,11 +65,13 @@ class UserApi(object): files = remove_none(dict()) body_params = params.get('body') - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -102,11 +106,13 @@ class UserApi(object): files = remove_none(dict()) body_params = params.get('body') - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -141,11 +147,13 @@ class UserApi(object): files = remove_none(dict()) body_params = params.get('body') - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -181,11 +189,13 @@ class UserApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -221,11 +231,13 @@ class UserApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -264,11 +276,13 @@ class UserApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -310,11 +324,13 @@ class UserApi(object): files = remove_none(dict()) body_params = params.get('body') - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, @@ -353,11 +369,13 @@ class UserApi(object): files = remove_none(dict()) body_params = None - accepts = ['application/json', 'application/xml'] - header_params['Accept'] = ', '.join(accepts) + # HTTP header `Accept` + header_params['Accept'] = ApiClient.select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] - content_types = [] - header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + # HTTP header `Content-Type` + header_params['Content-Type'] = ApiClient.select_header_content_type([]) response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py index 549106014e3..ab45eace646 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py @@ -105,7 +105,7 @@ class ApiClient(object): def to_path_value(self, obj): """ Convert a string or object to a path-friendly value - + :param obj: object or string value :return string: quoted value @@ -253,7 +253,32 @@ class ApiClient(object): return params + @staticmethod + def select_header_accept(accepts): + """ + Return `Accept` based on an array of accepts provided + """ + if not accepts: + return + accepts = list(map(lambda x: x.lower(), accepts)) + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + @staticmethod + def select_header_content_type(content_types): + """ + Return `Content-Type` baseed on an array of content_types provided + """ + if not content_types: + return 'application/json' + content_types = list(map(lambda x: x.lower(), content_types)) + + if 'application/json' in content_types: + return 'application/json' + else: + return content_types[0] diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py new file mode 100644 index 00000000000..9adf7cdb99d --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd SwaggerPetstore-python +$ nosetests -v +""" + +import os +import time +import unittest + +import SwaggerPetstore + +HOST = 'http://petstore.swagger.io/v2' + + +class ApiClientTests(unittest.TestCase): + + def setUp(self): + self.api_client = SwaggerPetstore.ApiClient(HOST) + + def test_select_header_accept(self): + accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] + accept = SwaggerPetstore.ApiClient.select_header_accept(accepts) + self.assertEqual(accept, 'application/json') + + accepts = ['application/json', 'application/xml'] + accept = SwaggerPetstore.ApiClient.select_header_accept(accepts) + self.assertEqual(accept, 'application/json') + + accepts = ['application/xml', 'application/json'] + accept = SwaggerPetstore.ApiClient.select_header_accept(accepts) + self.assertEqual(accept, 'application/json') + + accepts = ['text/plain', 'application/xml'] + accept = SwaggerPetstore.ApiClient.select_header_accept(accepts) + self.assertEqual(accept, 'text/plain, application/xml') + + accepts = [] + accept = SwaggerPetstore.ApiClient.select_header_accept(accepts) + self.assertEqual(accept, None) + + def test_select_header_content_type(self): + content_types = ['APPLICATION/JSON', 'APPLICATION/XML'] + content_type = SwaggerPetstore.ApiClient.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + content_types = ['application/json', 'application/xml'] + content_type = SwaggerPetstore.ApiClient.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + content_types = ['application/xml', 'application/json'] + content_type = SwaggerPetstore.ApiClient.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + content_types = ['text/plain', 'application/xml'] + content_type = SwaggerPetstore.ApiClient.select_header_content_type(content_types) + self.assertEqual(content_type, 'text/plain') + + content_types = [] + content_type = SwaggerPetstore.ApiClient.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp index af7b2371ebc..0be3a197cd1 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -431,7 +431,7 @@ SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) { emit updatePetWithFormSignal(); } void -SWGPetApi::deletePet(QString* api_key, qint64 petId) { +SWGPetApi::deletePet(QString* apiKey, qint64 petId) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.h b/samples/client/petstore/qt5cpp/client/SWGPetApi.h index 2f65cade2c4..488865729b9 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.h @@ -28,7 +28,7 @@ public: void findPetsByTags(QList* tags); void getPetById(qint64 petId); void updatePetWithForm(QString* petId, QString* name, QString* status); - void deletePet(QString* api_key, qint64 petId); + void deletePet(QString* apiKey, qint64 petId); void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file); private: diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb index d89cb6ae566..40e5f1e3177 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb @@ -9,7 +9,7 @@ module SwaggerClient # # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store - # @return void + # @return [nil] def self.update_pet(opts = {}) @@ -37,14 +37,15 @@ module SwaggerClient post_body = Swagger::Request.object_to_http_body(opts[:'body']) - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Add a new pet to the store # # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store - # @return void + # @return [nil] def self.add_pet(opts = {}) @@ -72,14 +73,15 @@ module SwaggerClient post_body = Swagger::Request.object_to_http_body(opts[:'body']) - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Finds Pets by status # Multiple status values can be provided with comma seperated strings # @param [Hash] opts the optional parameters # @option opts [array[string]] :status Status values that need to be considered for filter - # @return array[Pet] + # @return [array[Pet]] def self.find_pets_by_status(opts = {}) @@ -110,13 +112,13 @@ module SwaggerClient response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } - end + end # Finds Pets by tags # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. # @param [Hash] opts the optional parameters # @option opts [array[string]] :tags Tags to filter by - # @return array[Pet] + # @return [array[Pet]] def self.find_pets_by_tags(opts = {}) @@ -147,13 +149,13 @@ module SwaggerClient response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } - end + end # Find pet by ID # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions # @param pet_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters - # @return Pet + # @return [Pet] def self.get_pet_by_id(pet_id, opts = {}) # verify the required parameter 'pet_id' is set @@ -186,7 +188,7 @@ module SwaggerClient response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body obj = Pet.new() and obj.build_from_hash(response) - end + end # Updates a pet in the store with form data # @@ -194,7 +196,7 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @option opts [string] :name Updated name of the pet # @option opts [string] :status Updated status of the pet - # @return void + # @return [nil] def self.update_pet_with_form(pet_id, opts = {}) # verify the required parameter 'pet_id' is set @@ -227,15 +229,16 @@ module SwaggerClient post_body = nil - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Deletes a pet # # @param pet_id Pet id to delete # @param [Hash] opts the optional parameters # @option opts [string] :api_key - # @return void + # @return [nil] def self.delete_pet(pet_id, opts = {}) # verify the required parameter 'pet_id' is set @@ -267,8 +270,9 @@ module SwaggerClient post_body = nil - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # uploads an image # @@ -276,7 +280,7 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @option opts [string] :additional_metadata Additional data to pass to server # @option opts [file] :file file to upload - # @return void + # @return [nil] def self.upload_file(pet_id, opts = {}) # verify the required parameter 'pet_id' is set @@ -309,7 +313,8 @@ module SwaggerClient post_body = nil - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb index 37595c2147e..594c30a0775 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb @@ -8,7 +8,7 @@ module SwaggerClient # Returns pet inventories by status # Returns a map of status codes to quantities # @param [Hash] opts the optional parameters - # @return map[string,int] + # @return [map[string,int]] def self.get_inventory(opts = {}) @@ -38,13 +38,13 @@ module SwaggerClient response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body response.map {|response| obj = map.new() and obj.build_from_hash(response) } - end + end # Place an order for a pet # # @param [Hash] opts the optional parameters # @option opts [Order] :body order placed for purchasing the pet - # @return Order + # @return [Order] def self.place_order(opts = {}) @@ -74,13 +74,13 @@ module SwaggerClient response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body obj = Order.new() and obj.build_from_hash(response) - end + end # Find purchase order by ID # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # @param order_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters - # @return Order + # @return [Order] def self.get_order_by_id(order_id, opts = {}) # verify the required parameter 'order_id' is set @@ -113,13 +113,13 @@ module SwaggerClient response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body obj = Order.new() and obj.build_from_hash(response) - end + end # Delete purchase order by ID # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # @param order_id ID of the order that needs to be deleted # @param [Hash] opts the optional parameters - # @return void + # @return [nil] def self.delete_order(order_id, opts = {}) # verify the required parameter 'order_id' is set @@ -150,7 +150,8 @@ module SwaggerClient post_body = nil - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb index 12a45561e3f..96fe0cabada 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb @@ -9,7 +9,7 @@ module SwaggerClient # This can only be done by the logged in user. # @param [Hash] opts the optional parameters # @option opts [User] :body Created user object - # @return void + # @return [nil] def self.create_user(opts = {}) @@ -37,14 +37,15 @@ module SwaggerClient post_body = Swagger::Request.object_to_http_body(opts[:'body']) - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Creates list of users with given input array # # @param [Hash] opts the optional parameters # @option opts [array[User]] :body List of user object - # @return void + # @return [nil] def self.create_users_with_array_input(opts = {}) @@ -72,14 +73,15 @@ module SwaggerClient post_body = Swagger::Request.object_to_http_body(opts[:'body']) - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Creates list of users with given input array # # @param [Hash] opts the optional parameters # @option opts [array[User]] :body List of user object - # @return void + # @return [nil] def self.create_users_with_list_input(opts = {}) @@ -107,15 +109,16 @@ module SwaggerClient post_body = Swagger::Request.object_to_http_body(opts[:'body']) - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Logs user into the system # # @param [Hash] opts the optional parameters # @option opts [string] :username The user name for login # @option opts [string] :password The password for login in clear text - # @return string + # @return [string] def self.login_user(opts = {}) @@ -147,12 +150,12 @@ module SwaggerClient response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body obj = string.new() and obj.build_from_hash(response) - end + end # Logs out current logged in user session # # @param [Hash] opts the optional parameters - # @return void + # @return [nil] def self.logout_user(opts = {}) @@ -180,14 +183,15 @@ module SwaggerClient post_body = nil - Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Get user by user name # # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters - # @return User + # @return [User] def self.get_user_by_name(username, opts = {}) # verify the required parameter 'username' is set @@ -220,14 +224,14 @@ module SwaggerClient response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body obj = User.new() and obj.build_from_hash(response) - end + end # Updated user # This can only be done by the logged in user. # @param username name that need to be deleted # @param [Hash] opts the optional parameters # @option opts [User] :body Updated user object - # @return void + # @return [nil] def self.update_user(username, opts = {}) # verify the required parameter 'username' is set @@ -258,14 +262,15 @@ module SwaggerClient post_body = Swagger::Request.object_to_http_body(opts[:'body']) - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end # Delete user # This can only be done by the logged in user. # @param username The name that needs to be deleted # @param [Hash] opts the optional parameters - # @return void + # @return [nil] def self.delete_user(username, opts = {}) # verify the required parameter 'username' is set @@ -296,7 +301,8 @@ module SwaggerClient post_body = nil - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + nil + end end end diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index f66f33cf84c..68858c7b6cd 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -75,7 +75,9 @@ describe "Pet" do it "should create a pet" do pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") - SwaggerClient::PetApi.add_pet(:body => pet) + result = SwaggerClient::PetApi.add_pet(:body => pet) + # nothing is returned + result.should be_nil pet = SwaggerClient::PetApi.get_pet_by_id(10002) pet.id.should == 10002 diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index bdf489c08c0..0d0b3c83ed2 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -123,7 +123,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param status Status values that need to be considered for filter * @return List[Pet] */ - def findPetsByStatus (status: List[String] = available) : Option[List[Pet]] = { + def findPetsByStatus (status: List[String] /* = available */) : Option[List[Pet]] = { // create path and map variables val path = "/pet/findByStatus".replaceAll("\\{format\\}","json") @@ -325,11 +325,11 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Deletes a pet * - * @param api_key + * @param apiKey * @param petId Pet id to delete * @return void */ - def deletePet (api_key: String, petId: Long) = { + def deletePet (apiKey: String, petId: Long) = { // create path and map variables val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) @@ -347,7 +347,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", - headerParams += "api_key" -> api_key + headerParams += "api_key" -> apiKey var postBody: AnyRef = null diff --git a/samples/client/petstore/swift/PetstoreClient/Cartfile b/samples/client/petstore/swift/PetstoreClient/Cartfile new file mode 100644 index 00000000000..245a690a74b --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Cartfile @@ -0,0 +1,2 @@ +github "Alamofire/Alamofire" >= 1.2 +github "mxcl/PromiseKit" \ No newline at end of file diff --git a/samples/client/petstore/tizen/client/SamiPetApi.cpp b/samples/client/petstore/tizen/client/SamiPetApi.cpp index 35c4900a9ac..69997d3cee0 100644 --- a/samples/client/petstore/tizen/client/SamiPetApi.cpp +++ b/samples/client/petstore/tizen/client/SamiPetApi.cpp @@ -380,7 +380,7 @@ deletePetProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiErro } void -SamiPetApi::deletePetWithCompletion(String* api_key, Long* petId, void(*success)(SamiError*)) { +SamiPetApi::deletePetWithCompletion(String* apiKey, Long* petId, void(*success)(SamiError*)) { client = new SamiApiClient(); client->success(&deletePetProcessor, (void(*)(void*, SamiError*))success); @@ -388,7 +388,7 @@ SamiPetApi::deletePetWithCompletion(String* api_key, Long* petId, void(*success) headerParams->Construct(); - headerParams->Add(new String("api_key"), api_key); + headerParams->Add(new String("api_key"), apiKey); diff --git a/samples/client/petstore/tizen/client/SamiPetApi.h b/samples/client/petstore/tizen/client/SamiPetApi.h index 10a957a87b8..05844bd88bd 100644 --- a/samples/client/petstore/tizen/client/SamiPetApi.h +++ b/samples/client/petstore/tizen/client/SamiPetApi.h @@ -39,7 +39,7 @@ public: updatePetWithFormWithCompletion(String* petId, String* name, String* status, void(* handler)(SamiError*)); void - deletePetWithCompletion(String* api_key, Long* petId, void(* handler)(SamiError*)); + deletePetWithCompletion(String* apiKey, Long* petId, void(* handler)(SamiError*)); void uploadFileWithCompletion(Long* petId, String* additionalMetadata, SamiFile* file, void(* handler)(SamiError*)); diff --git a/samples/dynamic-html/docs/operations/PetApi.html b/samples/dynamic-html/docs/operations/PetApi.html index 0fd5a9ae3c6..0c7bb8bd189 100644 --- a/samples/dynamic-html/docs/operations/PetApi.html +++ b/samples/dynamic-html/docs/operations/PetApi.html @@ -209,7 +209,7 @@ Header: - api_key + apiKey String

diff --git a/samples/html/index.html b/samples/html/index.html index 9d47aa360eb..3cfd67d8d59 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -235,7 +235,7 @@

Parameters

-
api_key (optional)
+
apiKey (optional)
Header Parameter
petId (required)
@@ -332,7 +332,7 @@ "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-05-21T05:49:06.118+0000" + "shipDate" : "2015-05-23T15:56:49.441+0000" }

Example data

@@ -341,7 +341,7 @@ <id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-05-20T22:49:06.120Z</shipDate> + <shipDate>2015-05-23T08:56:49.444Z</shipDate> <status>string</status> <complete>true</complete> </Order> @@ -375,7 +375,7 @@ "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-05-21T05:49:06.121+0000" + "shipDate" : "2015-05-23T15:56:49.445+0000" }

Example data

@@ -384,7 +384,7 @@ <id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-05-20T22:49:06.122Z</shipDate> + <shipDate>2015-05-23T08:56:49.445Z</shipDate> <status>string</status> <complete>true</complete> </Order> diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index b57a4fd416d..825dec0f766 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -62,6 +62,25 @@ + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiException.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiOriginFilter.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiResponseMessage.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/api/NotFoundException.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..d5fd9c48e07 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,156 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.PetApiService; +import io.swagger.api.factories.PetApiServiceFactory; + +import com.wordnik.swagger.annotations.ApiParam; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Pet; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.*; + +@Path("/pet") + + +@com.wordnik.swagger.annotations.Api(value = "/pet", description = "the pet API") +public class PetApi { + + private final PetApiService delegate = PetApiServiceFactory.getPetApi(); + + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Validation exception"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + throws NotFoundException { + // do some magic! + return delegate.updatePet(body); + } + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) + + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + throws NotFoundException { + // do some magic! + return delegate.addPet(body); + } + @GET + @Path("/findByStatus") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value") }) + + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) + throws NotFoundException { + // do some magic! + return delegate.findPetsByStatus(status); + } + @GET + @Path("/findByTags") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value") }) + + public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) + throws NotFoundException { + // do some magic! + return delegate.findPetsByTags(tags); + } + @GET + @Path("/{petId}") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) + throws NotFoundException { + // do some magic! + return delegate.getPetById(petId); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) + + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathParam("petId") String petId, + @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, + @ApiParam(value = "Updated status of the pet" )@FormParam("status") String status) + throws NotFoundException { + // do some magic! + return delegate.updatePetWithForm(petId,name,status); + } + @DELETE + @Path("/{petId}") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value") }) + + public Response deletePet(@ApiParam(value = "" )@HeaderParam("api_key") String apiKey, + @ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId) + throws NotFoundException { + // do some magic! + return delegate.deletePet(apiKey,petId); + } + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathParam("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" )@FormParam("additionalMetadata") String additionalMetadata, + @ApiParam(value = "file to upload") @FormDataParam("file") InputStream inputStream, + @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail) + throws NotFoundException { + // do some magic! + return delegate.uploadFile(petId,additionalMetadata,fileDetail); + } +} + diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java new file mode 100644 index 00000000000..6e8060269eb --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java @@ -0,0 +1,47 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Pet; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +public abstract class PetApiService { + + public abstract Response updatePet(Pet body) + throws NotFoundException; + + public abstract Response addPet(Pet body) + throws NotFoundException; + + public abstract Response findPetsByStatus(List status) + throws NotFoundException; + + public abstract Response findPetsByTags(List tags) + throws NotFoundException; + + public abstract Response getPetById(Long petId) + throws NotFoundException; + + public abstract Response updatePetWithForm(String petId,String name,String status) + throws NotFoundException; + + public abstract Response deletePet(String apiKey,Long petId) + throws NotFoundException; + + public abstract Response uploadFile(Long petId,String additionalMetadata,FormDataContentDisposition fileDetail) + throws NotFoundException; + +} diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..7c8dff02ffa --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,94 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.StoreApiService; +import io.swagger.api.factories.StoreApiServiceFactory; + +import com.wordnik.swagger.annotations.ApiParam; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.*; + +@Path("/store") + + +@com.wordnik.swagger.annotations.Api(value = "/store", description = "the store API") +public class StoreApi { + + private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); + + @GET + @Path("/inventory") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation") }) + + public Response getInventory() + throws NotFoundException { + // do some magic! + return delegate.getInventory(); + } + @POST + @Path("/order") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order") }) + + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) + throws NotFoundException { + // do some magic! + return delegate.placeOrder(body); + } + @GET + @Path("/order/{orderId}") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) + throws NotFoundException { + // do some magic! + return delegate.getOrderById(orderId); + } + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) + throws NotFoundException { + // do some magic! + return delegate.deleteOrder(orderId); + } +} + diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java new file mode 100644 index 00000000000..5566e9c9b57 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java @@ -0,0 +1,35 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +public abstract class StoreApiService { + + public abstract Response getInventory() + throws NotFoundException; + + public abstract Response placeOrder(Order body) + throws NotFoundException; + + public abstract Response getOrderById(String orderId) + throws NotFoundException; + + public abstract Response deleteOrder(String orderId) + throws NotFoundException; + +} diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..f0c5493f848 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,150 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.UserApiService; +import io.swagger.api.factories.UserApiServiceFactory; + +import com.wordnik.swagger.annotations.ApiParam; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.User; +import java.util.*; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.*; + +@Path("/user") + + +@com.wordnik.swagger.annotations.Api(value = "/user", description = "the user API") +public class UserApi { + + private final UserApiService delegate = UserApiServiceFactory.getUserApi(); + + @POST + + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + + public Response createUser(@ApiParam(value = "Created user object" ) User body) + throws NotFoundException { + // do some magic! + return delegate.createUser(body); + } + @POST + @Path("/createWithArray") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) + throws NotFoundException { + // do some magic! + return delegate.createUsersWithArrayInput(body); + } + @POST + @Path("/createWithList") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) + throws NotFoundException { + // do some magic! + return delegate.createUsersWithListInput(body); + } + @GET + @Path("/login") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied") }) + + public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, + @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) + throws NotFoundException { + // do some magic! + return delegate.loginUser(username,password); + } + @GET + @Path("/logout") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + + public Response logoutUser() + throws NotFoundException { + // do some magic! + return delegate.logoutUser(); + } + @GET + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) + + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) + throws NotFoundException { + // do some magic! + return delegate.getUserByName(username); + } + @PUT + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied") }) + + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, + @ApiParam(value = "Updated user object" ) User body) + throws NotFoundException { + // do some magic! + return delegate.updateUser(username,body); + } + @DELETE + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + @com.wordnik.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) + + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) + throws NotFoundException { + // do some magic! + return delegate.deleteUser(username); + } +} + diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java new file mode 100644 index 00000000000..6a09fcd0feb --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java @@ -0,0 +1,47 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.User; +import java.util.*; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +public abstract class UserApiService { + + public abstract Response createUser(User body) + throws NotFoundException; + + public abstract Response createUsersWithArrayInput(List body) + throws NotFoundException; + + public abstract Response createUsersWithListInput(List body) + throws NotFoundException; + + public abstract Response loginUser(String username,String password) + throws NotFoundException; + + public abstract Response logoutUser() + throws NotFoundException; + + public abstract Response getUserByName(String username) + throws NotFoundException; + + public abstract Response updateUser(String username,User body) + throws NotFoundException; + + public abstract Response deleteUser(String username) + throws NotFoundException; + +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Category.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Order.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Pet.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Tag.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java similarity index 100% rename from samples/server/petstore/jaxrs/src/main/java/io/swagger/model/User.java rename to samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java deleted file mode 100644 index 8abaf768136..00000000000 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java +++ /dev/null @@ -1,167 +0,0 @@ -package io.swagger.api; - -import io.swagger.model.*; - -import com.wordnik.swagger.annotations.ApiParam; - -import com.sun.jersey.multipart.FormDataParam; - -import io.swagger.model.Pet; -import java.io.File; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - -@Path("/pet") - - -@com.wordnik.swagger.annotations.Api(value = "/pet", description = "the pet API") -public class PetApi { - - @PUT - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Validation exception"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) - - public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @POST - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) - - public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @GET - @Path("/findByStatus") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value") }) - - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @GET - @Path("/findByTags") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value") }) - - public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @GET - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) - - public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @POST - @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) - - public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathParam("petId") String petId, - @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, - @ApiParam(value = "Updated status of the pet" )@FormParam("status") String status) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @DELETE - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value") }) - - public Response deletePet(@ApiParam(value = "" )@HeaderParam("api_key") String apiKey, - @ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @POST - @Path("/{petId}/uploadImage") - @Consumes({ "multipart/form-data" }) - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) - - public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathParam("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" )@FormParam("additionalMetadata") String additionalMetadata, - @ApiParam(value = "file to upload") @FormDataParam("file") InputStream inputStream, - @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - -} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java deleted file mode 100644 index 660f6317422..00000000000 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java +++ /dev/null @@ -1,97 +0,0 @@ -package io.swagger.api; - -import io.swagger.model.*; - -import com.wordnik.swagger.annotations.ApiParam; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - -@Path("/store") - - -@com.wordnik.swagger.annotations.Api(value = "/store", description = "the store API") -public class StoreApi { - - @GET - @Path("/inventory") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation") }) - - public Response getInventory() - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @POST - @Path("/order") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order") }) - - public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @GET - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) - - public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @DELETE - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) - - public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - -} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java deleted file mode 100644 index d907b8b579b..00000000000 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java +++ /dev/null @@ -1,161 +0,0 @@ -package io.swagger.api; - -import io.swagger.model.*; - -import com.wordnik.swagger.annotations.ApiParam; - -import com.sun.jersey.multipart.FormDataParam; - -import io.swagger.model.User; -import java.util.*; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - -@Path("/user") - - -@com.wordnik.swagger.annotations.Api(value = "/user", description = "the user API") -public class UserApi { - - @POST - - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) - - public Response createUser(@ApiParam(value = "Created user object" ) User body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @POST - @Path("/createWithArray") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) - - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @POST - @Path("/createWithList") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) - - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @GET - @Path("/login") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied") }) - - public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, - @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @GET - @Path("/logout") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) - - public Response logoutUser() - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @GET - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) - - public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @PUT - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied") }) - - public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, - @ApiParam(value = "Updated user object" ) User body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - - @DELETE - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), - - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) - - public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - -} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java new file mode 100644 index 00000000000..56ad64c3212 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -0,0 +1,14 @@ +package io.swagger.api.factories; + +import io.swagger.api.PetApiService; +import io.swagger.api.impl.PetApiServiceImpl; + +public class PetApiServiceFactory { + + private final static PetApiService service = new PetApiServiceImpl(); + + public static PetApiService getPetApi() + { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java new file mode 100644 index 00000000000..d60aa7d8660 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -0,0 +1,14 @@ +package io.swagger.api.factories; + +import io.swagger.api.StoreApiService; +import io.swagger.api.impl.StoreApiServiceImpl; + +public class StoreApiServiceFactory { + + private final static StoreApiService service = new StoreApiServiceImpl(); + + public static StoreApiService getStoreApi() + { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java new file mode 100644 index 00000000000..5db4914a878 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -0,0 +1,14 @@ +package io.swagger.api.factories; + +import io.swagger.api.UserApiService; +import io.swagger.api.impl.UserApiServiceImpl; + +public class UserApiServiceFactory { + + private final static UserApiService service = new UserApiServiceImpl(); + + public static UserApiService getUserApi() + { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..069a8419623 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,79 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Pet; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +public class PetApiServiceImpl extends PetApiService { + + @Override + public Response updatePet(Pet body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response addPet(Pet body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByStatus(List status) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByTags(List tags) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getPetById(Long petId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updatePetWithForm(String petId,String name,String status) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deletePet(String apiKey,Long petId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response uploadFile(Long petId,String additionalMetadata,FormDataContentDisposition fileDetail) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..84e8938f2f9 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,51 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +public class StoreApiServiceImpl extends StoreApiService { + + @Override + public Response getInventory() + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response placeOrder(Order body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getOrderById(String orderId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteOrder(String orderId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..b7735c7ac9e --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,79 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.User; +import java.util.*; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +public class UserApiServiceImpl extends UserApiService { + + @Override + public Response createUser(User body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithArrayInput(List body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithListInput(List body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response loginUser(String username,String password) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response logoutUser() + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getUserByName(String username) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updateUser(String username,User body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteUser(String username) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + +}